프로젝트/Digital Twin Bootcamp

[Team 제주 넘는 차] 로그아웃

Ail_ 2022. 3. 3. 19:41

로컬 스토리지에 토큰을 담는 것은 이미 수업 때 해봤던 부분이라 그렇게 어렵지 않았다.

로그아웃 또한 마찬가지였다.

토큰 삭제를 어디서 할 지 고민했는데 그냥 수업 때처럼 프론트에서 삭제하기로 했다.

 

vues/auth/logout.vue

로그아웃 페이지를 따로 생성했다.

<template>
  <div>
    <div class="text-center" style="padding-top: 200px">
      <b-spinner variant="secondary" style="width: 3rem; height: 3rem; padding-top: 50px"></b-spinner>
    </div>
  </div>
</template>

<script>
export default {
  computed: {
    loading() {
      return this.$store.getters.TokenLoading
    }
  },
  watch: {
    loading(value) {
      if (value === false) {
        // 로그아웃 처리 후 이동
        this.$router.replace('/auth/login')
      }
    }
  },
  created() {
    this.$store.dispatch('authLogout')
  }
}
</script>

<style lang="scss" scoped></style>

 

store/models/auth.js

로그아웃 로직을 추가 했다.

백엔드로 받지 않고 프론트에서 로컬 스토리지에 있는 토큰을 삭제하도록 했다.

// ...

  mutations: {
    // 동기적
    setTokenUser(state, data) {
      state.TokenUser = data
    },
    setTokenLoading(state, data) {
      state.TokenLoading = data
      state.Error = null
    },
    setError(state, data) {
      state.Loading = false
      state.Error = data
      state.TokenUser = { ...stateInit.TokenUser }
    },
    clearError(state) {
      state.Error = null
    },
    setLogout(state) {
      state.Loading = false
      state.Error = null
      state.TokenUser = { ...stateInit.TokenUser }
    }
  },
  actions: {
    // 비동기 (mutations 호출)

// ...

    async authLogout(context) {
      // 로그아웃 처리

      // 상태값 초기화
      context.commit('clearError')
      context.commit('setLoading', true)

      /* 테스트 데이터 세팅 */
      setTimeout(() => {
        context.commit('setLogout') // 로그아웃 처리
        window.localStorage.removeItem('accessToken') // 토큰 삭제
      }, 1000) // 처리 시간 1초
    },

    authTokenUser(context, payload) {
      // 토큰 사용자 설정
      const decodedToken = jwtDecode(payload)
      context.commit('setTokenUser', decodedToken)
    }
  }
}

 

router/index.js

라우터에 logout을 추가했다.

// ...

    path: '/auth',
    component: () => import('../views/auth'),
    children: [
      {
        path: '/auth/login',
        component: () => import('../views/auth/login'),
        meta: { noLogin: true }
      },
      {
        path: '/auth/sign',
        component: () => import('../views/auth/signup'),
        meta: { noLogin: true }
      },
      {
        path: '/auth/logout',
        component: () => import('../views/auth/logout'),
        meta: { noLogin: true }
      }
    ]
  },
  
// ...