initial: standalone repo from monorepo split
This commit is contained in:
77
src/lib/auth.ts
Normal file
77
src/lib/auth.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { api } from './api';
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
mustChangePassword?: boolean;
|
||||
roles: string[];
|
||||
permissions: string[];
|
||||
accessMap: Record<string, Record<string, boolean>> | 'all';
|
||||
tenantRoles: { id: string; name: string; slug: string }[];
|
||||
tenant: {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
settings: Record<string, unknown>;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
success: boolean;
|
||||
data: {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
mustChangePassword?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export async function login(email: string, password: string): Promise<AuthUser> {
|
||||
const res = await api.post<LoginResponse>('/auth/login', { email, password });
|
||||
const { accessToken, refreshToken, mustChangePassword } = res.data.data;
|
||||
|
||||
localStorage.setItem('accessToken', accessToken);
|
||||
localStorage.setItem('refreshToken', refreshToken);
|
||||
|
||||
const user = await getProfile();
|
||||
// Merge the flag from login response if not already in profile
|
||||
if (mustChangePassword && !user.mustChangePassword) {
|
||||
user.mustChangePassword = true;
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function getProfile(): Promise<AuthUser> {
|
||||
const res = await api.get<{ success: boolean; data: AuthUser }>('/auth/profile');
|
||||
return res.data.data;
|
||||
}
|
||||
|
||||
export async function refreshTokens() {
|
||||
const refreshToken = localStorage.getItem('refreshToken');
|
||||
if (!refreshToken) throw new Error('No refresh token');
|
||||
|
||||
const res = await api.post<LoginResponse>('/auth/refresh', { refreshToken });
|
||||
const { accessToken, refreshToken: newRefresh } = res.data.data;
|
||||
|
||||
localStorage.setItem('accessToken', accessToken);
|
||||
localStorage.setItem('refreshToken', newRefresh);
|
||||
}
|
||||
|
||||
export function logout() {
|
||||
const token = localStorage.getItem('accessToken');
|
||||
if (token) {
|
||||
api.post('/auth/logout').catch(() => {});
|
||||
}
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
}
|
||||
|
||||
export function isAuthenticated(): boolean {
|
||||
return !!localStorage.getItem('accessToken');
|
||||
}
|
||||
|
||||
export async function changePassword(currentPassword: string, newPassword: string) {
|
||||
const res = await api.post('/auth/change-password', { currentPassword, newPassword });
|
||||
return res.data;
|
||||
}
|
||||
Reference in New Issue
Block a user