All files / src/controllers authentication.controller.ts

100% Statements 15/15
100% Branches 4/4
100% Functions 1/1
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 628x                       8x 8x       8x   8x                       8x           9x 1x         8x 8x             7x       7x   1x        
import {
  controller,
  description,
  HttpError,
  HttpStatus,
  inject,
  MicroserviceRequest,
  post,
  requestBody,
  response,
  summary,
} from "@waytrade/microservice-core";
import {UsernamePassword} from "../models/username-password.model";
import {AuthenticationService} from "../services/authentication.service";
 
/** The user authentication controller. */
@controller("Authentication", "/auth")
export class AuthenticatonController {
  @inject("AuthenticationService")
  private authService!: AuthenticationService;
 
  @post("/password")
  @summary("Login with username and password.")
  @description(
    "Login with username and password and return the Bearer token on authorization header.",
  )
  @requestBody(UsernamePassword)
  @response(
    HttpStatus.UNAUTHORIZED,
    "Unauthorized: wrong username or password.",
  )
  async loginPassword(
    request: MicroserviceRequest,
    params: UsernamePassword,
  ): Promise<void> {
    // verify input
 
    if (!params.password || !params.username) {
      throw new HttpError(HttpStatus.BAD_REQUEST);
    }
 
    // login with password
 
    try {
      const jwt = await this.authService.loginUserPassword(
        params.username,
        params.password,
      );
 
      // set response headers
 
      request.writeResponseHeader(
        "access-control-expose-headers",
        "authorization",
      );
      request.writeResponseHeader("authorization", `Bearer ${jwt}`);
    } catch (err: unknown) {
      throw new HttpError(HttpStatus.UNAUTHORIZED, (<Error>err).message);
    }
  }
}