All files / src/auth-strategies cognito.auth.strategy.ts

30.3% Statements 10/33
0% Branches 0/16
0% Functions 0/5
26.67% Lines 8/30

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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 811x 1x 1x   1x 1x 1x   1x     1x                                                                                                                                          
import { AuthenticationBindings, AuthenticationMetadata, AuthenticationStrategy } from '@loopback/authentication';
import { inject, service } from '@loopback/core';
import { HttpErrors, Request } from '@loopback/rest';
 
import { AwsCognitoService, AwsServiceBindings, UserProfile } from '@logchain/components/aws';
import { UserService } from '@logchain/services';
import { AuthenticationStrategyBindings, AuthenticationStrategyOptions } from './keys';
 
export class CognitoAuthenticationStrategy implements AuthenticationStrategy {
  name = 'aws-cognito';
  @inject(AuthenticationStrategyBindings.COGNITO_DEFAULT_OPTIONS)
  options: AuthenticationStrategyOptions;
 
  constructor(
    @inject(AwsServiceBindings.COGNITO_SERVICE)
    public cognitoService: AwsCognitoService,
    @service(UserService)
    public userService: UserService,
    @inject(AuthenticationBindings.METADATA)
    private metadata?: AuthenticationMetadata[],
  ) { }
 
  /**
   * Authenticate request
   * @param request The request
   */
  async authenticate(request: Request): Promise<UserProfile | undefined> {
    const token: string = this.extractCredentials(request);
    this.processOptions();
    const payload = await this.cognitoService.verifyToken(token, this.options);
    payload.reason = request.headers['reason'] as string | undefined;
    return this.userService.convertToUserProfile(payload);
  }
 
  /**
   * Extract a token from the request
   * @param request The request
   */
  private extractCredentials(request: Request): string {
    if (!request.headers.authorization) {
      throw new HttpErrors.Unauthorized(`Authorization header not found.`);
    }
 
    // for example : Bearer xxx.yyy.zzz
    const authHeaderValue = request.headers.authorization;
    if (!authHeaderValue.startsWith('Bearer')) {
      throw new HttpErrors.Unauthorized(
        `Authorization header is not of type 'Bearer'.`,
      );
    }
 
    //split the string into 2 parts : 'Bearer' and the `xxx.yyy.zzz`
    const parts = authHeaderValue.split(' ');
    if (parts.length !== 2)
      throw new HttpErrors.Unauthorized(
        `Authorization header value has too many parts. It must follow the pattern: 'Bearer xx.yy.zz' where xx.yy.zz is a valid JWT token.`,
      );
    return parts[1];
  }
 
  /**
   * Process the options
   */
  private processOptions() {
    /**
      Obtain the options object specified in the @authenticate decorator
      of a controller method associated with the current request.
      The AuthenticationMetadata interface contains : strategy:string, options?:object
      We want the options property.
    */
    if (!this.options) this.options = {}; //if no default options were bound, assign empty options object
 
    const metadata = this.metadata?.find(meta => {
      return this.name === meta.strategy;
    });
 
    //override default options with request-level options
    this.options = Object.assign({}, this.options, metadata?.options);
  }
}