46 lines
1.0 KiB
TypeScript
46 lines
1.0 KiB
TypeScript
import { create } from 'zustand'
|
|
import { persist } from 'zustand/middleware'
|
|
|
|
interface AuthState {
|
|
token: string | null
|
|
isAuthenticated: boolean
|
|
login: (username: string, password: string) => Promise<boolean>
|
|
logout: () => void
|
|
}
|
|
|
|
export const useAuthStore = create<AuthState>()(
|
|
persist(
|
|
(set) => ({
|
|
token: null,
|
|
isAuthenticated: false,
|
|
|
|
login: async (username: string, password: string) => {
|
|
try {
|
|
const res = await fetch('/api/v1/admin/login', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username, password }),
|
|
})
|
|
|
|
if (!res.ok) {
|
|
return false
|
|
}
|
|
|
|
const data = await res.json()
|
|
set({ token: data.token, isAuthenticated: true })
|
|
return true
|
|
} catch {
|
|
return false
|
|
}
|
|
},
|
|
|
|
logout: () => {
|
|
set({ token: null, isAuthenticated: false })
|
|
},
|
|
}),
|
|
{
|
|
name: 'funmc-admin-auth',
|
|
}
|
|
)
|
|
)
|