64 lines
1.6 KiB
TypeScript
64 lines
1.6 KiB
TypeScript
import { create } from "zustand"
|
|
import type { User, UserRole, VerificationStatus } from "@/lib/types"
|
|
|
|
interface AuthState {
|
|
isAuthenticated: boolean
|
|
currentRole: UserRole
|
|
verifiedRoles: UserRole[]
|
|
verificationStatus: Partial<Record<UserRole, VerificationStatus>>
|
|
user: User | null
|
|
switchRole: (role: UserRole) => void
|
|
submitVerification: (role: UserRole) => void
|
|
login: (user: User, verifiedRoles?: UserRole[]) => void
|
|
logout: () => void
|
|
}
|
|
|
|
export const useAuthStore = create<AuthState>((set, get) => ({
|
|
isAuthenticated: false,
|
|
currentRole: "consumer",
|
|
verifiedRoles: ["consumer"],
|
|
verificationStatus: { consumer: "approved" },
|
|
user: null,
|
|
switchRole: (role) => {
|
|
const { verifiedRoles } = get()
|
|
if (verifiedRoles.includes(role)) {
|
|
set({ currentRole: role })
|
|
}
|
|
},
|
|
submitVerification: (role) =>
|
|
set((state) => {
|
|
if (state.verifiedRoles.includes(role)) {
|
|
return state
|
|
}
|
|
|
|
return {
|
|
verificationStatus: {
|
|
...state.verificationStatus,
|
|
[role]: "pending",
|
|
},
|
|
}
|
|
}),
|
|
login: (user, verifiedRoles = ["consumer"]) =>
|
|
set({
|
|
isAuthenticated: true,
|
|
user,
|
|
currentRole: user.role,
|
|
verifiedRoles,
|
|
verificationStatus: verifiedRoles.reduce<Partial<Record<UserRole, VerificationStatus>>>(
|
|
(acc, role) => {
|
|
acc[role] = "approved"
|
|
return acc
|
|
},
|
|
{},
|
|
),
|
|
}),
|
|
logout: () =>
|
|
set({
|
|
isAuthenticated: false,
|
|
currentRole: "consumer",
|
|
verifiedRoles: ["consumer"],
|
|
verificationStatus: { consumer: "approved" },
|
|
user: null,
|
|
}),
|
|
}))
|