68 lines
1.8 KiB
TypeScript
68 lines
1.8 KiB
TypeScript
import { defineStore } from 'pinia';
|
|
import { computed, ref } from 'vue';
|
|
import type { PlatformAdminDto, PlatformLoginResponse } from '@mento/shared';
|
|
import { platformApi } from '@/lib/platform-api';
|
|
|
|
const TOKEN_KEY = 'mento_platform_token';
|
|
const ADMIN_KEY = 'mento_platform_admin';
|
|
|
|
function readStoredAdmin(): PlatformAdminDto | null {
|
|
const raw = localStorage.getItem(ADMIN_KEY);
|
|
if (!raw) return null;
|
|
try {
|
|
return JSON.parse(raw) as PlatformAdminDto;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export const usePlatformAuthStore = defineStore('platform-auth', () => {
|
|
const token = ref<string | null>(localStorage.getItem(TOKEN_KEY));
|
|
const admin = ref<PlatformAdminDto | null>(readStoredAdmin());
|
|
const isAuthenticated = computed(() => Boolean(token.value));
|
|
|
|
function persist(payload: PlatformLoginResponse) {
|
|
token.value = payload.accessToken;
|
|
admin.value = payload.admin;
|
|
localStorage.setItem(TOKEN_KEY, payload.accessToken);
|
|
localStorage.setItem(ADMIN_KEY, JSON.stringify(payload.admin));
|
|
}
|
|
|
|
async function login(mobile: string, password: string) {
|
|
const { data } = await platformApi.post<PlatformLoginResponse>(
|
|
'/platform/auth/login',
|
|
{ mobile, password },
|
|
);
|
|
persist(data);
|
|
}
|
|
|
|
function logout() {
|
|
token.value = null;
|
|
admin.value = null;
|
|
localStorage.removeItem(TOKEN_KEY);
|
|
localStorage.removeItem(ADMIN_KEY);
|
|
}
|
|
|
|
async function hydrate() {
|
|
if (!token.value) return;
|
|
try {
|
|
const { data } = await platformApi.get<PlatformAdminDto>('/platform/auth/me');
|
|
admin.value = data;
|
|
localStorage.setItem(ADMIN_KEY, JSON.stringify(data));
|
|
} catch {
|
|
logout();
|
|
}
|
|
}
|
|
|
|
if (token.value) void hydrate();
|
|
|
|
return {
|
|
token,
|
|
admin,
|
|
isAuthenticated,
|
|
login,
|
|
logout,
|
|
hydrate,
|
|
};
|
|
});
|