Files
CRM_Montzar/apps/web/src/stores/auth.ts
T

112 lines
2.7 KiB
TypeScript
Raw Normal View History

import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import type {
AuthUserDto,
LoginChallengeResponse,
LoginResponse,
RegisterChallengeResponse,
RegisterOrganizationRequest,
} from '@mento/shared';
import { api } from '@/lib/api';
const TOKEN_KEY = 'mento_token';
const USER_KEY = 'mento_user';
const LEGACY_KEYS = ['ment_token', 'ment_user'] as const;
function readStoredToken(): string | null {
return localStorage.getItem(TOKEN_KEY) ?? localStorage.getItem('ment_token');
}
function readStoredUser(): AuthUserDto | null {
const raw = localStorage.getItem(USER_KEY) ?? localStorage.getItem('ment_user');
if (!raw) return null;
try {
return JSON.parse(raw) as AuthUserDto;
} catch {
return null;
}
}
function clearLegacy() {
for (const key of LEGACY_KEYS) localStorage.removeItem(key);
}
export const useAuthStore = defineStore('auth', () => {
const token = ref<string | null>(readStoredToken());
const user = ref<AuthUserDto | null>(readStoredUser());
const isAuthenticated = computed(() => Boolean(token.value));
function persist(payload: LoginResponse) {
token.value = payload.accessToken;
user.value = payload.user;
localStorage.setItem(TOKEN_KEY, payload.accessToken);
localStorage.setItem(USER_KEY, JSON.stringify(payload.user));
clearLegacy();
}
async function login(identifier: string, password: string) {
const { data } = await api.post<LoginResponse>('/auth/login', {
identifier,
password,
});
persist(data);
}
async function requestLoginOtp(mobile: string) {
const { data } = await api.post<LoginChallengeResponse>('/auth/login/otp', {
mobile,
});
return data;
}
async function verifyLoginOtp(challengeId: string, code: string) {
const { data } = await api.post<LoginResponse>('/auth/login/otp/verify', {
challengeId,
code,
});
persist(data);
}
async function startRegister(payload: RegisterOrganizationRequest) {
const { data } = await api.post<RegisterChallengeResponse>(
'/auth/register',
payload,
);
return data;
}
async function verifyRegister(
challengeId: string,
mobileCode: string,
emailCode?: string,
) {
const { data } = await api.post<LoginResponse>('/auth/register/verify', {
challengeId,
mobileCode,
...(emailCode ? { emailCode } : {}),
});
persist(data);
}
function logout() {
token.value = null;
user.value = null;
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(USER_KEY);
clearLegacy();
}
return {
token,
user,
isAuthenticated,
login,
requestLoginOtp,
verifyLoginOtp,
startRegister,
verifyRegister,
logout,
};
});