50 lines
1.4 KiB
TypeScript
50 lines
1.4 KiB
TypeScript
import { create } from 'zustand';
|
|
import { persist } from 'zustand/middleware';
|
|
import portalApi from './portal-api';
|
|
|
|
interface PortalSubscriber {
|
|
accountNumber: string;
|
|
firstName: string;
|
|
lastName: string;
|
|
}
|
|
|
|
interface PortalAuthState {
|
|
subscriber: PortalSubscriber | null;
|
|
portalToken: string | null;
|
|
tenantSlug: string | null;
|
|
isAuthenticated: boolean;
|
|
login: (tenantSlug: string, accountNumber: string, password: string) => Promise<void>;
|
|
logout: () => void;
|
|
}
|
|
|
|
export const usePortalAuthStore = create<PortalAuthState>()(
|
|
persist(
|
|
(set) => ({
|
|
subscriber: null,
|
|
portalToken: null,
|
|
tenantSlug: null,
|
|
isAuthenticated: false,
|
|
login: async (tenantSlug, accountNumber, password) => {
|
|
const res = await portalApi.post('/api/v1/portal/auth/login', {
|
|
tenantSlug,
|
|
accountNumber,
|
|
password,
|
|
});
|
|
const { accessToken } = res.data;
|
|
localStorage.setItem('portal_token', accessToken);
|
|
set({
|
|
portalToken: accessToken,
|
|
tenantSlug,
|
|
subscriber: { accountNumber, firstName: '', lastName: '' },
|
|
isAuthenticated: true,
|
|
});
|
|
},
|
|
logout: () => {
|
|
localStorage.removeItem('portal_token');
|
|
set({ subscriber: null, portalToken: null, tenantSlug: null, isAuthenticated: false });
|
|
},
|
|
}),
|
|
{ name: 'portal_auth' }
|
|
)
|
|
);
|