mirror of
https://github.com/SyncrowIOT/backend.git
synced 2026-10-24 18:37:55 +00:00
44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
import { UnauthorizedException } from '@nestjs/common';
|
|
import { AuthGuard } from '@nestjs/passport';
|
|
import * as jwt from 'jsonwebtoken';
|
|
|
|
export class ClientGuard extends AuthGuard('jwt') {
|
|
handleRequest(err, user, info, context) {
|
|
if (err || !user) {
|
|
throw err || new UnauthorizedException();
|
|
}
|
|
|
|
const request = context.switchToHttp().getRequest();
|
|
const token = this.extractTokenFromHeader(request);
|
|
|
|
if (!token) {
|
|
throw new UnauthorizedException('Token not found');
|
|
}
|
|
|
|
try {
|
|
const decoded = jwt.decode(token);
|
|
if (!this.validateToken(decoded)) {
|
|
throw new UnauthorizedException('Invalid token');
|
|
}
|
|
|
|
request.client = (decoded as jwt.JwtPayload).client;
|
|
} catch (err) {
|
|
throw new UnauthorizedException('Invalid token');
|
|
}
|
|
|
|
return user;
|
|
}
|
|
|
|
private extractTokenFromHeader(request): string | null {
|
|
const authHeader = request.headers.authorization;
|
|
if (authHeader && authHeader.startsWith('Bearer ')) {
|
|
return authHeader.split(' ')[1];
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private validateToken(decoded: any): boolean {
|
|
return decoded?.client?.clientId && decoded?.client?.uuid;
|
|
}
|
|
}
|