102 lines
3.4 KiB
TypeScript
102 lines
3.4 KiB
TypeScript
import { computed, ref } from 'vue';
|
|
import { licenseHeaders } from '@/tools/license/license';
|
|
|
|
const TOKEN_KEY = 'it-tools-auth';
|
|
|
|
export interface AuthState {
|
|
token: string;
|
|
username: string;
|
|
role?: string;
|
|
}
|
|
|
|
function loadState(): AuthState | null {
|
|
try {
|
|
const v = JSON.parse(localStorage.getItem(TOKEN_KEY) ?? 'null');
|
|
if (v && typeof v.token === 'string' && typeof v.username === 'string') {
|
|
return v;
|
|
}
|
|
}
|
|
catch { /* ignore */ }
|
|
return null;
|
|
}
|
|
|
|
const state = ref<AuthState | null>(loadState());
|
|
|
|
function save(s: AuthState | null) {
|
|
state.value = s;
|
|
if (s) {
|
|
localStorage.setItem(TOKEN_KEY, JSON.stringify(s));
|
|
}
|
|
else {
|
|
localStorage.removeItem(TOKEN_KEY);
|
|
}
|
|
}
|
|
|
|
export async function apiFetch(path: string, init: RequestInit = {}): Promise<any> {
|
|
const headers = new Headers(init.headers);
|
|
if (state.value?.token) {
|
|
headers.set('Authorization', `Bearer ${state.value.token}`);
|
|
}
|
|
const res = await fetch(`/relay${path}`, { ...init, headers });
|
|
const body = await res.json().catch(() => ({}));
|
|
if (res.status === 401 && path !== '/user/login' && path !== '/user/register') {
|
|
// token expired/invalid -> logout locally
|
|
save(null);
|
|
window.dispatchEvent(new CustomEvent('it-tools-auth-changed'));
|
|
}
|
|
return { status: res.status, body };
|
|
}
|
|
|
|
export function useUserAuth() {
|
|
const isLoggedIn = computed(() => state.value !== null);
|
|
const username = computed(() => state.value?.username ?? '');
|
|
const isAdmin = computed(() => state.value?.role === 'admin');
|
|
|
|
async function login(u: string, p: string, captchaId = '', captchaCode = '') {
|
|
const { status, body } = await apiFetch('/user/login', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', ...licenseHeaders() },
|
|
body: JSON.stringify({ username: u, password: p, captcha_id: captchaId, captcha_code: captchaCode }),
|
|
});
|
|
if (status !== 200) {
|
|
throw new Error(body.message || '登录失败');
|
|
}
|
|
save({ token: body.data.token, username: body.data.username, role: body.data.role });
|
|
window.dispatchEvent(new CustomEvent('it-tools-auth-changed'));
|
|
return body.data.username;
|
|
}
|
|
|
|
async function register(u: string, p: string, captchaId = '', captchaCode = '') {
|
|
const { status, body } = await apiFetch('/user/register', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', ...licenseHeaders() },
|
|
body: JSON.stringify({ username: u, password: p, captcha_id: captchaId, captcha_code: captchaCode }),
|
|
});
|
|
if (status !== 200) {
|
|
throw new Error(body.message || '注册失败');
|
|
}
|
|
save({ token: body.data.token, username: body.data.username });
|
|
window.dispatchEvent(new CustomEvent('it-tools-auth-changed'));
|
|
return body.data.username;
|
|
}
|
|
|
|
function logout() {
|
|
save(null);
|
|
window.dispatchEvent(new CustomEvent('it-tools-auth-changed'));
|
|
}
|
|
|
|
/** upload a file to the cloud (only when logged in) */
|
|
async function cloudUpload(file: File | Blob, kind: string, name?: string): Promise<{ id: string } | null> {
|
|
if (!state.value) {
|
|
return null;
|
|
}
|
|
const fd = new FormData();
|
|
fd.append('file', file, name ?? (file as File).name ?? 'file');
|
|
fd.append('kind', kind);
|
|
const { status, body } = await apiFetch('/user/files', { method: 'POST', body: fd });
|
|
return status === 200 ? body.data : null;
|
|
}
|
|
|
|
return { isLoggedIn, username, isAdmin, login, register, logout, cloudUpload };
|
|
}
|