🖥️Frontend/Node

[Node] 로그아웃 기능 구현

뉴발자 2023. 12. 1.
728x90

 

 

 

 

 

 

 

 

 

 

 

 

 

그림 1-1. 로그아웃

 

 

JWT 토큰 인증

https://tlseoqja.tistory.com/54

 

[Node] 페이지 접속 시 JWT 토큰 인증

회원 로그인 기능 구현 https://tlseoqja.tistory.com/53 [Node] 회원 로그인, 비밀번호 복호화 및 JWT 토큰 생성 비밀번호 암호화 https://tlseoqja.tistory.com/51 [Node] 회원 가입 시 비밀번호 암호화 MongoDB 연동 및

tlseoqja.tistory.com

 

 

로그아웃

로그아웃 기능은 간단하다.

 

이전에 작성한 auth API를 이용해서 쿠키에 저장된 토큰 값을 복호화한 후 나온 _id값으로

 

MongoDB에 해당 유저의 존재 여부를 확인하고, 유저가 존재하는 경우 token 값을 공백으로 업데이트한다.

 

index.js

auth API 아래에 다음 코드를 작성해준다.

//index.js
...

app.get("/api/users/auth", auth, (req, res) => {
  ...
});

app.get("/api/users/logout", auth, (req, res) => {
  User.findOneAndUpdate({ _id: req.user._id }, { token: "" })
  .then((user, err) => {
    if( err ) {
      return res.json({
        logoutSuccess: false,
        err,
      });
    }

    return res.status(200).json({
      logoutSuccess: true,
    })
  })
});

 

mongoose 라이브러리의 findOneAndUpdate 함수를 사용해서 JWT 토큰 값을 업데이트 한다.

 

첫 번째 인자로 업데이트 할 대상을 찾고 (filter) 두 번째 인자로 업데이트 할 값(update)을 적어준다.

 

업데이트 할 대상이 존재한다면 user 객체를 반환하고, 아닐 경우 에러를 반환한다.

728x90

 

 

테스트

먼저 포스트맨으로 미로그인 시(토큰x) 로그아웃 API 테스트를 진행한다.

 

결과는 다음과 같다.

그림 2-1. 미로그인 시 로그아웃 API 통신 결과

 

로그아웃 API에서 에러 발생 시 리턴하는 logoutSuccess가 아닌 isAuth 값이 반환된다.

 

이유는 로그아웃 전에 auth API를 통해 토큰 검증 후 로그아웃이 진행되기 때문이다.

 

그래서 로그아웃 API를 거치기도 전에 에러가 발생하게 된다.

 

 

다음은 로그인 후(토큰 O) 로그아웃 테스트를 진행한 결과이다.

그림 3-1. 로그인 API 및 JWT 토큰 저장

 

그림 3-2. 로그인 시 로그아웃 API 테스트

 

 

참고 사이트

https://mongoosejs.com/docs/tutorials/findoneandupdate.html

 

Mongoose v8.0.2: Mongoose Tutorials: How to Use `findOneAndUpdate()` in Mongoose

How to Use findOneAndUpdate() in Mongoose The findOneAndUpdate() function in Mongoose has a wide variety of use cases. You should use save() to update documents where possible, for better validation and middleware support. However, there are some cases whe

mongoosejs.com

 

 

 

 

 

 

 

 

 

 

728x90

댓글