Files
tgex-frontend/lib/api/auth.ts
2025-12-29 10:12:13 +03:00

65 lines
1.5 KiB
TypeScript

// ============================================================================
// Auth API
// ============================================================================
import { api, clearAuthTokens } from "./client";
import { STORAGE_KEYS } from "@/lib/utils/constants";
import type { User, AuthCompleteResponse } from "@/lib/types/api";
export const authApi = {
/**
* Complete auth with one-time token from bot
* GET /auth/complete?token=...
*/
complete: async (token: string): Promise<AuthCompleteResponse> => {
const response = await api.get<AuthCompleteResponse>(
`/auth/complete?token=${token}`,
{ requireAuth: false }
);
// Save access token to storage
if (typeof window !== "undefined") {
localStorage.setItem(STORAGE_KEYS.ACCESS_TOKEN, response.access_token);
}
return response;
},
/**
* Get current user info
* GET /auth/me
*/
me: () => api.get<User>("/auth/me"),
/**
* Logout (clear tokens)
*/
logout: () => {
clearAuthTokens();
},
/**
* Get user from storage (no API call)
*/
getUserFromStorage: (): User | null => {
if (typeof window === "undefined") return null;
const userJson = localStorage.getItem(STORAGE_KEYS.USER);
if (!userJson) return null;
try {
return JSON.parse(userJson);
} catch {
return null;
}
},
/**
* Check if user is authenticated
*/
isAuthenticated: (): boolean => {
if (typeof window === "undefined") return false;
return !!localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);
},
};