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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { AuthenticationStrategy } from '@loopback/authentication';
import { inject, service } from '@loopback/core';
import { HttpErrors, Request } from '@loopback/rest';
import { Claim, UserProfile } from '@logchain/components/aws';
import { UserService } from '@logchain/services';
import { AuthenticationStrategyBindings, AuthenticationStrategyOptions } from './keys';
import { CompanyRepository, UserViewRepository } from '@logchain/repositories';
import { repository } from '@loopback/repository';
import { AuthError } from './hmac.auth.strategy';
export class ExternalAuthenticationStrategy implements AuthenticationStrategy {
name = 'external-api';
@inject(AuthenticationStrategyBindings.COGNITO_DEFAULT_OPTIONS)
options: AuthenticationStrategyOptions;
constructor(
@service(UserService)
public userService: UserService,
@repository(CompanyRepository)
public comp_repo: CompanyRepository,
@repository(UserViewRepository)
public user_repo: UserViewRepository,
) { }
/**
* Authenticate request
* @param request The request
*/
async authenticate(request: Request): Promise<UserProfile | undefined> {
const identifier_token: string = this.extractCredentials(request);
const company = await this.comp_repo.findOne({ where: { identifier_token } });
if (!company) {
throw new AuthError('Invalid identifier_token');
}
const userProfile = await this.user_repo.findById(company.identifier_user_id) as unknown as UserProfile;
if (!userProfile) {
throw new AuthError('Invalid identifier_user_id');
}
return this.userService.convertToUserProfile(userProfile as unknown as Claim);
}
/**
* Extract a token from the request
* @param request The request
*/
private extractCredentials(request: Request): string {
if (!request.headers['x-api-key']) {
throw new HttpErrors.Unauthorized(`x-api-key header not found.`);
}
if (request.headers['x-api-key'] !== process.env.EXTERNAL_ACCESS_KEY) {
throw new HttpErrors.Unauthorized(`x-api-key header not valid.`);
}
if (!request.path.split('/')[2]) {
throw new HttpErrors.Unauthorized(`identifier_token not found.`);
}
return request.path.split('/')[2];
}
}
|