nestjsnestjs-jwt

nestjs extends jwt guard


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..


Solution

  • 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.