init
This commit is contained in:
45
frontend/src/stores/admin.js
Normal file
45
frontend/src/stores/admin.js
Normal file
@@ -0,0 +1,45 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import api from '../api/client'
|
||||
|
||||
export const useAdminStore = defineStore('admin', () => {
|
||||
const token = ref(localStorage.getItem('admin_token') || '')
|
||||
const user = ref(null)
|
||||
const isAuthenticated = computed(() => !!token.value)
|
||||
|
||||
function setAuth(tokenValue, userData) {
|
||||
token.value = tokenValue
|
||||
user.value = userData
|
||||
localStorage.setItem('admin_token', tokenValue)
|
||||
api.defaults.headers.common['Authorization'] = `Bearer ${tokenValue}`
|
||||
}
|
||||
|
||||
function logout() {
|
||||
token.value = ''
|
||||
user.value = null
|
||||
localStorage.removeItem('admin_token')
|
||||
delete api.defaults.headers.common['Authorization']
|
||||
}
|
||||
|
||||
// Restore auth header on init
|
||||
if (token.value) {
|
||||
api.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
|
||||
}
|
||||
|
||||
async function login(email, password) {
|
||||
const { data } = await api.post('/admin/login', { email, password })
|
||||
setAuth(data.token, { email: data.email, name: data.name })
|
||||
return data
|
||||
}
|
||||
|
||||
async function fetchMe() {
|
||||
try {
|
||||
const { data } = await api.get('/admin/me')
|
||||
user.value = data
|
||||
} catch {
|
||||
logout()
|
||||
}
|
||||
}
|
||||
|
||||
return { token, user, isAuthenticated, login, logout, fetchMe, setAuth }
|
||||
})
|
||||
Reference in New Issue
Block a user