import { inject } from '@loopback/context'; import { HttpErrors, Request } from '@loopback/rest'; import { AuthenticationStrategy } from '@loopback/authentication'; import { TokenServiceBindings, TokenService } from '../services'; import { UserProfile } from '../data'; export class AuthStrategyJWT implements AuthenticationStrategy { name: string = 'jwt'; constructor( @inject(TokenServiceBindings.SERVICE_JWT) private _tokenService: TokenService, ){} async authenticate (request: Request): Promise { const token: string = this.extractCredentials(request); const userProfile: UserProfile = await this._tokenService.verifyToken(token); return userProfile; } extractCredentials (request: Request) { let token: string = ''; if (request.headers.jwt) { token = request.headers.jwt; } else if (request.headers.authorization) { const authHeader = request.headers.authorization; if (!authHeader.startsWith("JWT")) throw new HttpErrors.Unauthorized(`Error: no valid authorization header`); const parts = authHeader.split(' '); if (parts.length < 2) throw new HttpErrors.Unauthorized(`Error: no token value`); token = parts[1]; } else { throw new HttpErrors.Unauthorized(`Error: no authorization header`); } return token; } }