Created
March 31, 2025 21:55
-
-
Save josvaal/03b7e9d26f18ee11dbb66dd25ebb6799 to your computer and use it in GitHub Desktop.
auth.guard.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
CanActivate, | |
ExecutionContext, | |
Injectable, | |
UnauthorizedException, | |
} from '@nestjs/common'; | |
import { JwtService, TokenExpiredError } from '@nestjs/jwt'; | |
import { jwtConstants } from './constants'; | |
import { Request } from 'express'; | |
@Injectable() | |
export class AuthGuard implements CanActivate { | |
constructor(private jwtService: JwtService) {} | |
async canActivate(context: ExecutionContext): Promise<boolean> { | |
const request = context.switchToHttp().getRequest(); | |
const token = this.extractTokenFromHeader(request); | |
if (!token) { | |
throw new UnauthorizedException('Token no proporcionado'); | |
} | |
try { | |
const payload = await this.jwtService.verifyAsync(token, { | |
secret: jwtConstants.secret, | |
}); | |
// 💡 We're assigning the payload to the request object here | |
// so that we can access it in our route handlers | |
request['user'] = payload; | |
} catch (error) { | |
console.log(error); | |
if (error instanceof TokenExpiredError) { | |
throw new UnauthorizedException( | |
'La sesión ya expiró, inicie sesión nuevamente', | |
); | |
} | |
throw new UnauthorizedException( | |
'No tienes acceso a esto, consulta a un administrador o de rol más alto', | |
); | |
} | |
return true; | |
} | |
private extractTokenFromHeader(request: Request): string | undefined { | |
const [type, token] = request.headers.authorization?.split(' ') ?? []; | |
return type === 'Bearer' ? token : undefined; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment