-
-
Notifications
You must be signed in to change notification settings - Fork 304
/
Copy pathadmin-maybe.guard.ts
executable file
·33 lines (30 loc) · 1.02 KB
/
admin-maybe.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
/**
* @file AdminMaybe guard
* @module guard/admin-maybe
* @author Surmon <https://github.com/surmon-china>
*/
import { AuthGuard } from '@nestjs/passport'
import { ExecutionContext, Injectable } from '@nestjs/common'
import { HttpUnauthorizedError } from '@app/errors/unauthorized.error'
import { UNDEFINED } from '@app/constants/value.constant'
/**
* @class AdminMaybeGuard
* @classdesc Token isn't existed | Token validated
* @example ```@UseGuards(AdminMaybeGuard)```
*/
@Injectable()
export class AdminMaybeGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
return super.canActivate(context)
}
handleRequest(error, authInfo, errInfo) {
const validToken = Boolean(authInfo)
// MARK: https://github.com/mikenicholson/passport-jwt/issues/174
const emptyToken = !authInfo && errInfo?.message === 'No auth token'
if (!error && (validToken || emptyToken)) {
return authInfo
} else {
throw error || new HttpUnauthorizedError(UNDEFINED, errInfo?.message)
}
}
}