auth.ts
969 bytes
| 1 | import { ref, computed, watch } from 'vue' |
|---|---|
| 2 | import { defineStore } from 'pinia' |
| 3 | |
| 4 | export const useAuthStore = defineStore('auth', () => { |
| 5 | const jwt = ref<string | null>(localStorage.getItem('jwt')) |
| 6 | const refreshToken = ref<string | null>(localStorage.getItem('refreshToken')) |
| 7 | const userName = ref<string | null>(localStorage.getItem('userName')) |
| 8 | |
| 9 | const isAuthenticated = computed(() => !!jwt.value) |
| 10 | |
| 11 | watch(jwt, (val) => { |
| 12 | if (val) localStorage.setItem('jwt', val) |
| 13 | else localStorage.removeItem('jwt') |
| 14 | }) |
| 15 | |
| 16 | watch(refreshToken, (val) => { |
| 17 | if (val) localStorage.setItem('refreshToken', val) |
| 18 | else localStorage.removeItem('refreshToken') |
| 19 | }) |
| 20 | |
| 21 | watch(userName, (val) => { |
| 22 | if (val) localStorage.setItem('userName', val) |
| 23 | else localStorage.removeItem('userName') |
| 24 | }) |
| 25 | |
| 26 | function logout() { |
| 27 | jwt.value = null |
| 28 | refreshToken.value = null |
| 29 | userName.value = null |
| 30 | } |
| 31 | |
| 32 | return { jwt, refreshToken, userName, isAuthenticated, logout } |
| 33 | }) |
| 34 | |