119 lines
3.4 KiB
TypeScript
119 lines
3.4 KiB
TypeScript
/**
|
|
* PocketBase 认证服务 - 邮箱登录、注册
|
|
*/
|
|
|
|
import { getPocketBaseConfig } from "@/config/services.config";
|
|
import { PB_STORAGE_KEYS } from "./constants";
|
|
|
|
export interface AuthUser {
|
|
id: string;
|
|
email: string;
|
|
[key: string]: unknown;
|
|
}
|
|
|
|
export interface AuthResult {
|
|
token: string;
|
|
record: AuthUser;
|
|
}
|
|
|
|
function getPBUrl(): string {
|
|
return getPocketBaseConfig().url;
|
|
}
|
|
|
|
export async function pbLogin(
|
|
identity: string,
|
|
password: string
|
|
): Promise<AuthResult> {
|
|
const url = getPBUrl();
|
|
const res = await fetch(`${url}/api/collections/users/auth-with-password`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ identity, password }),
|
|
});
|
|
if (!res.ok) {
|
|
const err = await res.json();
|
|
throw new Error(err?.message || "登录失败");
|
|
}
|
|
const data = await res.json();
|
|
if (!data?.token) throw new Error("登录响应异常");
|
|
return { token: data.token, record: data.record };
|
|
}
|
|
|
|
/** 从 PocketBase 错误响应中提取可读错误信息 */
|
|
function parsePBError(err: { message?: string; data?: Record<string, { message?: string; code?: string }> }): string {
|
|
const data = err?.data;
|
|
if (data && typeof data === "object" && Object.keys(data).length > 0) {
|
|
const first = Object.values(data)[0];
|
|
if (first?.message) {
|
|
const code = first.code;
|
|
if (code === "validation_not_unique") {
|
|
return "该邮箱已被注册,请直接登录";
|
|
}
|
|
if (code === "validation_required") {
|
|
return "请填写必填项";
|
|
}
|
|
if (code?.startsWith("validation_")) {
|
|
return first.message;
|
|
}
|
|
return first.message;
|
|
}
|
|
}
|
|
if (err?.message === "Failed to create record.") {
|
|
return "注册失败,该邮箱可能已被使用,请尝试直接登录";
|
|
}
|
|
return err?.message || "注册失败";
|
|
}
|
|
|
|
export async function pbRegister(
|
|
email: string,
|
|
password: string,
|
|
passwordConfirm: string
|
|
): Promise<AuthResult> {
|
|
const url = getPBUrl();
|
|
const res = await fetch(`${url}/api/collections/users/records`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ email, password, passwordConfirm }),
|
|
});
|
|
if (!res.ok) {
|
|
const err = await res.json().catch(() => ({}));
|
|
throw new Error(parsePBError(err));
|
|
}
|
|
return pbLogin(email, password);
|
|
}
|
|
|
|
export function pbSaveAuth(token: string, record: AuthUser): void {
|
|
if (typeof window === "undefined") return;
|
|
localStorage.setItem(PB_STORAGE_KEYS.token, token);
|
|
localStorage.setItem(PB_STORAGE_KEYS.user, JSON.stringify(record));
|
|
}
|
|
|
|
/** 登出 - 清除本地存储和根域 Cookie */
|
|
export async function pbLogout(): Promise<void> {
|
|
if (typeof window === "undefined") return;
|
|
localStorage.removeItem(PB_STORAGE_KEYS.token);
|
|
localStorage.removeItem(PB_STORAGE_KEYS.user);
|
|
try {
|
|
await fetch("/api/auth/logout", { method: "POST", credentials: "include" });
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
}
|
|
|
|
export function getStoredUserEmail(): string | null {
|
|
if (typeof window === "undefined") return null;
|
|
try {
|
|
const raw = localStorage.getItem(PB_STORAGE_KEYS.user);
|
|
if (!raw) return null;
|
|
const user = JSON.parse(raw);
|
|
return user?.email ?? null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function getStoredToken(): string | null {
|
|
if (typeof window === "undefined") return null;
|
|
return localStorage.getItem(PB_STORAGE_KEYS.token);
|
|
}
|