jwt parse for user uuid
This commit is contained in:
parent
a1ed5429a4
commit
51436141a4
1 changed files with 31 additions and 3 deletions
|
|
@ -3,11 +3,28 @@ import { computed, ref } from 'vue'
|
|||
import { apiClient } from '@/services/apiClient'
|
||||
import router from '@/router/index.js'
|
||||
|
||||
function parseJwt(token) {
|
||||
try {
|
||||
const base64Url = token.split('.')[1]
|
||||
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const jsonPayload = decodeURIComponent(
|
||||
atob(base64)
|
||||
.split('')
|
||||
.map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
|
||||
.join('')
|
||||
)
|
||||
return JSON.parse(jsonPayload)
|
||||
} catch (e) {
|
||||
console.error('Invalid JWT:', e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
// state
|
||||
const accessToken = ref(localStorage.getItem('accessToken'))
|
||||
const userUuid = ref(localStorage.getItem('userUuid') || null)
|
||||
const user = ref(null)
|
||||
|
||||
const activeTab = ref('signin')
|
||||
|
||||
// getters
|
||||
|
|
@ -16,10 +33,20 @@ export const useAuthStore = defineStore('auth', () => {
|
|||
// actions
|
||||
const setToken = (token) => {
|
||||
accessToken.value = token
|
||||
|
||||
if (token) {
|
||||
localStorage.setItem('accessToken', token)
|
||||
|
||||
const decoded = parseJwt(token)
|
||||
const uuid = decoded?.sub
|
||||
if (uuid) {
|
||||
userUuid.value = uuid
|
||||
localStorage.setItem('userUuid', uuid)
|
||||
}
|
||||
} else {
|
||||
localStorage.removeItem('accessToken')
|
||||
localStorage.removeItem('userUuid')
|
||||
userUuid.value = null
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -68,7 +95,7 @@ export const useAuthStore = defineStore('auth', () => {
|
|||
const response = await apiClient.get('/user/')
|
||||
return response.data
|
||||
} catch (error) {
|
||||
console.error('Register error:', error)
|
||||
console.error('User info error:', error)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -77,12 +104,13 @@ export const useAuthStore = defineStore('auth', () => {
|
|||
const response = await apiClient.get('/user/auth/current-session')
|
||||
return response.data
|
||||
} catch (error) {
|
||||
console.error('Register error:', error)
|
||||
console.error('Current session error:', error)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
userUuid,
|
||||
user,
|
||||
isAuthenticated,
|
||||
activeTab,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue