-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuserIdResolver.ts
More file actions
37 lines (33 loc) · 1.18 KB
/
userIdResolver.ts
File metadata and controls
37 lines (33 loc) · 1.18 KB
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
import type { FastifyInstance } from 'fastify';
import type AuthService from '@domain/service/auth.js';
import { notEmpty } from '@infrastructure/utils/empty.js';
import { getRequestLogger } from '@infrastructure/logging/index.js';
/**
* Add middleware for resolve userId from Access Token and add it to request
* @param server - fastify instance
* @param authService - auth domain service
*/
export default function addUserIdResolver(server: FastifyInstance, authService: AuthService): void {
/**
* Default userId value — null
*/
server.decorateRequest('userId', null);
/**
* Resolve userId from Access Token on each request
*/
server.addHook('preHandler', (request, _reply, done) => {
const logger = getRequestLogger('middlewares');
const authorizationHeader = request.headers.authorization;
if (notEmpty(authorizationHeader)) {
const token = authorizationHeader.replace('Bearer ', '');
try {
request.userId = authService.verifyAccessToken(token)['id'];
logger.debug('User ID resolved from Access Token');
} catch (error) {
logger.error('Invalid Access Token');
logger.error(error);
}
}
done();
});
}