본문 바로가기
Node.js/NestJs

[User] Authentication #4 Guard

by Ykie 2023. 4. 8.
728x90

Guard: Request를 다음 단계로 진행할지 말지 결정하는 함수.

nest g mo auth 로 auth module 추가 (jwt module에서 더 다룰 건 없다)

// auth.guard.ts
@Injectable()
export class AuthGuard implements CanActivate {
  // CanActive는 반환되는 값에 따라 ture일 경우 request를 진행시키고 false인 경우 request를 멈추게 한다.
  canActivate(context: ExecutionContext): boolean {
    // content가 http로 되어 있어서 graphql context로 변환해줘야 한다.
    const gqlContext = GqlExecutionContext.create(context).getContext();
    const user = gqlContext['user'];
    if (!user) {
      return false;
    }
    return true;
  }
}


// user.resolver.ts
...
  @Query((returns) => User)
  @UseGuards(AuthGuard) // authentication!! user role에 따라 권한을 부여할 수도 있고 등등
  me() {}
...

 

But! @UseGuards를 사용하지 않고 Decorator를 추가할 것. #5에서 계속~  

728x90

'Node.js > NestJs' 카테고리의 다른 글

[User] update Profile  (0) 2023.04.14
[User] Authentication #5 AuthUser Decorator  (0) 2023.04.08
[User] Authentication #3 JWT Middleware  (0) 2023.04.08
[User] Authentication #2 JWT Module  (0) 2023.04.07
[User] Authentication #1 - login  (0) 2023.04.07

댓글