Files
juwan-frontend/lib/api/auth.ts
T
2026-02-28 07:26:05 +08:00

94 lines
2.6 KiB
TypeScript

import type { User } from "@/lib/types"
import { mockUsers } from "@/lib/mock"
export type RegisterInput = {
username: string
email: string
password: string
vcode?: string
}
export type LoginInput = {
username: string
password: string
}
function throwApiError(code: number, msg: string): never {
throw { code, msg }
}
function nextUserId(): string {
const maxId = Math.max(0, ...mockUsers.map((user) => Number.parseInt(user.id, 10) || 0))
return String(maxId + 1)
}
export async function register(input: RegisterInput): Promise<User> {
const username = input.username.trim()
const email = input.email.trim()
const password = input.password
if (!username) throwApiError(400, "请输入用户名")
if (!email) throwApiError(400, "请输入邮箱")
if (!password || password.length < 6) throwApiError(400, "密码至少6位")
const usernameTaken = mockUsers.some(
(user) => user.username.toLowerCase() === username.toLowerCase(),
)
if (usernameTaken) throwApiError(400, "用户名已存在")
const emailTaken = mockUsers.some((user) => user.email?.toLowerCase() === email.toLowerCase())
if (emailTaken) throwApiError(400, "邮箱已被注册")
await new Promise((r) => setTimeout(r, 500))
const user: User = {
id: nextUserId(),
username,
email,
nickname: username,
avatar: "/avatars/u1.jpg",
role: "consumer",
createdAt: new Date().toISOString(),
}
mockUsers.push(user)
return user
}
export async function login(input: LoginInput): Promise<User> {
const username = input.username.trim()
const password = input.password
if (!username) throwApiError(400, "请输入用户名")
if (!password || password.length < 6) throwApiError(400, "密码至少6位")
await new Promise((r) => setTimeout(r, 500))
const user =
mockUsers.find((u) => u.username.toLowerCase() === username.toLowerCase()) ??
mockUsers.find((u) => u.email?.toLowerCase() === username.toLowerCase())
if (!user) throwApiError(404, "用户不存在")
return user
}
export async function resetPassword(input: {
email: string
vcode: string
newPassword: string
}): Promise<void> {
const email = input.email.trim()
const vcode = input.vcode.trim()
const newPassword = input.newPassword
if (!email) throwApiError(400, "请输入邮箱")
if (!vcode) throwApiError(400, "请输入验证码")
if (!newPassword || newPassword.length < 8) throwApiError(400, "密码至少8位")
await new Promise((r) => setTimeout(r, 500))
const user = mockUsers.find((u) => u.email?.toLowerCase() === email.toLowerCase())
if (!user) throwApiError(404, "用户不存在")
}