Files
FunConnect/admin-panel/src/stores/authStore.ts

46 lines
1.0 KiB
TypeScript
Raw Normal View History

import { create } from 'zustand'
import { persist, createJSONStorage } 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',
}
)
)