52 lines
1.6 KiB
TypeScript
52 lines
1.6 KiB
TypeScript
import { create } from 'zustand';
|
|
import * as SecureStore from 'expo-secure-store';
|
|
import { api } from '../services/api';
|
|
|
|
interface AuthState {
|
|
token: string | null;
|
|
tenantSlug: string | null;
|
|
user: any | null;
|
|
isLoading: boolean;
|
|
login: (tenantSlug: string, username: string, password: string) => Promise<void>;
|
|
logout: () => Promise<void>;
|
|
hydrate: () => Promise<void>;
|
|
}
|
|
|
|
export const useAuthStore = create<AuthState>((set) => ({
|
|
token: null,
|
|
tenantSlug: null,
|
|
user: null,
|
|
isLoading: true,
|
|
|
|
hydrate: async () => {
|
|
try {
|
|
const token = await SecureStore.getItemAsync('auth_token');
|
|
const tenantSlug = await SecureStore.getItemAsync('tenant_slug');
|
|
if (token && tenantSlug) {
|
|
const res = await api.get('/api/v1/auth/me');
|
|
set({ token, tenantSlug, user: res.data, isLoading: false });
|
|
} else {
|
|
set({ isLoading: false });
|
|
}
|
|
} catch {
|
|
await SecureStore.deleteItemAsync('auth_token');
|
|
await SecureStore.deleteItemAsync('tenant_slug');
|
|
set({ token: null, tenantSlug: null, user: null, isLoading: false });
|
|
}
|
|
},
|
|
|
|
login: async (tenantSlug, username, password) => {
|
|
const res = await api.post('/api/v1/auth/login', { tenantSlug, username, password });
|
|
const { token, user } = res.data;
|
|
await SecureStore.setItemAsync('auth_token', token);
|
|
await SecureStore.setItemAsync('tenant_slug', tenantSlug);
|
|
set({ token, tenantSlug, user });
|
|
},
|
|
|
|
logout: async () => {
|
|
await SecureStore.deleteItemAsync('auth_token');
|
|
await SecureStore.deleteItemAsync('tenant_slug');
|
|
set({ token: null, tenantSlug: null, user: null });
|
|
},
|
|
}));
|