feat: 用户系统 — 注册/登录 + 数据云同步(收藏/最近/记录/书签) + 工具文件云端留档

This commit is contained in:
personal82555 committed 2026-10-12 10:15:27 +08:00
1 parent fed65ceb80
commit 580c5997b4
12 files changed
+754

No files matched your search

+250
View File
@@ -0,0 +1,250 @@
<script setup lang="ts">
import { NIcon } from 'naive-ui';
import { User as UserIcon, CloudUpload, Logout } from '@vicons/tabler';
import { useUserAuth } from '@/composable/user-auth';
import { useCloudSync } from '@/composable/cloud-sync';
const { isLoggedIn, username, login, register, logout } = useUserAuth();
const { syncNow } = useCloudSync();
const showLogin = ref(false);
const mode = ref<'login' | 'register'>('login');
const formUser = ref('');
const formPass = ref('');
const formPass2 = ref('');
const error = ref('');
const busy = ref(false);
const notice = ref('');
let noticeTimer: ReturnType<typeof setTimeout> | undefined;
function setNotice(msg: string) {
notice.value = msg;
if (noticeTimer) {
clearTimeout(noticeTimer);
}
noticeTimer = setTimeout(() => (notice.value = ''), 4000);
}
async function submit() {
error.value = '';
if (mode.value === 'register' && formPass.value !== formPass2.value) {
error.value = '两次输入的密码不一致';
return;
}
busy.value = true;
try {
if (mode.value === 'login') {
await login(formUser.value.trim(), formPass.value);
}
else {
await register(formUser.value.trim(), formPass.value);
}
showLogin.value = false;
formPass.value = '';
formPass2.value = '';
setNotice('登录成功,正在同步数据…');
const r = await syncNow();
setNotice(r.ok ? '✓ 数据已合并同步到云端' : r.message);
}
catch (e: any) {
error.value = String(e?.message || e);
}
finally {
busy.value = false;
}
}
async function doSync() {
setNotice('同步中…');
const r = await syncNow();
setNotice(r.ok ? '✓ 同步完成,云端与本机数据已合并' : r.message);
}
function doLogout() {
logout();
setNotice('已退出登录(云端数据保留)');
}
function switchMode() {
mode.value = mode.value === 'login' ? 'register' : 'login';
error.value = '';
}
</script>
<template>
<div class="user-root">
<div v-if="notice" class="user-notice">
{{ notice }}
</div>
<!-- not logged in -->
<c-button v-if="!isLoggedIn" size="small" round :bordered="false" @click="showLogin = true">
<NIcon :component="UserIcon" mr-4px />
登录
</c-button>
<!-- logged in -->
<div v-else class="user-chip" :title="`当前用户:${username}`">
<NIcon :component="UserIcon" />
<span class="user-name">{{ username }}</span>
<a href="javascript:;" class="user-action" title="同步数据到云端(收藏/最近使用/生成记录/网站收藏/上传文件)" @click="doSync">
<NIcon :component="CloudUpload" />
</a>
<a href="javascript:;" class="user-action" title="退出登录" @click="doLogout">
<NIcon :component="Logout" />
</a>
</div>
<!-- login modal -->
<div v-if="showLogin" class="user-mask" @click.self="showLogin = false">
<div class="user-modal">
<div class="user-modal-title">
{{ mode === 'login' ? '登录' : '注册' }}
</div>
<div class="user-modal-sub">
登录后收藏、最近使用、生成记录、网站收藏等数据自动同步云端,换电脑登录即恢复;工具上传的文件也会保存到云端。
</div>
<input v-model="formUser" class="user-input" placeholder="用户名(3-32位字母/数字/下划线/中文)" autocomplete="username" @keyup.enter="submit">
<input v-model="formPass" class="user-input" type="password" placeholder="密码(至少 6 位)" :autocomplete="mode === 'login' ? 'current-password' : 'new-password'" @keyup.enter="submit">
<input v-if="mode === 'register'" v-model="formPass2" class="user-input" type="password" placeholder="确认密码" autocomplete="new-password" @keyup.enter="submit">
<div v-if="error" class="user-error">
{{ error }}
</div>
<div class="user-modal-actions">
<a href="javascript:;" class="user-switch" @click="switchMode">
{{ mode === 'login' ? '没有账号?注册' : '已有账号?登录' }}
</a>
<div>
<c-button size="small" @click="showLogin = false">
取消
</c-button>
<c-button size="small" type="primary" ml-8px :disabled="busy || !formUser || !formPass" @click="submit">
{{ busy ? '请稍候…' : (mode === 'login' ? '登录' : '注册并登录') }}
</c-button>
</div>
</div>
</div>
</div>
</div>
</template>
<style lang="less" scoped>
.user-root {
position: relative;
}
.user-notice {
position: fixed;
top: 60px;
right: 16px;
z-index: 9999;
background: #18a058;
color: #fff;
font-size: 13px;
padding: 8px 16px;
border-radius: 8px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}
.user-chip {
display: inline-flex;
align-items: center;
gap: 6px;
border: 1px solid rgba(128, 128, 128, 0.35);
border-radius: 999px;
padding: 3px 12px;
font-size: 13px;
.user-name {
max-width: 110px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.user-action {
display: inline-flex;
opacity: 0.6;
transition: opacity 0.15s;
&:hover {
opacity: 1;
color: #18a058;
}
}
}
.user-mask {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.35);
z-index: 9998;
display: flex;
align-items: center;
justify-content: center;
}
.user-modal {
width: 360px;
max-width: 92vw;
background: #fff;
border-radius: 14px;
padding: 22px 24px;
box-shadow: 0 12px 48px rgba(0, 0, 0, 0.2);
.user-modal-title {
font-size: 18px;
font-weight: 800;
margin-bottom: 6px;
}
.user-modal-sub {
font-size: 12px;
opacity: 0.6;
line-height: 1.7;
margin-bottom: 14px;
}
.user-input {
width: 100%;
box-sizing: border-box;
border: 1px solid rgba(128, 128, 128, 0.35);
border-radius: 8px;
padding: 9px 12px;
font-size: 14px;
margin-bottom: 10px;
outline: none;
transition: border-color 0.15s;
&:focus {
border-color: #18a058;
}
}
.user-error {
color: #d03050;
font-size: 12.5px;
margin-bottom: 8px;
}
.user-modal-actions {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 4px;
.user-switch {
font-size: 12.5px;
color: #18a058;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
}
}
</style>
+119
View File
@@ -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 };
}
+98
View File
@@ -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 };
}
+3
View File
@@ -14,6 +14,7 @@ import type { ToolCategory } from '@/tools/tools.types';
import { useToolStore } from '@/tools/tools.store';
import { useTracker } from '@/modules/tracker/tracker.services';
import CollapsibleToolMenu from '@/components/CollapsibleToolMenu.vue';
import UserMenu from '@/components/UserMenu.vue';
const themeVars = useThemeVars();
const styleStore = useStyleStore();
@@ -103,6 +104,8 @@ const tools = computed<ToolCategory[]>(() => [
<NavbarButtons v-if="!styleStore.isSmallScreen" />
</div>
<UserMenu />
<c-tooltip position="bottom" :tooltip="'查看授权功能与购买'">
<RouterLink to="/pricing" class="pricing-link">
<c-button
+5
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { useUserAuth } from '@/composable/user-auth';
import { licenseHeaders } from '../license/license';
import GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
@@ -67,8 +68,12 @@ function onDrop(e: DragEvent) {
handleFile(e.dataTransfer?.files?.[0]);
}
const { cloudUpload } = useUserAuth();
function handleFile(file?: File | null) {
if (!file) return;
cloudUpload(file, 'ai-retouch').catch(() => {}); // 云端留档(登录后)
if (!file.type.startsWith('image/')) {
error.value = '请选择图片文件(png/jpg/webp 等)';
return;
+5
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { useUserAuth } from '@/composable/user-auth';
import GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
@@ -22,10 +23,14 @@ function pickFile() {
fileInput.value?.click();
}
const { cloudUpload } = useUserAuth();
async function handleFile(file?: File | null) {
if (!file) {
return;
}
cloudUpload(file, 'image-ocr').catch(() => {}); // 云端留档(登录后)
if (!file.type.startsWith('image/')) {
error.value = '请选择图片文件(png/jpg/webp/bmp 等)';
return;
+6
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { useUserAuth } from '@/composable/user-auth';
import exifr from 'exifr';
import QRCode from 'qrcode';
import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader';
@@ -100,7 +101,12 @@ function onDrop(e: DragEvent) {
addFiles(Array.from(e.dataTransfer?.files ?? []));
}
const { cloudUpload } = useUserAuth();
function addFiles(list: File[]) {
for (const f of list) {
cloudUpload(f, 'image-tools').catch(() => {});
}
const imgs = list.filter(f => f.type.startsWith('image/'));
if (!imgs.length) {
errorMsg.value = '请选择图片文件';
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { useUserAuth } from '@/composable/user-auth';
import GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
@@ -248,6 +249,8 @@ async function pickPdf() {
pdfInput.value?.click();
}
const { cloudUpload } = useUserAuth();
async function onPdfFile(e: Event) {
const input = e.target as HTMLInputElement;
const file = input.files?.[0];
@@ -255,6 +258,7 @@ async function onPdfFile(e: Event) {
if (!file) {
return;
}
cloudUpload(file, 'label-designer').catch(() => {});
loadingPdf.value = true;
error.value = '';
try {
+4
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { useUserAuth } from '@/composable/user-auth';
import GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
@@ -77,7 +78,10 @@ function onPaste(e: ClipboardEvent) {
}
}
const { cloudUpload } = useUserAuth();
async function processFile(file: File) {
cloudUpload(file, 'pdf-ocr').catch(() => {}); // 云端留档(登录后)
if (!file.name.toLowerCase().endsWith('.pdf') && file.type !== 'application/pdf') {
error.value = '请选择 PDF 文件';
return;
+6
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { useUserAuth } from '@/composable/user-auth';
import { degrees, PDFDocument, rgb } from '@cantoo/pdf-lib';
import { getDocument, GlobalWorkerOptions } from 'pdfjs-dist';
import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.min.js?url';
@@ -71,7 +72,12 @@ function onDrop(e: DragEvent) {
addFiles(Array.from(e.dataTransfer?.files ?? []));
}
const { cloudUpload } = useUserAuth();
function addFiles(list: File[]) {
for (const f of list) {
cloudUpload(f, 'pdf-tools').catch(() => {});
}
const pdfs = list.filter(f => f.type === 'application/pdf' || f.name.toLowerCase().endsWith('.pdf'));
if (!pdfs.length) {
errorMsg.value = '请选择 PDF 文件';