feat: 用户系统 — 注册/登录 + 数据云同步(收藏/最近/记录/书签) + 工具文件云端留档
This commit is contained in:
1 parent
fed65ceb80
commit
580c5997b4
12 files changed
+754
No files matched your search
@@ -0,0 +1,98 @@
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
const TOKEN_KEY = 'it-tools-auth';
|
||||
|
||||
export interface AuthState {
|
||||
token: string;
|
||||
username: 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 ?? '');
|
||||
|
||||
async function login(u: string, p: string) {
|
||||
const { status, body } = await apiFetch('/user/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: u, password: p }),
|
||||
});
|
||||
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;
|
||||
}
|
||||
|
||||
async function register(u: string, p: string) {
|
||||
const { status, body } = await apiFetch('/user/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: u, password: p }),
|
||||
});
|
||||
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, login, register, logout, cloudUpload };
|
||||
}
|
||||
Reference in new issue
Block a user