1

i have extended jwt guard for purpose of checking if user exists in user table here's my code:

import {
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { error } from 'console';
import { UsersService } from 'src/users/users.service';
import { Role } from './role.enum';
@Injectable()
export class JwtUserGuard extends AuthGuard('jwt') {
  constructor(private readonly userService: UsersService) {
    super();
  }
  canActivate(context: ExecutionContext) {
    return super.canActivate(context);
  }

  handleRequest(err, user, info) {
    this.userService.findByEmail(user.email).then((user) => {
  if (user === undefined) {
    throw new UnauthorizedException();
  }
  return user;
}).catch(error=>{
  throw new UnauthorizedException();
});

    if (user.role !== Role.User) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

but i always get an error

(node:4504) UnhandledPromiseRejectionWarning: Error: Unauthorized
    at /media/ridwan/storage/workspace/backend/javascript/nestjs/queueing/dist/auth/jwt-user.guard.js:28:23
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:4504) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:4504) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

my question is how to handle UnhandledPromiseRejectionWarning my code still running even though user doesn't exists? thanks in advance..

imedin
  • 13
  • 1
  • 3

2 Answers2

2

You're mixing synchronous and asynchronous programming methods by using promises (with a chained then and catch) and by not returning the promise in the first place. I believe Nest's handleRequest method doesn't allow for asynchronous methods. So what's happening is you're kicking off an async process (the promised call to this.userService.findByEmail) and it's throwing an error, but you're returning (synchronously) the user property (or throwing a different error that is properly handled). Then, when the promise resolves (rejects) you have an unhandled throw meaning an UnhandledPromiseRejection.

I don't understand why you wouldn't be able to do all of this logic inside of a Strategy file instead, as the handleRequest happens after the validateis called in the first place.

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • thanks for your answer, what i would like to do is to create different jwt guard for each of user like `JwtUserGuard`, `JwtAdminGuard`, `JwtTenantGuard`. because user using email for login and the rest using username so i have to check which table should i use from the token. – imedin Jan 22 '21 at 02:49
  • Why can't you make that a part of the `JwtStrategy` and keep the logic consolidated to there? I don't see why you need to bring in multiple guards – Jay McDoniel Jan 22 '21 at 03:03
  • i don't know how to create specific route only for specific user like route for list of user only for admin can access it that why i created a different type of guards, could you give me some example how to do it in `JwtStrategy` ? – imedin Jan 22 '21 at 03:11
  • It seems like overall you're trying to merge something like a `RolesGuard` and a `JwtGuard` into a single guard. What I would suggest doing is have the `JwtGuard` which is to assert the validity of the passed jwt, and a `RolesGuard` [similar to what's shown in the docs](https://docs.nestjs.com/security/authorization#basic-rbac-implementation) to verify that the calling user has access to the route. This way you have your separation of concerns and aren't worrying about mixing your logics – Jay McDoniel Jan 22 '21 at 03:22
  • yes what i'm trying to create single guard because i don't know how to pass and read user object from token to the `RolesGuard` for example. using ` const { user } = context.switchToHttp().getRequest();` it gives me undefined result, maybe you can give me example how to pass and read user object from token in roleguard? – imedin Jan 22 '21 at 06:44
  • For that, you're probably binding the `RolesGuard` globally but using the `JwtGuard` at a controller or route handler leve. Guards (and everything really) have a defned order of running. That's a different question with a different answer (and I'm pretty sure has already been asked). To keep discussion from happening too much further in the comments, please acknowledge if your original question has been answer and create a new question, or [find some support on Discord](https://discord.gg/nestjs) – Jay McDoniel Jan 22 '21 at 06:57
0

Use the PassportStrategy mixin and move the findByEmail logic to the right place. They explain how to do this here: https://docs.nestjs.com/security/authentication#implement-protected-route-and-jwt-strategy-guards

Micael Levi
  • 5,054
  • 2
  • 16
  • 27
  • thanks for your response, but i need put some extra logic based on information from that token for example if this token belongs to user or admin to determine access policy because i used different table for authentication for each of users – imedin Jan 22 '21 at 01:39