본문 바로가기
Node.js/NestJs

[User] Authentication #1 - login

by Ykie 2023. 4. 7.
728x90

login resolver / service / dto

nestjs/passports, passports/jwt는 편하고 좋지만 일단 패스.
step1. jwt 붙이기
step2. jwt module 만들어서 this.jwt.sign() 으로 사용. > nestjs module 구조 공부 용도.

jwt token은 유저가 해독 가능하기 때문에 민감한 정보를 넣지 않고, 일반적으로는 ID 정도의 정보가 적당하다.
token에 담을 항목을 정해주고, private key를 적어주면 끝. private key를 통해 변경된 토큰 여부를 확인할 수 있다. 
https://randomkeygen.com/ 를 통해 쉽게 랜덤 키를 생성할 수 있음.
https://jwt.io/ 

https://ykie-dev.tistory.com/18

 

JWT (JSON WEB TOKEN)

JWT 는 유저를 인증하고 식별하기 위한 토큰(Token)기반 인증이다. RFC 7519 에 자세한 명세가 나와있다. 토큰은 세션과는 달리 서버가 아닌 클라이언트에 저장되기 때문에 메모리나 스토리지 등을

ykie-dev.tistory.com

 

// user.entity.ts
  ...
  async checkPassword(aPassword: string): Promise<boolean> {
    try {
      const ok = await bcrypt.compare(aPassword, this.password);
      return ok;
    } catch (e) {
      throw new InternalServerErrorException();
    }
  }
  ...


// login.dto.ts
@InputType()
export class LoginInput extends PickType(User, ['email', 'password']) {}

@ObjectType()
export class LoginOutput extends MutationOutput {
  @Field((type) => String, { nullable: true })
  token?: string;
}


// users.service.ts
  ...
  async login({
    email,
    password,
  }: LoginInput): Promise<{ ok: boolean; error?: string; token?: string }> {
    try {
      // find the user with the email
      const user = await this.users.findOne({ where: { email } });
      if (!user) {
        return { ok: false, error: 'User not found' };
      }
      // check if the paswwrod is correct
      const passwordCorrect = await user.checkPassword(password);
      if (!passwordCorrect) {
        return { ok: false, error: 'Wrong password' };
      }
      // make a JWT and give
	  const token = jwt.sign({ id: user.id }, process.env.SECRET_KEY);
      return { ok: true, token };
    } catch (error) {
      return { ok: false, error };
    }
  }
  ...


  // users.resolve.ts
  ...
  @Mutation((returns) => LoginOutput)
  async login(@Args('input') loginInput: LoginInput): Promise<LoginOutput> {
    try {
      return this.userService.login(loginInput);
    } catch (error) {
      return { ok: false, error };
    }
  }
  ...
728x90

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

[User] Authentication #3 JWT Middleware  (0) 2023.04.08
[User] Authentication #2 JWT Module  (0) 2023.04.07
[User] Model #3 Create Account (+ Hashing Password)  (0) 2023.04.06
[User] Model #2 graphql enum  (0) 2023.04.06
TypeOrm Decorator  (0) 2023.04.06

댓글