Spaces:
Running
Running
File size: 1,216 Bytes
96c0248 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import axios from "axios";
import type { AuthUser } from "../types";
export interface AuthCredentials {
username: string;
password: string;
}
const authStorageKey = "resource-portal.auth";
export const getStoredCredentials = (): AuthCredentials | null => {
try {
const raw = window.sessionStorage.getItem(authStorageKey);
if (!raw) return null;
const parsed = JSON.parse(raw) as AuthCredentials;
return parsed.username && parsed.password ? parsed : null;
} catch {
return null;
}
};
export const setStoredCredentials = (credentials: AuthCredentials) => {
window.sessionStorage.setItem(authStorageKey, JSON.stringify(credentials));
};
export const clearStoredCredentials = () => {
window.sessionStorage.removeItem(authStorageKey);
};
export const api = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL ?? "/api/v1",
});
api.interceptors.request.use((config) => {
const credentials = getStoredCredentials();
if (credentials && !config.auth) {
config.auth = credentials;
}
return config;
});
export const getCurrentUser = async (credentials?: AuthCredentials) =>
(await api.get<AuthUser>("/me", credentials ? { auth: credentials } : undefined)).data;
|