49 lines
2.0 KiB
TypeScript
49 lines
2.0 KiB
TypeScript
import { toNextJsHandler } from "better-auth/next-js";
|
|
import { and, eq } from "drizzle-orm";
|
|
|
|
import { getAuth, isSudlohOidcEnabled } from "@/lib/auth/server";
|
|
import { getDb } from "@/db";
|
|
import { accounts } from "@/db/schema";
|
|
import { errorResponse, HttpError, readJson, requireSameOrigin } from "@/lib/security/http";
|
|
|
|
const handlers = toNextJsHandler((request) => getAuth().handler(request));
|
|
|
|
export async function GET(request: Request) {
|
|
return handlers.GET(request);
|
|
}
|
|
|
|
async function mutate(request: Request) {
|
|
try {
|
|
requireSameOrigin(request);
|
|
const input = await readJson(request.clone());
|
|
const path = new URL(request.url).pathname;
|
|
if (["/update-user", "/change-email"].some((endpoint) => path.endsWith(endpoint))) {
|
|
if (isSudlohOidcEnabled() && process.env.SUDLOH_OIDC_ONLY === "true")
|
|
throw new HttpError(403, "manage-profile-at-sudloh");
|
|
const session = await getAuth().api.getSession({ headers: request.headers });
|
|
if (session) {
|
|
const [linked] = await getDb().select({ id: accounts.id }).from(accounts).where(and(
|
|
eq(accounts.userId, session.user.id), eq(accounts.providerId, "sudloh"),
|
|
)).limit(1);
|
|
if (linked) throw new HttpError(403, "manage-profile-at-sudloh");
|
|
}
|
|
}
|
|
if (["/admin/create-user", "/admin/set-user-password"].some((endpoint) => path.endsWith(endpoint))) {
|
|
const password = input && typeof input === "object" && "password" in input ? input.password : undefined;
|
|
const newPassword = input && typeof input === "object" && "newPassword" in input ? input.newPassword : undefined;
|
|
const value = password ?? newPassword;
|
|
if (typeof value !== "string" || value.length < 6 || value.length > 128) {
|
|
throw new HttpError(400, "invalid-password-length");
|
|
}
|
|
}
|
|
return await getAuth().handler(request);
|
|
} catch (cause) {
|
|
return errorResponse(cause);
|
|
}
|
|
}
|
|
|
|
export const POST = mutate;
|
|
export const PATCH = mutate;
|
|
export const PUT = mutate;
|
|
export const DELETE = mutate;
|