54 lines
1.4 KiB
JavaScript
54 lines
1.4 KiB
JavaScript
import { defineStore } from 'pinia'
|
|
import { ref, computed } from 'vue'
|
|
import { authApi } from '../api/auth'
|
|
|
|
export const useAuthStore = defineStore('auth', () => {
|
|
const token = ref(localStorage.getItem('wmms_token') || '')
|
|
const user = ref(JSON.parse(localStorage.getItem('wmms_user') || 'null'))
|
|
|
|
const isLoggedIn = computed(() => !!token.value)
|
|
const hasRole = roleCode => (user.value?.roles || []).some(role => role.enabled && role.code === roleCode)
|
|
const isAdmin = computed(() => hasRole('super_admin'))
|
|
|
|
function saveAuth(newToken, newUser) {
|
|
token.value = newToken
|
|
user.value = newUser
|
|
localStorage.setItem('wmms_token', newToken)
|
|
localStorage.setItem('wmms_user', JSON.stringify(newUser))
|
|
}
|
|
|
|
function clearAuth() {
|
|
token.value = ''
|
|
user.value = null
|
|
localStorage.removeItem('wmms_token')
|
|
localStorage.removeItem('wmms_user')
|
|
}
|
|
|
|
async function login(username, password) {
|
|
const res = await authApi.login(username, password)
|
|
saveAuth(res.data.token, res.data.user)
|
|
return res.data
|
|
}
|
|
|
|
async function fetchCurrentUser() {
|
|
if (!token.value) return null
|
|
try {
|
|
const res = await authApi.getCurrentUser()
|
|
saveAuth(token.value, res.data)
|
|
return res.data
|
|
} catch {
|
|
clearAuth()
|
|
return null
|
|
}
|
|
}
|
|
|
|
function logout() {
|
|
clearAuth()
|
|
}
|
|
|
|
return {
|
|
token, user, isLoggedIn, isAdmin, hasRole,
|
|
saveAuth, clearAuth, login, fetchCurrentUser, logout
|
|
}
|
|
})
|