UNPKG

bauth-js

Version:

A Node.js authentication library for API requests via remote authentication service using Bearer tokens. Compatible with Express and NestJS.

107 lines 3.11 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BAuth = void 0; const axios_1 = __importDefault(require("axios")); class BAuth { constructor(config) { this.token = null; this.config = { timeout: 10000, headers: {}, ...config, }; this.client = axios_1.default.create({ baseURL: this.config.endpoint, timeout: this.config.timeout || 10000, headers: { 'Content-Type': 'application/json', ...this.config.headers, }, }); } /** * Set the Bearer token for authentication */ setToken(token) { this.token = token; } /** * Get the current token */ getToken() { return this.token; } /** * Validate if the current token is valid */ async validate() { if (!this.token) { return { valid: false, error: 'No token provided' }; } try { const response = await this.client.post('/auth/validate', {}, { headers: { Authorization: `Bearer ${this.token}`, }, }); return { valid: response.data.valid || false }; } catch (error) { if (axios_1.default.isAxiosError(error)) { if (error.response?.status === 401) { return { valid: false, error: 'Invalid token' }; } return { valid: false, error: error.message }; } return { valid: false, error: 'Unknown error occurred' }; } } /** * Get authenticated user information */ async user() { if (!this.token) { return { valid: false, error: 'No token provided' }; } try { const response = await this.client.get('/users/me', { headers: { Authorization: `Bearer ${this.token}`, }, }); return { valid: true, user: response.data, }; } catch (error) { if (axios_1.default.isAxiosError(error)) { if (error.response?.status === 401) { return { valid: false, error: 'Invalid token' }; } return { valid: false, error: error.message }; } return { valid: false, error: 'Unknown error occurred' }; } } /** * Authenticate with a token and get user info */ async authenticate(token) { this.setToken(token); return this.user(); } /** * Create a new instance with a token */ static withToken(token, config) { const auth = new BAuth(config); auth.setToken(token); return auth; } } exports.BAuth = BAuth; //# sourceMappingURL=auth.js.map