86 lines
1.9 KiB
TypeScript
86 lines
1.9 KiB
TypeScript
import { apiRequest } from "@/lib/api";
|
|
|
|
const TOKEN_STORAGE_KEY = "mira_access_token";
|
|
|
|
export type AuthUser = {
|
|
id: string;
|
|
email: string;
|
|
name: string;
|
|
role: "super_admin" | "agency_user" | "client_viewer";
|
|
status: string;
|
|
};
|
|
|
|
type LoginResponse = {
|
|
access_token: string;
|
|
token_type: "Bearer";
|
|
user: AuthUser;
|
|
};
|
|
|
|
type AcceptInvitationResponse = {
|
|
message: string;
|
|
user: AuthUser;
|
|
};
|
|
|
|
type MeResponse = {
|
|
user: AuthUser;
|
|
};
|
|
|
|
export function getStoredToken() {
|
|
return sessionStorage.getItem(TOKEN_STORAGE_KEY);
|
|
}
|
|
|
|
export function storeToken(token: string) {
|
|
localStorage.removeItem(TOKEN_STORAGE_KEY);
|
|
sessionStorage.setItem(TOKEN_STORAGE_KEY, token);
|
|
}
|
|
|
|
export function clearStoredToken() {
|
|
localStorage.removeItem(TOKEN_STORAGE_KEY);
|
|
sessionStorage.removeItem(TOKEN_STORAGE_KEY);
|
|
}
|
|
|
|
export async function logout() {
|
|
await apiRequest<{ message: string }>("/auth/logout", {
|
|
method: "POST",
|
|
}).catch(() => undefined);
|
|
localStorage.removeItem(TOKEN_STORAGE_KEY);
|
|
sessionStorage.removeItem(TOKEN_STORAGE_KEY);
|
|
}
|
|
|
|
export async function login(email: string, password: string) {
|
|
const response = await apiRequest<LoginResponse>("/auth/login", {
|
|
method: "POST",
|
|
body: JSON.stringify({ email, password }),
|
|
});
|
|
|
|
storeToken(response.access_token);
|
|
return response;
|
|
}
|
|
|
|
export async function acceptInvitation(token: string, name: string, password: string) {
|
|
const response = await apiRequest<AcceptInvitationResponse>("/auth/invitations/accept", {
|
|
method: "POST",
|
|
body: JSON.stringify({ token, name, password }),
|
|
});
|
|
|
|
return response;
|
|
}
|
|
|
|
export async function refreshSession() {
|
|
const response = await apiRequest<LoginResponse>("/auth/refresh", {
|
|
method: "POST",
|
|
});
|
|
|
|
storeToken(response.access_token);
|
|
return response;
|
|
}
|
|
|
|
export async function loadCurrentUser(token: string) {
|
|
const response = await apiRequest<MeResponse>("/me", {
|
|
method: "GET",
|
|
token,
|
|
});
|
|
|
|
return response.user;
|
|
}
|