feat: 用户系统 — 注册/登录 + 数据云同步(收藏/最近/记录/书签) + 工具文件云端留档
This commit is contained in:
1 parent
fed65ceb80
commit
580c5997b4
12 files changed
+754
No files matched your search
Vendored
+1
@@ -233,6 +233,7 @@ declare module '@vue/runtime-core' {
|
||||
UrlParser: typeof import('./src/tools/url-parser/url-parser.vue')['default']
|
||||
UserAgentParser: typeof import('./src/tools/user-agent-parser/user-agent-parser.vue')['default']
|
||||
UserAgentResultCards: typeof import('./src/tools/user-agent-parser/user-agent-result-cards.vue')['default']
|
||||
UserMenu: typeof import('./src/components/UserMenu.vue')['default']
|
||||
UuidGenerator: typeof import('./src/tools/uuid-generator/uuid-generator.vue')['default']
|
||||
WifiQrCodeGenerator: typeof import('./src/tools/wifi-qr-code-generator/wifi-qr-code-generator.vue')['default']
|
||||
XmlFormatter: typeof import('./src/tools/xml-formatter/xml-formatter.vue')['default']
|
||||
|
||||
@@ -570,6 +570,216 @@ def activate_card(card_key: str, machine_id: str, contact_qq: str, replace: bool
|
||||
return code, ares
|
||||
|
||||
|
||||
|
||||
# ================= 用户系统(注册/登录/数据云同步/文件存储) =================
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import sqlite3
|
||||
import uuid
|
||||
|
||||
USER_DB = os.environ.get("USER_DB", "/app/data/users.db")
|
||||
SECRET_FILE = os.environ.get("SECRET_FILE", "/app/data/.auth_secret")
|
||||
USERS_ROOT = os.environ.get("USERS_ROOT", "/app/data/users")
|
||||
MAX_UPLOAD = int(os.environ.get("MAX_UPLOAD_MB", "50")) * 1024 * 1024
|
||||
|
||||
|
||||
def _auth_secret():
|
||||
if not os.path.exists(SECRET_FILE):
|
||||
os.makedirs(os.path.dirname(SECRET_FILE), exist_ok=True)
|
||||
with open(SECRET_FILE, "w") as f:
|
||||
f.write(secrets.token_hex(32))
|
||||
with open(SECRET_FILE) as f:
|
||||
return f.read().strip()
|
||||
|
||||
|
||||
def _db():
|
||||
conn = sqlite3.connect(USER_DB)
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, salt TEXT, pw_hash TEXT, created REAL)")
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS files (id TEXT PRIMARY KEY, username TEXT, name TEXT, size INTEGER, mime TEXT, created REAL)")
|
||||
conn.commit()
|
||||
return conn
|
||||
|
||||
|
||||
def _hash_pw(pw, salt):
|
||||
return hashlib.pbkdf2_hmac("sha256", pw.encode(), salt.encode(), 120000).hex()
|
||||
|
||||
|
||||
def _make_token(username):
|
||||
exp = str(int(time.time()) + 7 * 86400)
|
||||
payload = username + "." + exp
|
||||
sig = hmac.new(_auth_secret().encode(), payload.encode(), hashlib.sha256).hexdigest()[:32]
|
||||
return payload + "." + sig
|
||||
|
||||
|
||||
def _parse_token(tok):
|
||||
try:
|
||||
username, exp, sig = tok.rsplit(".", 2)
|
||||
payload = username + "." + exp
|
||||
expect = hmac.new(_auth_secret().encode(), payload.encode(), hashlib.sha256).hexdigest()[:32]
|
||||
if hmac.compare_digest(sig, expect) and int(exp) > time.time():
|
||||
return username
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _user_dir(username):
|
||||
d = os.path.join(USERS_ROOT, username)
|
||||
os.makedirs(os.path.join(d, "files"), exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def _auth_user(handler):
|
||||
tok = handler.headers.get("Authorization", "")
|
||||
if tok.lower().startswith("bearer "):
|
||||
tok = tok[7:]
|
||||
return _parse_token(tok) if tok else None
|
||||
|
||||
|
||||
USER_NAME_RE = re.compile(r"^[A-Za-z0-9_\u4e00-\u9fa5-]{3,32}$")
|
||||
|
||||
|
||||
def user_api(method, sub, payload, handler):
|
||||
"""returns (status, body_dict)"""
|
||||
if method == "POST" and sub == "/register":
|
||||
username = str(payload.get("username") or "").strip()
|
||||
password = str(payload.get("password") or "")
|
||||
if not USER_NAME_RE.match(username):
|
||||
return 400, {"code": 400, "message": "用户名需 3-32 位字母/数字/下划线/中文"}
|
||||
if len(password) < 6:
|
||||
return 400, {"code": 400, "message": "密码至少 6 位"}
|
||||
conn = _db()
|
||||
try:
|
||||
salt = secrets.token_hex(16)
|
||||
conn.execute("INSERT INTO users VALUES (?,?,?,?)", (username, salt, _hash_pw(password, salt), time.time()))
|
||||
conn.commit()
|
||||
except sqlite3.IntegrityError:
|
||||
return 409, {"code": 409, "message": "用户名已被注册"}
|
||||
finally:
|
||||
conn.close()
|
||||
_user_dir(username)
|
||||
return 200, {"code": 200, "message": "ok", "data": {"token": _make_token(username), "username": username}}
|
||||
|
||||
if method == "POST" and sub == "/login":
|
||||
username = str(payload.get("username") or "").strip()
|
||||
password = str(payload.get("password") or "")
|
||||
conn = _db()
|
||||
row = conn.execute("SELECT salt, pw_hash FROM users WHERE username=?", (username,)).fetchone()
|
||||
conn.close()
|
||||
if not row or _hash_pw(password, row[0]) != row[1]:
|
||||
return 401, {"code": 401, "message": "用户名或密码错误"}
|
||||
_user_dir(username)
|
||||
return 200, {"code": 200, "message": "ok", "data": {"token": _make_token(username), "username": username}}
|
||||
|
||||
# ---- below requires auth ----
|
||||
username = _auth_user(handler)
|
||||
if not username:
|
||||
return 401, {"code": 401, "message": "请先登录"}
|
||||
|
||||
if method == "GET" and sub == "/me":
|
||||
return 200, {"code": 200, "message": "ok", "data": {"username": username}}
|
||||
|
||||
if method == "GET" and sub == "/data":
|
||||
path = os.path.join(_user_dir(username), "data.json")
|
||||
if not os.path.exists(path):
|
||||
return 200, {"code": 200, "message": "ok", "data": {"data": {}, "updated": 0}}
|
||||
try:
|
||||
with open(path) as f:
|
||||
saved = json.load(f)
|
||||
except Exception:
|
||||
saved = {}
|
||||
return 200, {"code": 200, "message": "ok", "data": {"data": saved.get("data", {}), "updated": saved.get("updated", 0)}}
|
||||
|
||||
if method == "POST" and sub == "/data":
|
||||
data = payload.get("data")
|
||||
if not isinstance(data, dict):
|
||||
return 400, {"code": 400, "message": "data 需为对象"}
|
||||
path = os.path.join(_user_dir(username), "data.json")
|
||||
tmp = path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump({"data": data, "updated": time.time()}, f, ensure_ascii=False)
|
||||
os.replace(tmp, path)
|
||||
return 200, {"code": 200, "message": "ok"}
|
||||
|
||||
if method == "POST" and sub == "/files":
|
||||
files = payload.get("_files") or {}
|
||||
fields = payload.get("_fields") or {}
|
||||
fobj = files.get("file")
|
||||
if not fobj:
|
||||
return 400, {"code": 400, "message": "缺少 file 字段"}
|
||||
fname, fdata, fmime = fobj
|
||||
if len(fdata) > MAX_UPLOAD:
|
||||
return 413, {"code": 413, "message": "文件超过 " + str(MAX_UPLOAD // 1024 // 1024) + "MB 限制"}
|
||||
if not fdata:
|
||||
return 400, {"code": 400, "message": "文件为空"}
|
||||
file_id = uuid.uuid4().hex[:16]
|
||||
safe_name = os.path.basename(str(fname))[:120] or "file"
|
||||
kind = re.sub(r"[^A-Za-z0-9_-]", "", str(fields.get("kind") or ""))[:32]
|
||||
fdir = os.path.join(_user_dir(username), "files")
|
||||
os.makedirs(fdir, exist_ok=True)
|
||||
if kind:
|
||||
fdir = os.path.join(fdir, kind)
|
||||
os.makedirs(fdir, exist_ok=True)
|
||||
with open(os.path.join(fdir, file_id), "wb") as f:
|
||||
f.write(fdata)
|
||||
conn = _db()
|
||||
conn.execute("INSERT INTO files VALUES (?,?,?,?,?,?)", (file_id, username, safe_name, len(fdata), fmime, time.time()))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return 200, {"code": 200, "message": "ok", "data": {"id": file_id, "name": safe_name, "size": len(fdata), "kind": kind}}
|
||||
|
||||
if method == "GET" and sub == "/files":
|
||||
conn = _db()
|
||||
rows = conn.execute("SELECT id, name, size, mime, created FROM files WHERE username=? ORDER BY created DESC LIMIT 200", (username,)).fetchall()
|
||||
conn.close()
|
||||
files = [{"id": r[0], "name": r[1], "size": r[2], "mime": r[3], "created": int(r[4])} for r in rows]
|
||||
return 200, {"code": 200, "message": "ok", "data": {"files": files}}
|
||||
|
||||
if sub.startswith("/file/"):
|
||||
file_id = sub[len("/file/"):]
|
||||
if not re.match(r"^[A-Za-z0-9_-]{8,64}$", file_id):
|
||||
return 400, {"code": 400, "message": "文件ID无效"}
|
||||
conn = _db()
|
||||
row = conn.execute("SELECT id, username, name, size, mime, created FROM files WHERE id=?", (file_id,)).fetchone()
|
||||
conn.close()
|
||||
if not row or row[1] != username:
|
||||
return 404, {"code": 404, "message": "文件不存在"}
|
||||
fpath = None
|
||||
base = os.path.join(_user_dir(username), "files")
|
||||
if os.path.exists(os.path.join(base, file_id)):
|
||||
fpath = os.path.join(base, file_id)
|
||||
else:
|
||||
for d in os.listdir(base):
|
||||
p = os.path.join(base, d, file_id)
|
||||
if os.path.exists(p):
|
||||
fpath = p
|
||||
break
|
||||
if not fpath:
|
||||
return 404, {"code": 404, "message": "文件不存在"}
|
||||
if method == "GET":
|
||||
if not os.path.exists(fpath):
|
||||
return 404, {"code": 404, "message": "文件不存在"}
|
||||
with open(fpath, "rb") as f:
|
||||
data = f.read()
|
||||
handler.send_response(200)
|
||||
handler.send_header("Content-Type", row[4] or "application/octet-stream")
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
handler.send_header("Content-Disposition", "attachment; filename*=UTF-8''" + parse.quote(row[2]))
|
||||
handler.end_headers()
|
||||
handler.wfile.write(data)
|
||||
return None, None
|
||||
if method == "DELETE":
|
||||
if fpath and os.path.exists(fpath):
|
||||
os.remove(fpath)
|
||||
conn = _db()
|
||||
conn.execute("DELETE FROM files WHERE id=?", (file_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return 200, {"code": 200, "message": "ok"}
|
||||
|
||||
return 404, {"code": 404, "message": "unknown user api"}
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
@@ -585,8 +795,45 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.wfile.write(body)
|
||||
|
||||
# ---------- GET ----------
|
||||
def _handle_user(self, method):
|
||||
parsed = parse.urlparse(self.path)
|
||||
sub = parsed.path[len("/user"):]
|
||||
payload = {}
|
||||
if method == "POST":
|
||||
try:
|
||||
ctype = self.headers.get("Content-Type", "")
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
if length > MAX_UPLOAD + 1024 * 1024:
|
||||
self._reply(413, json.dumps({"code": 413, "message": "文件过大"}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
raw = self.rfile.read(length) if length else b"{}"
|
||||
if ctype.startswith("multipart/form-data"):
|
||||
env = {"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype, "CONTENT_LENGTH": str(length)}
|
||||
fs = cgi.FieldStorage(fp=io.BytesIO(raw), environ=env, keep_blank_values=True)
|
||||
files = {}
|
||||
fields = {}
|
||||
for k in fs.keys():
|
||||
item = fs[k]
|
||||
if getattr(item, "filename", None):
|
||||
files[k] = (item.filename, item.file.read(), item.type or "application/octet-stream")
|
||||
else:
|
||||
fields[k] = item.value
|
||||
payload = {"_fields": fields, "_files": files}
|
||||
else:
|
||||
payload = json.loads(raw.decode("utf-8") or "{}")
|
||||
except Exception:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "无效请求体"}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
status, body = user_api(method, sub, payload, self)
|
||||
if status is None:
|
||||
return # response already sent (file download)
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def do_GET(self):
|
||||
parsed = parse.urlparse(self.path)
|
||||
if parsed.path.startswith("/user"):
|
||||
self._handle_user("GET")
|
||||
return
|
||||
if parsed.path == "/auth-status":
|
||||
qs = parse.parse_qs(parsed.query)
|
||||
machine = (qs.get("machine_id") or [""])[0]
|
||||
@@ -637,6 +884,9 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
def do_POST(self):
|
||||
parsed = parse.urlparse(self.path)
|
||||
if parsed.path.startswith("/user"):
|
||||
self._handle_user("POST")
|
||||
return
|
||||
if parsed.path == "/convert":
|
||||
self._handle_convert()
|
||||
return
|
||||
@@ -766,6 +1016,9 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
def do_DELETE(self):
|
||||
parsed = parse.urlparse(self.path)
|
||||
if parsed.path.startswith("/user"):
|
||||
self._handle_user("DELETE")
|
||||
return
|
||||
if parsed.path.startswith("/sites/"):
|
||||
sub = parsed.path[len("/sites"):]
|
||||
status, body = sites_api("DELETE", sub, {})
|
||||
|
||||
@@ -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>
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 文件';
|
||||
|
||||
Reference in new issue
Block a user