import { inject } from '@loopback/context'; import { AuthenticationBindings } from '@loopback/authentication'; import { get, post, param, requestBody, } from '@loopback/rest'; import { PasswordServiceBindings, TokenServiceBindings, UserServiceBindings, UserService, TokenService, PasswordService, authenticate, User, UserCredentials, UserProfile, UserCredentialsRequestBody, TokenSchema, ErrorSchema, StatusSchema, } from '../..'; export class AuthController { constructor( @inject(TokenServiceBindings.SERVICE_JWT) private _jwtService: TokenService, @inject(PasswordServiceBindings.SERVICE) private _passService: PasswordService, @inject(UserServiceBindings.SERVICE) private _userService: UserService, ) {} @post('/login/json', { responses: { "200": { description: 'Authentication with credentials in body (recommended, secured)', content: { 'application/json': { schema: TokenSchema, }, }, }, }, }) async login ( @requestBody(UserCredentialsRequestBody) credentials: UserCredentials, ): Promise<{ token: string }> { const user: User = await this._userService.verifyCredentials(credentials); const userProfile: UserProfile = this._userService.convertToUserProfile(user); const token: string = await this.getToken('jwt', userProfile); return { token }; } @post('/login/basic', { responses: { "200": { description: 'Basic HTTP authentication', content: { 'application/json': { schema: TokenSchema, }, }, }, "401": { description: "Unauthorized - invalid credentials", content: { "application/json": { schema: ErrorSchema, }, }, } }, security: [ { basic: ['basic'], }, ], }) @authenticate('basic') async loginBasic ( @inject(AuthenticationBindings.CURRENT_USER) user: User, ): Promise<{ token: string }> { const userProfile: UserProfile = this._userService.convertToUserProfile(user); const token: string = await this.getToken('jwt', userProfile); return { token }; } @post('/logout', { responses: { "200": { description: 'Authentication sign out', content: { 'application/json': { schema: StatusSchema, }, }, }, "401": { description: "Unauthorized - token is invalid/expired or absent", content: { "application/json": { schema: ErrorSchema, }, }, } }, security: [ { jwt: ['jwt'], }, ], }) @authenticate('jwt') async logout ( @inject(AuthenticationBindings.CURRENT_USER) user: User, ): Promise<{ statusCode: boolean }> { const statusCode: boolean = true; console.log(user); return { statusCode }; } async getToken (tokenType: string, userProfile: UserProfile): Promise { const token: string = await this._jwtService.generateToken(userProfile); return token; } }