feat: 用户系统 — 注册/登录 + 数据云同步(收藏/最近/记录/书签) + 工具文件云端留档
This commit is contained in:
1 parent
fed65ceb80
commit
580c5997b4
12 files changed
+754
No files matched your search
@@ -0,0 +1,119 @@
|
||||
import { apiFetch, useUserAuth } from './user-auth';
|
||||
|
||||
// localStorage keys synced to the cloud
|
||||
const SYNC_KEYS = [
|
||||
'favoriteToolsName',
|
||||
'it-tools-recent-tools',
|
||||
'it-tools-bookmarks:sites',
|
||||
'menu-tool-option:collapsed-categories',
|
||||
];
|
||||
|
||||
function collectLocal(): Record<string, any> {
|
||||
const data: Record<string, any> = {};
|
||||
for (const k of SYNC_KEYS) {
|
||||
const v = localStorage.getItem(k);
|
||||
if (v !== null) {
|
||||
data[k] = v;
|
||||
}
|
||||
}
|
||||
// gen-history:* records
|
||||
const hist: Record<string, string> = {};
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const k = localStorage.key(i);
|
||||
if (k && k.startsWith('gen-history:')) {
|
||||
hist[k] = localStorage.getItem(k) ?? '';
|
||||
}
|
||||
}
|
||||
if (Object.keys(hist).length > 0) {
|
||||
data['__gen-history'] = hist;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function applyLocal(data: Record<string, any>) {
|
||||
for (const [k, v] of Object.entries(data)) {
|
||||
if (k === '__gen-history') {
|
||||
for (const [hk, hv] of Object.entries(v as Record<string, string>)) {
|
||||
localStorage.setItem(hk, hv);
|
||||
}
|
||||
}
|
||||
else if (typeof v === 'string') {
|
||||
localStorage.setItem(k, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** merge two string arrays parsed from JSON storage (union, server items appended) */
|
||||
function mergeJsonArrays(a: string, b: string, keyField: string | null): string {
|
||||
try {
|
||||
const arrA = JSON.parse(a);
|
||||
const arrB = JSON.parse(b);
|
||||
if (!Array.isArray(arrA) || !Array.isArray(arrB)) {
|
||||
return b;
|
||||
}
|
||||
const seen = new Set(arrA.map((x: any) => (keyField ? x?.[keyField] : x)));
|
||||
for (const item of arrB) {
|
||||
const id = keyField ? item?.[keyField] : item;
|
||||
if (id !== undefined && !seen.has(id)) {
|
||||
arrA.push(item);
|
||||
seen.add(id);
|
||||
}
|
||||
}
|
||||
return JSON.stringify(arrA);
|
||||
}
|
||||
catch {
|
||||
return b;
|
||||
}
|
||||
}
|
||||
|
||||
function mergeData(server: Record<string, any>, mine: Record<string, any>): Record<string, any> {
|
||||
const out: Record<string, any> = { ...server };
|
||||
for (const [k, v] of Object.entries(mine)) {
|
||||
if (k === '__gen-history') {
|
||||
out[k] = { ...(server[k] ?? {}), ...(v as Record<string, string>) };
|
||||
}
|
||||
else if (out[k] === undefined) {
|
||||
out[k] = v;
|
||||
}
|
||||
else if (typeof v === 'string' && typeof out[k] === 'string') {
|
||||
// prefer the larger/newer list per key
|
||||
if (k === 'favoriteToolsName' || k === 'it-tools-recent-tools' || k === 'it-tools-bookmarks:sites') {
|
||||
out[k] = mergeJsonArrays(out[k], v, k === 'it-tools-recent-tools' ? 'path' : null);
|
||||
}
|
||||
else {
|
||||
out[k] = v; // scalar configs: local wins
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function useCloudSync() {
|
||||
const { isLoggedIn } = useUserAuth();
|
||||
|
||||
/** push local data up, pull server data down, merge both ways */
|
||||
async function syncNow(): Promise<{ ok: boolean; message: string }> {
|
||||
if (!isLoggedIn.value) {
|
||||
return { ok: false, message: '未登录' };
|
||||
}
|
||||
const mine = collectLocal();
|
||||
const { status, body } = await apiFetch('/user/data');
|
||||
if (status !== 200) {
|
||||
return { ok: false, message: body.message || '同步失败' };
|
||||
}
|
||||
const server = body.data?.data ?? {};
|
||||
const merged = mergeData(server, mine);
|
||||
const put = await apiFetch('/user/data', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ data: merged }),
|
||||
});
|
||||
if (put.status !== 200) {
|
||||
return { ok: false, message: put.body.message || '同步失败' };
|
||||
}
|
||||
applyLocal(merged);
|
||||
return { ok: true, message: '同步完成' };
|
||||
}
|
||||
|
||||
return { syncNow, isLoggedIn };
|
||||
}
|
||||
@@ -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