@takentrade/takentrade-libs
Version:
TakeNTrade shared libraries
67 lines (66 loc) • 2.99 kB
JavaScript
;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TNTAuthGuard = void 0;
const common_1 = require("@nestjs/common");
const passport_1 = require("@nestjs/passport");
const public_decorator_1 = require("../decorators/public.decorator");
/**
* Validates if the decoded JWT payload contains required AuthUser properties.
* @param payload The decoded JWT payload.
* @returns The validated AuthUser object with id, email, phone, isActive, and optional role.
* @throws UnauthorizedException if required properties are missing.
*/
function validateAuthUser(payload) {
if (!payload || typeof payload !== 'object') {
throw new common_1.UnauthorizedException('Invalid token payload');
}
const { id, email, phone, isActive, role } = payload;
if (!id || !email || !phone || isActive === undefined) {
throw new common_1.UnauthorizedException('Token payload missing required properties');
}
return { id, email, phone, isActive, role };
}
/**
* Custom guard to validate JWT tokens and authorize requests using Passport JWT strategy.
* Allows public routes to bypass authentication if decorated with @Public().
*/
let TNTAuthGuard = class TNTAuthGuard extends (0, passport_1.AuthGuard)('jwt') {
reflector;
constructor(reflector) {
super();
this.reflector = reflector;
}
/**
* Determines if the request is authorized based on JWT validation.
* @param context Execution context containing the request.
* @returns True if the request is authorized or public, false otherwise.
* @throws UnauthorizedException if token validation fails.
*/
async canActivate(context) {
const isPublic = this.reflector.getAllAndOverride(public_decorator_1.IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) {
return true;
}
const canActivate = await super.canActivate(context);
if (!canActivate) {
throw new common_1.UnauthorizedException('Invalid or expired token');
}
const request = context.switchToHttp().getRequest();
const user = request.user;
request.user = validateAuthUser(user);
return true;
}
};
exports.TNTAuthGuard = TNTAuthGuard;
exports.TNTAuthGuard = TNTAuthGuard = __decorate([
(0, common_1.Injectable)()
], TNTAuthGuard);