|
| 1 | +import { JsonWebTokenError } from 'jsonwebtoken'; |
1 | 2 | import { Request, Response, NextFunction } from 'express'; |
2 | 3 |
|
3 | 4 | import * as jwt from '../utils/jwt'; |
4 | 5 | import logger from '../utils/logger'; |
5 | 6 | import config from '../config/config'; |
6 | | -import ErrorType from './../resources/enums/ErrorType'; |
| 7 | +import { JWTErrorType } from './../resources/enums/ErrorType'; |
7 | 8 | import BadRequestError from '../exceptions/BadRequestError'; |
8 | 9 | import UnauthorizedError from '../exceptions/UnauthorizedError'; |
| 10 | +import { tokenErrorMessageMap } from '../resources/constants/maps'; |
9 | 11 |
|
10 | 12 | const { errors } = config; |
11 | 13 |
|
12 | | -const tokenErrorMessageMap: any = { |
13 | | - [ErrorType.INVALID]: errors.invalidToken, |
14 | | - [ErrorType.EXPIRED]: errors.accessTokenExpired |
15 | | -}; |
16 | | - |
17 | 14 | /** |
18 | 15 | * A middleware to authenticate the authorization token i.e. access token. |
19 | 16 | * |
@@ -48,17 +45,21 @@ async function authenticate( |
48 | 45 | ); |
49 | 46 |
|
50 | 47 | next(); |
51 | | - } catch (err: any) { |
52 | | - const tokenErrorMessage = tokenErrorMessageMap[err.name]; |
53 | | - logger.log('error', 'JWT: Authentication failed - %s', err.message); |
| 48 | + } catch (err) { |
| 49 | + if (err instanceof JsonWebTokenError) { |
| 50 | + const tokenErrorMessage = tokenErrorMessageMap[err.name as JWTErrorType]; |
| 51 | + logger.log('error', 'JWT: Authentication failed - %s', err.message); |
| 52 | + |
| 53 | + if (tokenErrorMessage) { |
| 54 | + logger.log('error', 'JWT: Token error - %s', tokenErrorMessage); |
54 | 55 |
|
55 | | - if (tokenErrorMessage) { |
56 | | - logger.log('error', 'JWT: Token error - %s', tokenErrorMessage); |
| 56 | + next(new UnauthorizedError(tokenErrorMessage)); |
57 | 57 |
|
58 | | - next(new UnauthorizedError(tokenErrorMessage)); |
59 | | - } else { |
60 | | - next(err); |
| 58 | + return; |
| 59 | + } |
61 | 60 | } |
| 61 | + |
| 62 | + next(err); |
62 | 63 | } |
63 | 64 | } |
64 | 65 |
|
|
0 commit comments