Files
no-whatever/src/lib/userId.ts
T
kurihada 04c7b547aa feat: 用户名密码登录注册系统
- 新增 /api/auth/register 和 /api/auth/login 接口,使用 bcryptjs 哈希密码
- User 模型改为 username + passwordHash,id 自动生成 cuid
- 新增 AuthModal 组件(登录/注册双标签页),替换旧的 ProfileSetupModal
- 重写 /profile 页面:支持修改用户名、密码、头像、绑定邮箱、退出登录
- /api/user PUT 支持密码修改(需验证当前密码)和用户名唯一性校验
- 游客模式保留,右上角显示"登录"按钮;登录后显示头像和用户名
- 全局 nickname -> username 重命名(types、SwipeDeck、RoomManageModal、buildRoomStatus)
- 新增 logout() 清除登录态并重新生成游客 UUID
2026-02-25 00:21:03 +08:00

64 lines
1.7 KiB
TypeScript

import type { UserProfile, UserPreferences } from "@/types";
const STORAGE_KEY = "nowhatever_user_id";
const PROFILE_KEY = "nowhatever_profile";
export function getUserId(): string {
if (typeof window === "undefined") return "";
let id = localStorage.getItem(STORAGE_KEY);
if (!id) {
id = crypto.randomUUID();
localStorage.setItem(STORAGE_KEY, id);
}
return id;
}
export function getCachedProfile(): UserProfile | null {
if (typeof window === "undefined") return null;
try {
const raw = localStorage.getItem(PROFILE_KEY);
return raw ? JSON.parse(raw) : null;
} catch {
return null;
}
}
export function setCachedProfile(profile: UserProfile | null): void {
if (typeof window === "undefined") return;
if (profile) {
localStorage.setItem(PROFILE_KEY, JSON.stringify(profile));
} else {
localStorage.removeItem(PROFILE_KEY);
}
}
export function isRegistered(): boolean {
return getCachedProfile() !== null;
}
export function getCachedPreferences(): UserPreferences {
if (typeof window === "undefined") return {};
try {
const profile = getCachedProfile();
if (!profile) return {};
const raw = localStorage.getItem("nowhatever_preferences");
return raw ? JSON.parse(raw) : {};
} catch {
return {};
}
}
export function setCachedPreferences(prefs: UserPreferences): void {
if (typeof window === "undefined") return;
localStorage.setItem("nowhatever_preferences", JSON.stringify(prefs));
}
export function logout(): void {
if (typeof window === "undefined") return;
localStorage.removeItem(PROFILE_KEY);
localStorage.removeItem("nowhatever_preferences");
const newId = crypto.randomUUID();
localStorage.setItem(STORAGE_KEY, newId);
}