UNPKG

bauth-js

Version:

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

95 lines 3.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CurrentUser = exports.UseBAuth = exports.BAuthGuard = void 0; exports.createBAuthGuard = createBAuthGuard; // Note: This file requires @nestjs/common and @nestjs/core to be installed // It's designed to work with NestJS applications const auth_1 = require("../auth"); class MockUnauthorizedException extends Error { constructor(message) { super(message); this.name = 'UnauthorizedException'; } } class BAuthGuard { constructor(options) { this.options = options; this.auth = new auth_1.BAuth(options); } async canActivate(context) { const request = context.switchToHttp().getRequest(); const token = this.extractToken(context); if (!token) { throw new MockUnauthorizedException('No token provided'); } try { const result = await this.auth.authenticate(token); if (!result.valid) { throw new MockUnauthorizedException(result.error || 'Invalid token'); } // Attach user to request const userProperty = this.options.userProperty || 'user'; request[userProperty] = result.user; request.bauth = { token, user: result.user, }; return true; } catch (error) { if (error instanceof MockUnauthorizedException) { throw error; } throw new MockUnauthorizedException('Authentication error'); } } extractToken(context) { if (this.options.tokenExtractor) { return this.options.tokenExtractor(context); } const request = context.switchToHttp().getRequest(); const authHeader = request.headers.authorization; if (!authHeader || !authHeader.startsWith('Bearer ')) { return null; } return authHeader.substring(7); } } exports.BAuthGuard = BAuthGuard; /** * Decorator to mark routes that require authentication * Note: This is a placeholder. In a real NestJS environment, * you would use the actual NestJS decorators. */ const UseBAuth = (options) => { return (_target, _propertyKey, _descriptor) => { // This is a placeholder implementation // In a real NestJS environment, you would use proper metadata console.log('UseBAuth decorator called with options:', options); }; }; exports.UseBAuth = UseBAuth; /** * Decorator to get the authenticated user * Note: This is a placeholder. In a real NestJS environment, * you would use the actual NestJS decorators. */ const CurrentUser = () => { return (_target, _propertyKey, _parameterIndex) => { // This is a placeholder implementation // In a real NestJS environment, you would use proper metadata console.log('CurrentUser decorator called'); }; }; exports.CurrentUser = CurrentUser; /** * Factory function to create BAuthGuard */ function createBAuthGuard(options) { return class extends BAuthGuard { constructor() { super(options); } }; } //# sourceMappingURL=nest.js.map