feat(auth) : improve Google account handling

This commit is contained in:
2026-10-12 00:51:29 +07:00 Unverified
parent e2af59292c
commit fdbabecf56
7 changed files with 80 additions and 11 deletions
+25 -1
View File
@@ -1,5 +1,8 @@
import { toNextJsHandler } from "better-auth/next-js";
import { getAuth } from "@/lib/auth/server";
import { eq, sql } from "drizzle-orm";
import { getDb } from "@/db";
import { accounts } from "@/db/schema";
import { getAuth, getCustomerSession } from "@/lib/auth/server";
import { errorResponse, HttpError, readJson, requireSameOrigin } from "@/lib/security/http";
const handlers = toNextJsHandler((request) => getAuth().handler(request));
@@ -21,6 +24,27 @@ async function mutate(request: Request) {
throw new HttpError(400, "invalid-password-length");
}
}
if (path === "/api/auth/unlink-account") {
const accountId = input && typeof input === "object" && "accountId" in input
&& typeof input.accountId === "string" ? input.accountId : null;
const session = accountId ? await getCustomerSession() : null;
if (accountId && session) {
const linkedAccounts = await getDb().select({
id: accounts.id,
providerId: accounts.providerId,
hasPassword: sql<boolean>`${accounts.password} is not null`,
}).from(accounts).where(eq(accounts.userId, session.user.id));
const accountExists = linkedAccounts.some((account) => account.id === accountId);
const hasAlternativeSignIn = linkedAccounts.some((account) => account.id !== accountId
&& (account.providerId !== "credential" || account.hasPassword));
if (accountExists && !hasAlternativeSignIn) {
return Response.json({
code: "LAST_AUTH_METHOD",
message: "กรุณาตั้งรหัสผ่านหรือเชื่อมต่อวิธีเข้าสู่ระบบอื่นก่อนยกเลิกการเชื่อมต่อ Google",
}, { status: 409, headers: { "Cache-Control": "no-store" } });
}
}
}
return await getAuth().handler(request);
} catch (cause) {
return errorResponse(cause);