import { Controller, Post, Body, Req, HttpException, HttpStatus, Logger, Inject, } from '@nestjs/common'; import { sign, verify } from 'jsonwebtoken'; import * as jwt from 'jsonwebtoken'; import { Request } from 'express'; import { LaunchpadApiClientAuthConfig } from '../models/launchpad.auth.config'; import { LaunchpadApiService } from '../services/launchpad-api/launchpad-api-service'; import { LogBody } from '../models/logbody'; @Controller('auth') export class LaunchpadAuthController { constructor( @Inject('LAUNCHPAD_AUTH_CONFIG') private readonly authConfig: LaunchpadApiClientAuthConfig, private launchpadApiService: LaunchpadApiService ) {} @Post('login') async login(@Body() body: { token: string }): Promise { const claims = verify(body.token, this.authConfig.launchPadJwtSecret) as any; const user = await this.launchpadApiService.getUserByName(body.token); this.launchpadApiService.launchPadLog( new LogBody(user.userName, 'login', `${this.authConfig.apiName} successful login`), ); const access = this.authConfig.customMethods.mutateUserResponseAccess ? this.authConfig.customMethods.mutateUserResponseAccess(user.access) : user.access; return { token: sign({ sub: claims.sub, access: access }, this.authConfig.apiJwtConfig.secret, { expiresIn: this.authConfig.apiJwtConfig.expiry, subject: claims.sub, issuer: this.authConfig.apiJwtConfig.issuer, }), customers: access, }; } @Post('logLogout') async logLogout(@Req() request: Request): Promise { let jwtToken = request.headers['authorization']; if (jwtToken) { jwtToken = jwtToken.replace('Bearer ', ''); try { const claims = jwt.verify(jwtToken, this.authConfig.apiJwtConfig.secret, { ignoreExpiration: false, }) as any; this.launchpadApiService.launchPadLog( new LogBody(claims.sub, 'logout', `${this.authConfig.apiName} user logged out`), ); Logger.log(`Log Logout, user ${claims.sub} logged out`); } catch { Logger.warn(`Log Logout, jwt access claims not validated, token: ${jwtToken}`); throw new HttpException('Forbidden: Jwt Not Verified', HttpStatus.FORBIDDEN); } } else { Logger.warn(`Log Logout, no token on header`); throw new HttpException('Forbidden: Jwt Not Verified', HttpStatus.FORBIDDEN); } } }