This commit is contained in:
root
2026-06-07 12:48:17 +08:00
parent 9ee203c221
commit 283d65d1d1
46 changed files with 1205 additions and 2579 deletions

View File

@@ -1,8 +1,7 @@
/**
* PocketBase 认证服务 - 邮箱登录、注册
* 认证服务 - 前端只调用 FastAPI不直连 PocketBase。
*/
import { getPocketBaseConfig } from "@/config/services.config";
import { PB_STORAGE_KEYS } from "./constants";
import { apiUrl } from "@/app/lib/api-client";
@@ -15,48 +14,37 @@ export interface AuthUser {
export interface AuthResult {
token: string;
record: AuthUser;
is_new?: boolean;
provider?: string;
}
function getPBUrl(): string {
return getPocketBaseConfig().url;
}
export async function pbLogin(
identity: string,
password: string
): Promise<AuthResult> {
const res = await fetch(apiUrl("/api/auth/login"), {
async function authRequest(path: string, body: Record<string, unknown>): Promise<AuthResult> {
const res = await fetch(apiUrl(path), {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ email: identity, password }),
body: JSON.stringify(body),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err?.detail || err?.message || "登录失败");
throw new Error(err?.detail || err?.message || "认证失败");
}
const data = await res.json();
if (!data?.token) throw new Error("登录响应异常");
return { token: data.token, record: data.record };
return {
token: data.token,
record: data.record,
is_new: data.is_new,
provider: data.provider,
};
}
export async function pbRegister(
email: string,
password: string,
passwordConfirm: string
): Promise<AuthResult> {
const res = await fetch(apiUrl("/api/auth/register"), {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ email, password, passwordConfirm }),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err?.detail || err?.message || "注册失败");
}
const data = await res.json();
return { token: data.token, record: data.record };
export async function emailLogin(email: string): Promise<AuthResult> {
return authRequest("/api/auth/email", { email });
}
export async function googleLogin(idToken: string): Promise<AuthResult> {
return authRequest("/api/auth/google", { id_token: idToken });
}
export function pbSaveAuth(token: string, record: AuthUser): void {