-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathbearer-token-verify.provider.ts
56 lines (52 loc) · 1.86 KB
/
bearer-token-verify.provider.ts
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
// Copyright (c) 2023 Sourcefuse Technologies
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
import {inject, Provider} from '@loopback/context';
import {repository} from '@loopback/repository';
import {HttpErrors, Request} from '@loopback/rest';
import {AuthenticateErrorKeys, ILogger, LOGGER} from '@sourceloop/core';
import {VerifyFunction} from 'loopback4-authentication';
import moment from 'moment-timezone';
import {JWTVerifierFn} from '../../../providers';
import {AuthCodeBindings} from '../../../providers/keys';
import {RevokedTokenRepository} from '../../../repositories';
import {AuthUser} from '../models/auth-user.model';
export class BearerTokenVerifyProvider
implements Provider<VerifyFunction.BearerFn>
{
constructor(
@repository(RevokedTokenRepository)
public revokedTokenRepository: RevokedTokenRepository,
@inject(LOGGER.LOGGER_INJECT) public logger: ILogger,
@inject(AuthCodeBindings.JWT_VERIFIER)
public jwtVerifier: JWTVerifierFn<AuthUser>,
) {}
value(): VerifyFunction.BearerFn {
return async (token: string, req?: Request) => {
const isRevoked = await this.revokedTokenRepository.get(token);
if (isRevoked?.token) {
throw new HttpErrors.Unauthorized(AuthenticateErrorKeys.TokenRevoked);
}
let user: AuthUser;
try {
user = await this.jwtVerifier(token, {
issuer: process.env.JWT_ISSUER,
algorithms: ['HS256'],
});
} catch (error) {
this.logger.error(JSON.stringify(error));
throw new HttpErrors.Unauthorized('TokenExpired');
}
if (
user.passwordExpiryTime &&
moment().isSameOrAfter(moment(user.passwordExpiryTime))
) {
throw new HttpErrors.Unauthorized(
AuthenticateErrorKeys.PasswordExpiryError,
);
}
return user;
};
}
}