Files
ai-learning-platform/frontend/src/lib/auth.ts
T
yuzhiran-dev 23edb74bce feat: 支付闭环 + 运营助手 Tool Calling + 管理后台完善
- 支付系统:微信支付 mock 自动完成、NATIVE 扫码支付、JSAPI 集成
- 运营助手:Tool Calling 架构,19 个可执行工具,AI 驱动操作
- 角色管理:表格布局 + Dialog 表单 + 权限勾选
- 配置统一:config.ts 单一数据源
- API 审计:补齐 status toggle / comments 端点
- 暗黑模式硬件编码颜色全部替换为 CSS 变量
2026-05-20 18:29:00 +08:00

91 lines
2.6 KiB
TypeScript

import { API_BASE } from '@/lib/config';
export function getToken(): string | null {
if (typeof window === 'undefined') return null;
return localStorage.getItem('token');
}
export function getAdminToken(): string | null {
if (typeof window === 'undefined') return null;
return localStorage.getItem('adminToken');
}
export function getRefreshToken(): string | null {
if (typeof window === 'undefined') return null;
return localStorage.getItem('refreshToken');
}
export function setTokens(accessToken: string, refreshToken?: string) {
localStorage.setItem('token', accessToken);
if (refreshToken) localStorage.setItem('refreshToken', refreshToken);
}
export function clearTokens() {
localStorage.removeItem('token');
localStorage.removeItem('refreshToken');
}
export function clearAdminToken() {
localStorage.removeItem('adminToken');
}
export function isLoggedIn(): boolean {
return !!getToken();
}
export function isAdminLoggedIn(): boolean {
return !!getAdminToken();
}
export async function adminApiFetch(url: string, opts: RequestInit = {}): Promise<Response> {
const token = getAdminToken();
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(opts.headers as Record<string, string> || {}),
};
if (token) headers['Authorization'] = `Bearer ${token}`;
return fetch(`${API_BASE}${url}`, { ...opts, headers });
}
export async function refreshToken(): Promise<string | null> {
const token = getToken();
const refreshTk = getRefreshToken();
if (!token && !refreshTk) return null;
try {
const res = await fetch(`${API_BASE}/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ accessToken: token }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.message);
setTokens(data.accessToken, data.refreshToken);
return data.accessToken;
} catch {
clearTokens();
return null;
}
}
export async function apiFetch(url: string, opts: RequestInit = {}): Promise<Response> {
const token = getToken();
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(opts.headers as Record<string, string> || {}),
};
if (token) headers['Authorization'] = `Bearer ${token}`;
let res = await fetch(`${API_BASE}${url}`, { ...opts, headers });
if (res.status === 401 && token) {
const newToken = await refreshToken();
if (newToken) {
headers['Authorization'] = `Bearer ${newToken}`;
res = await fetch(`${API_BASE}${url}`, { ...opts, headers });
}
}
return res;
}