로그인 유저 식별

PSK·2021년 7월 10일
0

eatingSimple

목록 보기
3/3

구현 이유

  • db를 건드리는 Mutation 작업을 할 때, 로그인 유저를 식별하는 것은 매우 중요하고 가장 기본이다.
  • 허락되지 않은 유저가 남의 정보를 마음대로 수정, 삭제할 수 있으면 큰 문제가 생긴다.
  • 많은 Mutation에서 로그인 유저를 식별해야 하기 때문에, Resolver마다 일일히 코딩하기 보다 하나의 함수로 만들어 활용하는 것이 편하다.

어떻게 구현?

export const protectedResolver =
  (ourResolver) => (root, args, context, info) => {
    const { loggedInUser } = context;
    if (!loggedInUser) {
      const query = info.operation.operation === "query";
      if (query) {
        return null;
      }
      return {
        ok: false,
        error: "User's not logged in",
      };
    }
    return ourResolver(root, args, context, info);
  };

이 함수는 어떻게 실행될까?

  1. 실제 Mutation에서 실행될 Resolver가 작동하기 전에, protecedResolver 함수가 작동한다.

  2. 먼저 Apollo Server에서 http header의 token을 해석해서(이것은 jwt를 이용) loggedInUser라는 이름으로 context에 들어간 상태이다.

  3. protecedResolver 함수는 context를 읽고 loggedInUser가 존재하지 않는 경우(token이 손상됐거나 비로그인 상태인 경우), info에서 client가 어떤 요청을 했는지(Query or Mutation)보고, query면 null을 return하고 mutation이면 ok: false와 에러 메시지를 return 한다.

  4. loggedInUser가 존재하면 실제 Mutation에서 실행될 Resolver(ourResolver)함수를 실행해준다.


어떻게 활용?

user가 자신의 정보를 수정하고 싶다. 이 경우에 loggedInUser가 자신이라는 것을 잘 식별해줘야 하기 때문에 protectedResolver를 활용해야한다.

editProfile: protectedResolver(
      async (
        _,
        { email, password: newPassword, name, avatar, bio },
        { loggedInUser }
      ) => {
        try {
          {코드 생략...}      
          await client.user.update({
            where: {
              id: loggedInUser.id,
            },
            data: {
              email,
              name,
              ...(newAvatar && { avatar: newAvatar }),
              bio,
              ...(uglyPassword && { password: uglyPassword }),
            },
          });
          return {
            ok: true,
          };
        } catch (e) {
          return {
            ok: false,
            error: e.message,
          };
        }
      }
    ),
  • protectedResolver안에 실제 Mutation에 사용될 함수를 넣어준다.
  • 따라서 protectedResolver는 함수를 인자로 받는 함수인 것이다.
  • loggedInUser가 밝혀지면 Resolver가 실행되고, Mutation에서 받은 인자를 바탕으로 user의 정보를 업데이트 해준다.(처음에 수정될 user의 id와 loggedInUser의 id 일치 여부 확인 필수)
profile
개발잘하고싶다

0개의 댓글