35 lines
931 B
TypeScript
35 lines
931 B
TypeScript
import {
|
|
HttpException,
|
|
HttpStatus,
|
|
Inject,
|
|
Injectable,
|
|
NestMiddleware,
|
|
} from '@nestjs/common';
|
|
import { ClientProxy } from '@nestjs/microservices';
|
|
import { Request, Response, NextFunction } from 'express';
|
|
import { lastValueFrom } from 'rxjs';
|
|
|
|
@Injectable()
|
|
export class UserMiddleware implements NestMiddleware {
|
|
constructor(@Inject('auth') private authClient: ClientProxy) {}
|
|
|
|
async use(req: Request, res: Response, next: NextFunction) {
|
|
if (!req.headers.authorization) return next();
|
|
|
|
// Verify token by auth microservice
|
|
const [, token] = req.headers.authorization.split(' ');
|
|
const user = await lastValueFrom(
|
|
this.authClient.send('auth.verify', { token }),
|
|
).catch((err) => {
|
|
throw new HttpException(
|
|
err.response,
|
|
Number(err.status) || HttpStatus.FORBIDDEN,
|
|
);
|
|
});
|
|
|
|
// Add token contents to locals
|
|
res.locals.user = user;
|
|
next();
|
|
}
|
|
}
|