-
Notifications
You must be signed in to change notification settings - Fork 4
/
authorization.guard.ts
40 lines (34 loc) · 1.02 KB
/
authorization.guard.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
import {
CanActivate,
ExecutionContext,
Injectable,
InternalServerErrorException,
UnauthorizedException,
} from '@nestjs/common';
import { Request, Response } from 'express';
import {
auth,
InvalidTokenError,
UnauthorizedError,
} from 'express-oauth2-jwt-bearer';
import { promisify } from 'util';
@Injectable()
export class AuthorizationGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const response = context.switchToHttp().getResponse<Response>();
const validateAccessToken = promisify(auth());
try {
await validateAccessToken(request, response);
return true;
} catch (error) {
if (error instanceof InvalidTokenError) {
throw new UnauthorizedException('Bad credentials');
}
if (error instanceof UnauthorizedError) {
throw new UnauthorizedException('Requires authentication');
}
throw new InternalServerErrorException();
}
}
}