Skip to content

Commit

Permalink
Update JwtAuthGuard to handle exception with handleRequest
Browse files Browse the repository at this point in the history
  • Loading branch information
wet6123 committed Aug 3, 2024
1 parent 1e2907a commit a66bd78
Showing 1 changed file with 12 additions and 35 deletions.
47 changes: 12 additions & 35 deletions backend/src/auth/jwt.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,11 @@ import {
import { Reflector } from "@nestjs/core";
import { AuthGuard } from "@nestjs/passport";
import { IS_PUBLIC_PATH } from "src/utils/decorators/auth.decorator";
import * as jwt from "jsonwebtoken";
import { ConfigService } from "@nestjs/config";
import { AuthorizedUser } from "src/utils/types/req.type";

@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt") {
constructor(
private reflector: Reflector,
private configService: ConfigService
) {
constructor(private reflector: Reflector) {
super();
}

Expand All @@ -27,38 +23,19 @@ export class JwtAuthGuard extends AuthGuard("jwt") {
if (isPublic) {
return true;
}
return super.canActivate(context);
}

try {
const request = context.switchToHttp().getRequest();
const token = request.headers.authorization?.split(" ")[1];
if (!token) {
throw new UnauthorizedException("Unauthorized", {
cause: new Error(),
description: "Token not found",
});
}

const secretKey = this.configService.get<string>("JWT_AUTH_SECRET");
const decoded = jwt.verify(token, secretKey);
request.user = decoded;
return super.canActivate(context);
} catch (e) {
if (e.name === "TokenExpiredError") {
throw new UnauthorizedException("Unauthorized", {
cause: new Error(),
description: "Token has expired.",
});
} else if (e.name === "JsonWebTokenError") {
throw new UnauthorizedException("Unauthorized", {
cause: new Error(),
description: "Invalid token",
});
handleRequest<User = AuthorizedUser>(err: Error, user: User, info: Error): User {
if (err || !user) {
if (info?.name === "TokenExpiredError") {
throw new UnauthorizedException("Token has expired.");
} else if (info?.name === "JsonWebTokenError") {
throw new UnauthorizedException("Invalid token");
} else {
throw new ForbiddenException("Forbidden", {
cause: new Error(),
description: "Access denied",
});
throw err || new ForbiddenException("Access denied");
}
}
return user;
}
}

0 comments on commit a66bd78

Please sign in to comment.