mirror of
https://github.com/SyncrowIOT/backend.git
synced 2026-10-23 11:57:54 +00:00
finished client endpoints
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
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');
|
||||
}
|
||||
} 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 {
|
||||
if (
|
||||
decoded &&
|
||||
decoded.client &&
|
||||
decoded.client.clientId &&
|
||||
decoded.client.uuid
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user