1

I am new in NestJS and trying to do auth system. I was able to do. So here is what I am doing to get access to auth.

In my controller I have

@Get('/user')
async getUser(@AuthUser() token: string) : Promise<Object> {
    return this.authService.getUser(token)
    return token
}

Here I am passing a AuthUser decorator I want to avoid passing in controllers. In the authService.getUser method I have something like this

async getUser(token: string): Promise<Object> {
    try {
        const user = await this.jwtService.verifyAsync(token)
        return user 
    } catch (error) {
        return false
    }
}

and my decorator looks like this

import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const AuthUser = createParamDecorator(
(data = 'u_ses', ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return data ? request.cookies?.[data] : request.cookies;
},
);

I don't like code. If I need to know the user id from a service class or anywhere I would need to pass the token and to get token I need use @AuthUser() token: string)

So I want to do something like this

this.authService.getUser(), here I don't want to pass token or anything and should be able to access this getUser method from anywhere. Since it's a service class, I can inject and use it but I won't have the token.

I tried injecting the decorator inside the service class, but this doesn't work.

One best solution I would prefer is to use the JWT things inside the decorator, so I don't need the service class' method :)

I am looking for a nicer solutions from you :)

Thank you.

greybeard
  • 2,249
  • 8
  • 30
  • 66
Hkm Sadek
  • 2,987
  • 9
  • 43
  • 95

1 Answers1

0

Nestjs has NestMiddleware. Here, you can authorize before access to controller like this:

import { Injectable, NestMiddleware, UnauthorizedException } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class AuthenticationMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    const headerAuthentication = req.headers.authorization;
    if(!headerAuthentication) throw new UnauthorizedException('Authorization failed!');
    const token = req.headers.authorization.split(' ')[1];
    if(token) {
      next();
    }else {
      throw new UnauthorizedException('Authorization failed!');
    }
  }
}

and in AppModule implement it

  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthenticationMiddleware).forRoutes('/');
  }
}
danhuong
  • 202
  • 1
  • 8