-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathuser-id.middleware.ts
42 lines (33 loc) · 1.28 KB
/
user-id.middleware.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
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Response } from 'express';
import { FirebaseAuthService, LogService } from '../../../services';
import { RequestExtended } from '../../baseClasses';
/**
* Uses JWT from "request.headers.authorization" to get related userId and save it to req.userId
*/
@Injectable()
export class UserIdMiddleware implements NestMiddleware {
logService = new LogService(UserIdMiddleware.name);
constructor(private readonly firebaseAuthService: FirebaseAuthService) {}
async use(req: RequestExtended, _res: Response, next: () => void): Promise<void> {
await this.logService.trackSegment(this.use.name, async logSegment => {
const { authorization } = req.headers;
if (!authorization) {
logSegment.log(`Token is not presented`);
// TODO: context.setUser(null);
next();
return;
}
const token = authorization.replace('Bearer ', '');
const userId = await this.firebaseAuthService.validateJWT(token);
req.userId = userId || undefined;
logSegment.log(`Token is ${userId ? '' : 'in'}valid.`, { userId, token });
if (userId) {
// TODO: context.setUser({ id: userId });
} else {
// TODO: context.setUser(null);
}
next();
});
}
}