feat : use guide login only [no ci]

This commit is contained in:
2026-10-06 18:41:28 +07:00 Unverified
parent 1339dd43e6
commit 3c8f60433a
28 changed files with 50 additions and 783 deletions
-66
View File
@@ -1,66 +0,0 @@
import { describe, expect, it } from "vitest";
import { betterAuth } from "better-auth";
import { memoryAdapter } from "better-auth/adapters/memory";
import { genericOAuth } from "better-auth/plugins";
const origin = "https://guide.test";
function createReplica(database: Record<string, Record<string, unknown>[]>) {
return betterAuth({
baseURL: origin,
secret: "a-shared-test-secret-with-enough-entropy-123",
database: memoryAdapter(database),
rateLimit: { enabled: false },
plugins: [genericOAuth({ config: [{
providerId: "sudloh",
clientId: "test-client",
clientSecret: "test-secret",
authorizationUrl: "https://account.test/authorize",
tokenUrl: "https://account.test/token",
getToken: async () => ({ accessToken: "test-access-token", accessTokenExpiresAt: new Date(Date.now() + 3600_000) }),
getUserInfo: async () => ({ id: "test-subject", email: "[email protected]",
emailVerified: true, name: "Test User" }),
}] })],
});
}
describe("Sudloh OAuth callback", () => {
it("completes across replicas, creates the Guide session, and consumes state once", async () => {
const database = { user: [], session: [], account: [], verification: [] };
const first = createReplica(database);
const second = createReplica(database);
const start = await first.handler(new Request(`${origin}/api/auth/sign-in/social`, {
method: "POST", headers: { Origin: origin, "Content-Type": "application/json" },
body: JSON.stringify({ provider: "sudloh", callbackURL: "/profile" }),
}));
expect(start.status).toBe(200);
const authorization = new URL((await start.json()).url);
expect(authorization.searchParams.get("code_challenge_method")).toBe("S256");
expect(authorization.searchParams.get("code_challenge")).toBeTruthy();
const stateCookie = start.headers.get("set-cookie")?.split(";", 1)[0];
expect(stateCookie).toBeTruthy();
const callbackURL = new URL(`${origin}/api/auth/callback/sudloh`);
callbackURL.searchParams.set("code", "test-code");
callbackURL.searchParams.set("state", authorization.searchParams.get("state")!);
const callback = await second.handler(new Request(callbackURL, {
headers: { Cookie: stateCookie! },
}));
expect(callback.status).toBe(302);
expect(callback.headers.get("location")).toBe("/profile");
const sessionCookie = callback.headers.getSetCookie()
.find((cookie) => cookie.includes("session_token="))?.split(";", 1)[0];
const session = await second.api.getSession({ headers: new Headers({ Cookie: sessionCookie! }) });
expect(session?.user.email).toBe("[email protected]");
const replay = await first.handler(new Request(callbackURL, {
headers: { Cookie: stateCookie! },
}));
expect(replay.headers.get("location")).toContain("state_mismatch");
});
it("rejects a callback without state before exchanging a code", async () => {
const auth = createReplica({ user: [], session: [], account: [], verification: [] });
const response = await auth.handler(new Request(`${origin}/api/auth/callback/sudloh?code=test-code`));
expect(response.status).toBe(302);
expect(response.headers.get("location")).toContain("state_not_found");
});
});
+7 -63
View File
@@ -8,10 +8,9 @@ vi.mock("better-auth", () => ({ betterAuth: mocks.auth }));
vi.mock("better-auth/adapters/drizzle", () => ({ drizzleAdapter: () => ({}) }));
vi.mock("better-auth/next-js", () => ({ nextCookies: () => ({}) }));
vi.mock("better-auth/plugins", () => ({ admin: (options: unknown) => options, captcha: () => ({}),
genericOAuth: (options: unknown) => ({ id: "generic-oauth", options }),
emailOTP: (options: unknown) => ({ id: "email-otp", options }) }));
const envNames = ["NODE_ENV", "DATABASE_URL", "BETTER_AUTH_URL", "BETTER_AUTH_SECRET", "BUZZ_DEMO_MODE", "RESEND_API_KEY", "SUDLOH_OIDC_CLIENT_ID", "SUDLOH_OIDC_CLIENT_SECRET", "SUDLOH_OIDC_REDIRECT_URI", "SUDLOH_OIDC_ISSUER", "SUDLOH_OIDC_ONLY", "SUDLOH_OIDC_PAUSED", "TRUSTED_CLIENT_IP_HEADER"] as const;
const envNames = ["NODE_ENV", "DATABASE_URL", "BETTER_AUTH_URL", "BETTER_AUTH_SECRET", "BUZZ_DEMO_MODE", "RESEND_API_KEY", "TRUSTED_CLIENT_IP_HEADER"] as const;
const testEnv = process.env as Record<string, string | undefined>;
const originalEnv = envNames.map((name) => testEnv[name]);
@@ -23,12 +22,6 @@ beforeEach(() => {
testEnv.BETTER_AUTH_SECRET = "a-test-secret-with-more-than-32-characters";
mocks.auth.mockReturnValue({ api: { getSession: mocks.session } });
mocks.session.mockResolvedValue(null);
delete testEnv.SUDLOH_OIDC_CLIENT_ID;
delete testEnv.SUDLOH_OIDC_CLIENT_SECRET;
delete testEnv.SUDLOH_OIDC_REDIRECT_URI;
delete testEnv.SUDLOH_OIDC_ISSUER;
delete testEnv.SUDLOH_OIDC_ONLY;
delete testEnv.SUDLOH_OIDC_PAUSED;
delete testEnv.TRUSTED_CLIENT_IP_HEADER;
});
afterEach(() => {
@@ -59,77 +52,28 @@ describe("actual administrator session boundary", () => {
it("defaults accounts to user and requires six-character new passwords", async () => {
(await import("./server")).getAuth();
const options = mocks.auth.mock.calls.at(-1)![0];
expect(options.emailAndPassword).toMatchObject({ disableSignUp: false, minPasswordLength: 6 });
expect(options.emailAndPassword).toMatchObject({ enabled: true, minPasswordLength: 6 });
expect(options.plugins).toContainEqual({ defaultRole: "user" });
expect(options.rateLimit.customStorage.consume).toBeTypeOf("function");
expect(options.databaseHooks).toBeUndefined();
});
it("adds verified Sudloh sign-in while retaining email sign-in", async () => {
testEnv.SUDLOH_OIDC_CLIENT_ID = "client";
testEnv.SUDLOH_OIDC_CLIENT_SECRET = "secret";
testEnv.SUDLOH_OIDC_REDIRECT_URI = "https://guide.example.test/api/auth/callback/sudloh";
const { getAuth, isSudlohOidcEnabled } = await import("./server");
expect(isSudlohOidcEnabled()).toBe(true);
getAuth();
const options = mocks.auth.mock.calls.at(-1)![0];
expect(options.emailAndPassword).toMatchObject({ enabled: true, disableSignUp: false });
expect(options.account.accountLinking.disableImplicitLinking).toBe(true);
expect(options.account.accountLinking.enabled).not.toBe(false);
expect(options.plugins.some((plugin: { id?: string }) => plugin.id === "email-otp")).toBe(true);
expect(options.plugins.find((plugin: { id?: string }) => plugin.id === "generic-oauth").options.config[0]).toMatchObject({
providerId: "sudloh", authentication: "basic", requireIdTokenVerification: true,
requireEmailVerification: true, disableProviderLogout: true,
overrideUserInfo: true,
scopes: ["openid", "profile", "email"],
redirectURI: "https://guide.example.test/api/auth/callback/sudloh",
});
});
it("uses local sign-in while Sudloh is paused, even with client credentials present", async () => {
testEnv.SUDLOH_OIDC_CLIENT_ID = "client";
testEnv.SUDLOH_OIDC_CLIENT_SECRET = "secret";
testEnv.SUDLOH_OIDC_REDIRECT_URI = "https://guide.example.test/api/auth/callback/sudloh";
testEnv.SUDLOH_OIDC_PAUSED = "true";
const { getAuth, isSudlohOidcEnabled } = await import("./server");
expect(isSudlohOidcEnabled()).toBe(false);
getAuth();
const options = mocks.auth.mock.calls.at(-1)![0];
expect(options.emailAndPassword).toMatchObject({ enabled: true, disableSignUp: false });
expect(options.plugins.some((plugin: { id?: string }) => plugin.id === "generic-oauth")).toBe(false);
});
it("disables local sign-in after the OIDC cutover flag is set", async () => {
testEnv.SUDLOH_OIDC_CLIENT_ID = "client";
testEnv.SUDLOH_OIDC_CLIENT_SECRET = "secret";
testEnv.SUDLOH_OIDC_REDIRECT_URI = "https://guide.example.test/api/auth/callback/sudloh";
testEnv.SUDLOH_OIDC_ONLY = "true";
it("always enables Guide credentials and registration", async () => {
testEnv.TRUSTED_CLIENT_IP_HEADER = "x-forwarded-for";
(await import("./server")).getAuth();
const options = mocks.auth.mock.calls.at(-1)![0];
expect(options.advanced.ipAddress.ipAddressHeaders).toEqual(["x-forwarded-for"]);
expect(options.emailAndPassword).toMatchObject({ enabled: false, disableSignUp: true });
expect(options.plugins.some((plugin: { id?: string }) => plugin.id === "email-otp")).toBe(false);
expect(options.emailAndPassword).toMatchObject({ enabled: true });
expect(options.plugins.some((plugin: { id?: string }) => plugin.id === "email-otp")).toBe(true);
expect(options.plugins.some((plugin: { id?: string }) => plugin.id === "generic-oauth")).toBe(false);
expect(options.databaseHooks).toBeUndefined();
});
it("keeps the local Guide session after the Sudloh access token expires", async () => {
testEnv.SUDLOH_OIDC_CLIENT_ID = "client";
testEnv.SUDLOH_OIDC_CLIENT_SECRET = "secret";
testEnv.SUDLOH_OIDC_REDIRECT_URI = "https://guide.example.test/api/auth/callback/sudloh";
testEnv.SUDLOH_OIDC_ONLY = "true";
it("keeps the local Guide session", async () => {
mocks.session.mockResolvedValue({ user: { id: "user-1", email: "[email protected]",
emailVerified: true, role: "admin" }, session: { id: "guide-session" } });
const { getAdminSession, getCustomerSession } = await import("./server");
expect(await getCustomerSession()).toMatchObject({ user: { id: "user-1" } });
expect(await getAdminSession()).toMatchObject({ user: { id: "user-1" } });
});
it("rejects incomplete or mismatched Sudloh client configuration", async () => {
const { getAuth, isSudlohOidcEnabled } = await import("./server");
testEnv.SUDLOH_OIDC_REDIRECT_URI = "https://guide.example.test/api/auth/callback/sudloh";
expect(isSudlohOidcEnabled()).toBe(false);
testEnv.SUDLOH_OIDC_CLIENT_ID = "client";
expect(isSudlohOidcEnabled).toThrow("client ID, client secret, and exact redirect URI");
testEnv.SUDLOH_OIDC_CLIENT_SECRET = "secret";
testEnv.SUDLOH_OIDC_REDIRECT_URI = "https://wrong.example.test/api/auth/callback/sudloh";
expect(getAuth).toThrow("SUDLOH_OIDC_REDIRECT_URI must be");
});
it("requires verification and sends auth links from the configured sender", async () => {
testEnv.RESEND_API_KEY = "test-key";
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 200 }));
+4 -38
View File
@@ -3,7 +3,7 @@ import "server-only";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { nextCookies } from "better-auth/next-js";
import { admin, captcha, emailOTP, genericOAuth } from "better-auth/plugins";
import { admin, captcha, emailOTP } from "better-auth/plugins";
import { headers } from "next/headers";
import { cache } from "react";
@@ -32,26 +32,7 @@ function hasAuthConfiguration(): boolean {
);
}
export function isSudlohOidcEnabled(): boolean {
if (process.env.SUDLOH_OIDC_PAUSED === "true") return false;
const clientId = process.env.SUDLOH_OIDC_CLIENT_ID;
const clientSecret = process.env.SUDLOH_OIDC_CLIENT_SECRET;
if (!clientId && !clientSecret) return false;
if (!clientId || !clientSecret || !process.env.SUDLOH_OIDC_REDIRECT_URI) {
throw new Error("Sudloh OIDC requires a client ID, client secret, and exact redirect URI.");
}
return true;
}
function createAuth() {
const oidcEnabled = isSudlohOidcEnabled();
const oidcOnly = oidcEnabled && process.env.SUDLOH_OIDC_ONLY === "true";
if (oidcEnabled) {
const callback = `${required("BETTER_AUTH_URL").replace(/\/$/, "")}/api/auth/callback/sudloh`;
if (process.env.SUDLOH_OIDC_REDIRECT_URI !== callback) {
throw new Error(`SUDLOH_OIDC_REDIRECT_URI must be ${callback}`);
}
}
return betterAuth({
appName: "Buzz Guide",
database: drizzleAdapter(getDb(), {
@@ -71,8 +52,7 @@ function createAuth() {
.filter(Boolean),
secret: required("BETTER_AUTH_SECRET"),
emailAndPassword: {
enabled: !oidcOnly,
disableSignUp: oidcOnly,
enabled: true,
requireEmailVerification: true,
minPasswordLength: 6,
maxPasswordLength: 128,
@@ -89,7 +69,6 @@ function createAuth() {
},
},
},
account: { accountLinking: { disableImplicitLinking: true } },
emailVerification: {
sendOnSignUp: false,
autoSignInAfterVerification: true,
@@ -115,26 +94,13 @@ function createAuth() {
},
},
plugins: [
...(oidcEnabled ? [genericOAuth({ config: [{
providerId: "sudloh",
clientId: process.env.SUDLOH_OIDC_CLIENT_ID!,
clientSecret: process.env.SUDLOH_OIDC_CLIENT_SECRET!,
redirectURI: process.env.SUDLOH_OIDC_REDIRECT_URI!,
discoveryUrl: `${(process.env.SUDLOH_OIDC_ISSUER || "https://account.sudloh.com/api/auth").replace(/\/$/, "")}/.well-known/openid-configuration`,
scopes: ["openid", "profile", "email"],
authentication: "basic",
requireIdTokenVerification: true,
requireEmailVerification: true,
disableProviderLogout: true,
overrideUserInfo: true,
}] })] : []),
...(!oidcOnly ? [emailOTP({
emailOTP({
sendVerificationOnSignUp: true,
storeOTP: "hashed",
sendVerificationOTP: async ({ email, otp }) => {
await sendAuthEmail(email, "รหัสยืนยัน Buzz Guide", `รหัสยืนยันอีเมลของคุณคือ ${otp}\n\nรหัสนี้หมดอายุใน 5 นาที`);
},
})] : []),
}),
...(process.env.NODE_ENV === "development" ? [] : [
captcha({
provider: "cloudflare-turnstile",
-42
View File
@@ -1,42 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { claimAutomaticSudlohSignIn, markSudlohSignInAttempt, sudlohStartErrorMessage } from "./sudloh-redirect";
const values = new Map<string, string>();
beforeEach(() => {
values.clear();
vi.stubGlobal("sessionStorage", {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => { values.set(key, value); },
});
vi.spyOn(Date, "now").mockReturnValue(1_000_000);
});
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
describe("Sudloh redirect guard", () => {
it("starts once and stops automatic redirects when login is revisited", () => {
expect(claimAutomaticSudlohSignIn()).toBe(true);
expect(claimAutomaticSudlohSignIn()).toBe(false);
vi.spyOn(Date, "now").mockReturnValue(1_000_000 + 5 * 60_000);
expect(claimAutomaticSudlohSignIn()).toBe(true);
});
it("keeps logout from immediately starting another sign-in", () => {
markSudlohSignInAttempt();
expect(claimAutomaticSudlohSignIn()).toBe(false);
});
it("requires a manual start when browser storage is unavailable", () => {
vi.stubGlobal("sessionStorage", { getItem: () => { throw new Error("blocked"); } });
expect(claimAutomaticSudlohSignIn()).toBe(false);
});
it("explains a rate limit without leaking the provider response", () => {
expect(sudlohStartErrorMessage(429)).toContain("รอสักครู่");
expect(sudlohStartErrorMessage(503)).not.toContain("รอสักครู่");
});
});
-24
View File
@@ -1,24 +0,0 @@
const attemptKey = "sudloh-oidc-last-start";
const attemptWindowMs = 5 * 60 * 1000;
export function sudlohStartErrorMessage(status?: number): string {
return status === 429
? "ลองเข้าสู่ระบบบ่อยเกินไป กรุณารอสักครู่แล้วลองอีกครั้ง"
: "ไม่สามารถเริ่มเข้าสู่ระบบได้ กรุณาลองอีกครั้ง";
}
export function markSudlohSignInAttempt() {
try { sessionStorage.setItem(attemptKey, String(Date.now())); }
catch { /* A manual retry remains available when storage is blocked. */ }
}
export function claimAutomaticSudlohSignIn(): boolean {
try {
const lastAttempt = Number(sessionStorage.getItem(attemptKey));
if (lastAttempt > 0 && Date.now() - lastAttempt < attemptWindowMs) return false;
markSudlohSignInAttempt();
return true;
} catch {
return false;
}
}
-80
View File
@@ -1,80 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const rows: unknown[][] = [];
const updateUser = vi.fn(async () => undefined);
vi.mock("server-only", () => ({}));
vi.mock("@/db", () => ({ getDb: () => ({
select: () => ({ from: () => ({ where: () => ({ limit: async () => rows.shift() ?? [] }) }) }),
update: () => ({ set: () => ({ where: updateUser }) }),
}) }));
const { refreshLinkedSudlohProfile } = await import("./sudloh");
const account = { accountId: "sub-1", accessToken: "access-1",
accessTokenExpiresAt: new Date(Date.now() + 60 * 60_000) };
beforeEach(() => {
rows.length = 0;
vi.clearAllMocks();
process.env.SUDLOH_OIDC_ISSUER = "https://account.test/api/auth";
process.env.SUDLOH_OIDC_CLIENT_ID = "client";
process.env.SUDLOH_OIDC_CLIENT_SECRET = "secret";
});
function provider(active: boolean, profileSub = "sub-1") {
return vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
const url = String(input);
if (url.endsWith("openid-configuration")) return Response.json({
issuer: "https://account.test/api/auth",
introspection_endpoint: "https://account.test/api/auth/oauth2/introspect",
userinfo_endpoint: "https://account.test/api/auth/oauth2/userinfo",
});
if (url.endsWith("introspect")) return Response.json({ active, sub: "sub-1",
exp: Math.floor(Date.now() / 1000) + 3600 });
if (url.endsWith("userinfo")) return Response.json({ sub: profileSub, name: "New Name",
email: "[email protected]", email_verified: true, picture: "https://account.test/avatar.png" });
throw new Error(`unexpected URL: ${url}`);
});
}
describe("Sudloh profile refresh", () => {
it("requires a new Sudloh sign-in after the access token expires", async () => {
rows.push([{ ...account, accessTokenExpiresAt: new Date(Date.now() - 1000) }]);
await expect(refreshLinkedSudlohProfile("user-1"))
.rejects.toMatchObject({ status: 401, message: "sudloh-sign-in-required" });
});
it("requires a new Sudloh sign-in when the token is revoked", async () => {
const fetchMock = provider(false);
rows.push([account]);
await expect(refreshLinkedSudlohProfile("user-1"))
.rejects.toMatchObject({ status: 401, message: "sudloh-sign-in-required" });
fetchMock.mockRestore();
});
it("rejects UserInfo for another subject", async () => {
const fetchMock = provider(true, "someone-else");
rows.push([account]);
await expect(refreshLinkedSudlohProfile("user-1"))
.rejects.toMatchObject({ status: 503 });
expect(updateUser).not.toHaveBeenCalled();
fetchMock.mockRestore();
});
it("reports a verified Sudloh email that conflicts with another Guide account", async () => {
const fetchMock = provider(true);
rows.push([account], [{ name: "Old Name", email: "[email protected]", emailVerified: true, image: null }]);
updateUser.mockRejectedValueOnce({ cause: { code: "23505" } });
await expect(refreshLinkedSudlohProfile("user-1"))
.rejects.toMatchObject({ status: 409, message: "sudloh-email-conflict" });
fetchMock.mockRestore();
});
it("updates a linked profile while its token is active", async () => {
const fetchMock = provider(true);
rows.push([account], [{ name: "Old Name", email: "[email protected]", emailVerified: true, image: null }]);
await refreshLinkedSudlohProfile("user-1");
expect(updateUser).toHaveBeenCalledOnce();
fetchMock.mockRestore();
});
});
-110
View File
@@ -1,110 +0,0 @@
import "server-only";
import { and, eq } from "drizzle-orm";
import { getDb } from "@/db";
import { accounts, users } from "@/db/schema";
import { HttpError } from "@/lib/security/http";
const ACCOUNT_SETTINGS_URL = "https://account.sudloh.com/account";
export { ACCOUNT_SETTINGS_URL };
type Endpoints = { issuer: string; userinfo_endpoint: string; introspection_endpoint: string };
type BoundToken = { token: string; accountId: string };
let discovery: { endpoints: Endpoints; until: number } | undefined;
async function endpoints(): Promise<Endpoints> {
if (discovery && discovery.until > Date.now()) return discovery.endpoints;
const issuer = (process.env.SUDLOH_OIDC_ISSUER || "https://account.sudloh.com/api/auth").replace(/\/$/, "");
const response = await fetch(`${issuer}/.well-known/openid-configuration`, {
cache: "no-store", signal: AbortSignal.timeout(5000),
});
if (!response.ok) throw new HttpError(503, "sudloh-unavailable");
const data: unknown = await response.json();
if (!data || typeof data !== "object" || !("issuer" in data) || data.issuer !== issuer ||
!("userinfo_endpoint" in data) || typeof data.userinfo_endpoint !== "string" ||
!("introspection_endpoint" in data) || typeof data.introspection_endpoint !== "string") {
throw new HttpError(503, "sudloh-discovery-invalid");
}
const result = data as Endpoints;
for (const url of [result.userinfo_endpoint, result.introspection_endpoint]) {
if (new URL(url).origin !== new URL(issuer).origin) throw new HttpError(503, "sudloh-discovery-invalid");
}
discovery = { endpoints: result, until: Date.now() + 10 * 60_000 };
return result;
}
async function userInfo(account: BoundToken) {
const response = await fetch((await endpoints()).userinfo_endpoint, {
headers: { Authorization: `Bearer ${account.token}` },
cache: "no-store", signal: AbortSignal.timeout(5000),
});
if (!response.ok) throw new HttpError(503, "sudloh-unavailable");
const data: unknown = await response.json();
if (!data || typeof data !== "object" ||
!("sub" in data) || data.sub !== account.accountId ||
!("name" in data) || typeof data.name !== "string" ||
!("email" in data) || typeof data.email !== "string" ||
!("email_verified" in data) || data.email_verified !== true ||
!("picture" in data) || typeof data.picture !== "string") {
throw new HttpError(503, "sudloh-profile-invalid");
}
return data as { sub: string; name: string; email: string; email_verified: true; picture: string };
}
async function introspect(account: BoundToken): Promise<boolean> {
const clientId = process.env.SUDLOH_OIDC_CLIENT_ID;
const clientSecret = process.env.SUDLOH_OIDC_CLIENT_SECRET;
if (!clientId || !clientSecret) throw new HttpError(503, "sudloh-not-configured");
const response = await fetch((await endpoints()).introspection_endpoint, {
method: "POST",
headers: {
Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({ token: account.token, token_type_hint: "access_token" }),
cache: "no-store", signal: AbortSignal.timeout(5000),
});
if (!response.ok) throw new HttpError(503, "sudloh-unavailable");
const data: unknown = await response.json();
if (!data || typeof data !== "object" || !("active" in data) || typeof data.active !== "boolean") {
throw new HttpError(503, "sudloh-introspection-invalid");
}
if (!data.active) return false;
if (!("sub" in data) || data.sub !== account.accountId ||
!("exp" in data) || typeof data.exp !== "number" || data.exp <= Date.now() / 1000) return false;
return true;
}
async function updateProfile(userId: string, token: BoundToken): Promise<boolean> {
const profile = await userInfo(token);
const [current] = await getDb().select({ name: users.name, email: users.email,
emailVerified: users.emailVerified, image: users.image }).from(users).where(eq(users.id, userId)).limit(1);
if (!current) return false;
const email = profile.email.toLowerCase();
if (current.name !== profile.name || current.email !== email ||
!current.emailVerified || current.image !== profile.picture) {
try {
await getDb().update(users).set({ name: profile.name, email,
emailVerified: true, image: profile.picture }).where(eq(users.id, userId));
} catch (cause) {
const dbError = cause && typeof cause === "object" && "cause" in cause ? cause.cause : cause;
if (dbError && typeof dbError === "object" && "code" in dbError && dbError.code === "23505")
throw new HttpError(409, "sudloh-email-conflict");
throw cause;
}
}
return true;
}
export async function refreshLinkedSudlohProfile(userId: string): Promise<void> {
const [account] = await getDb().select().from(accounts).where(and(
eq(accounts.userId, userId), eq(accounts.providerId, "sudloh"),
)).limit(1);
if (!account?.accessToken || !account.accessTokenExpiresAt ||
account.accessTokenExpiresAt.getTime() <= Date.now()) throw new HttpError(401, "sudloh-sign-in-required");
const token: BoundToken = { token: account.accessToken, accountId: account.accountId };
if (!await introspect(token)) throw new HttpError(401, "sudloh-sign-in-required");
if (!await updateProfile(userId, token)) throw new HttpError(401, "unauthorized");
}