User token 재사용성 높이는 작업

ESH'S VELOG·2023년 10월 4일
1

사용자의 인증(authentication)을 검증하기 위해 사용하는 access token과 refresh token을 백엔드에서 작업하려고 한다.

✍ 지금까지 사용해오던 방식

 @Post('/login')
 async login(
   @Body() data: LoginUserDto,
   @Res({ passthrough: true }) response: Response,
 ) {
   const authentication = await this.userService.login(
     data.email,
     data.password,
   );
   response.cookie('Authentication', 'Bearer ' + authentication.access_Token);
   response.cookie('Authentication', 'Bearer ' + authentication.refresh_Token);

   return { message: authentication };
 }

위와 같이 로그인 시 cookie를 직접 세팅해주었다.
이렇게 되면 문제가 프론트 연결 또는 앱 연결 시 다시 한 번 작업을 해주어여 한다는 것인다.
따라서 더 좋은 코드는 서버에서 token 값만 반환하여 받는 쪽(앱 또는 웹의 프론트)에서 가공하여 설정하게끔 하는 것이다.

  @Post('/login')
  async login(@Body() data: LoginUserDto) {
    const authentication = await this.userService.login(
      data.email,
      data.password,
    );
    return {
      AccessToken: 'Bearer ' + authentication.accessToken,
      RefreshToken: 'Bearer ' + authentication.refreshToken,
    };
  }

서버쪽을 바꾸어 주었으니 프론트쪽도 바꾸어 주어야 한다.

// 로그인
function login() {
  const data = {
    email: $('#loginEmail').val(),
    password: $('#loginPass').val(),
  };
  axios
    .post('https://togethereat.shop/users/login', data)
    .then(response => {
      setCookie('AccessToken', response.data.AccessToken, 1);
      setCookie('RefreshToken', response.data.RefreshToken, 1);
      alert('고객님 또 와주셨군요 ! 메뉴 추천 페이지로 이동합니다 !^ㅠ^');
      location.href = 'https://togethereat.shop/menu-subscribe.html';
    })
    .catch(error => {
      // 서버에서 발생한 예외 처리
      if (error.response) {
        // 서버가 응답을 보낸 경우
        const errorMessage = error.response.data.message;
        alert('로그인 실패: ' + '이메일 또는 비밀번호가 올바르지 않습니다.');
      } else {
        // 서버로 요청을 보내는 동안 네트워크 오류 등의 문제가 발생한 경우/주석
        console.error('네트워크 오류:', error.message);
        alert('네트워크 오류가 발생했습니다.');
      }
    });
}
//set cookie 함수
function setCookie(cookie_name, value, days) {
  const exdate = new Date();
  exdate.setDate(exdate.getDate() + days);
  const cookie_value =
    value + (days == null ? '' : '; expires =' + exdate.toUTCString());
  document.cookie = cookie_name + '=' + cookie_value;
}
profile
Backend Developer - Typescript, Javascript 를 공부합니다.

0개의 댓글