Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac
docs.nestjs.com
nest g mo auth로 인증 모듈을 만든다.
Guard는 HTTP Request를 다음 단계로 넘길지에 대해서 인증을 하게 해준다.
auth.guard.ts를 만들고 implements CanActivate를 입력한다. CanActivate 함수는 true를 return하면 request 진행 반대면 멈춘다.
context가 HTTP Request로 이루어져 있어서 이를 GraphQL 문으로 gqlContext를 사용하여 변경해준다. 그 이유는 구조가 다르기 때문이다.
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { GqlExecutionContext } from "@nestjs/graphql";
import { Observable } from "rxjs";
@Injectable()
export class AuthGuard implements CanActivate{
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
const gqlContext = GqlExecutionContext.create(context).getContext();
const user = gqlContext['user'];
if(!user){
return false;
}
return true;
}
}
추가로 요청을 누가 보냈는지 custom decorator를 만들어보자.
import { createParamDecorator, ExecutionContext } from "@nestjs/common";
import { GqlExecutionContext } from "@nestjs/graphql";
export const AuthUser = createParamDecorator(
(data:unknown, context: ExecutionContext) => {
const gqlContext = GqlExecutionContext.create(context).getContext();
const user = gqlContext['user'];
return user;
}
);
resolver에서는 아래와 같이 사용한다.
@Query(returns => User)
@UseGuards(AuthGuard)
me(@AuthUser() authUser: User) {
return authUser;
}
'Uber Eats' 카테고리의 다른 글
Uber Eats # 19 Mail module 만들기 (0) | 2021.03.19 |
---|---|
Uber Eats # 18 User Profile (0) | 2021.03.13 |
Uber Eats # 16 User Authentication (0) | 2021.03.11 |
Uber Eats # 15 User Resolver and Service, InputType과 ObjectType 비교 (0) | 2021.03.09 |
Uber Eats # 14 User Model (0) | 2021.03.09 |