feat(admin-auth): add first-start onboarding flow and dev db reset command
This commit is contained in:
@@ -7,6 +7,7 @@
|
||||
"dev": "bun --env-file=../../.env next dev --port 3001",
|
||||
"build": "bun --env-file=../../.env next build",
|
||||
"start": "bun --env-file=../../.env next start --port 3001",
|
||||
"auth:seed:support": "bun --env-file=../../.env ./scripts/seed-support-user.ts",
|
||||
"lint": "biome check src",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
|
||||
11
apps/admin/scripts/seed-support-user.ts
Normal file
11
apps/admin/scripts/seed-support-user.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { ensureSupportUserBootstrap } from "../src/lib/auth/server"
|
||||
|
||||
async function main() {
|
||||
await ensureSupportUserBootstrap()
|
||||
console.log("Support user bootstrap completed")
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -1,28 +1,106 @@
|
||||
import { authRouteHandlers, ensureAuthBootstrap } from "@/lib/auth/server"
|
||||
import {
|
||||
authRouteHandlers,
|
||||
canUserSelfRegister,
|
||||
ensureSupportUserBootstrap,
|
||||
hasOwnerUser,
|
||||
promoteFirstRegisteredUserToOwner,
|
||||
} from "@/lib/auth/server"
|
||||
|
||||
export const runtime = "nodejs"
|
||||
|
||||
type AuthPostResponse = {
|
||||
user?: {
|
||||
id?: string
|
||||
role?: string
|
||||
}
|
||||
message?: string
|
||||
}
|
||||
|
||||
function jsonResponse(payload: unknown, status: number): Response {
|
||||
return Response.json(payload, { status })
|
||||
}
|
||||
|
||||
async function handleSignUpPost(request: Request): Promise<Response> {
|
||||
await ensureSupportUserBootstrap()
|
||||
|
||||
const hadOwnerBeforeSignUp = await hasOwnerUser()
|
||||
const registrationEnabled = await canUserSelfRegister()
|
||||
|
||||
if (!registrationEnabled) {
|
||||
return jsonResponse(
|
||||
{
|
||||
message: "Registration is currently disabled.",
|
||||
},
|
||||
403,
|
||||
)
|
||||
}
|
||||
|
||||
const response = await authRouteHandlers.POST(request)
|
||||
|
||||
if (!response.ok) {
|
||||
return response
|
||||
}
|
||||
|
||||
const payload = (await response
|
||||
.clone()
|
||||
.json()
|
||||
.catch(() => null)) as AuthPostResponse | null
|
||||
const userId = payload?.user?.id
|
||||
|
||||
if (!userId) {
|
||||
return response
|
||||
}
|
||||
|
||||
if (hadOwnerBeforeSignUp || !payload?.user) {
|
||||
return response
|
||||
}
|
||||
|
||||
const promoted = await promoteFirstRegisteredUserToOwner(userId)
|
||||
|
||||
if (!promoted) {
|
||||
return jsonResponse(
|
||||
{
|
||||
message: "Initial owner registration window has just closed. Please sign in instead.",
|
||||
},
|
||||
409,
|
||||
)
|
||||
}
|
||||
|
||||
payload.user.role = "owner"
|
||||
|
||||
return new Response(JSON.stringify(payload), {
|
||||
status: response.status,
|
||||
headers: response.headers,
|
||||
})
|
||||
}
|
||||
|
||||
export async function GET(request: Request): Promise<Response> {
|
||||
await ensureAuthBootstrap()
|
||||
await ensureSupportUserBootstrap()
|
||||
return authRouteHandlers.GET(request)
|
||||
}
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
await ensureAuthBootstrap()
|
||||
const pathname = new URL(request.url).pathname
|
||||
|
||||
if (pathname.endsWith("/sign-up/email")) {
|
||||
return handleSignUpPost(request)
|
||||
}
|
||||
|
||||
await ensureSupportUserBootstrap()
|
||||
return authRouteHandlers.POST(request)
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request): Promise<Response> {
|
||||
await ensureAuthBootstrap()
|
||||
await ensureSupportUserBootstrap()
|
||||
return authRouteHandlers.PATCH(request)
|
||||
}
|
||||
|
||||
export async function PUT(request: Request): Promise<Response> {
|
||||
await ensureAuthBootstrap()
|
||||
await ensureSupportUserBootstrap()
|
||||
return authRouteHandlers.PUT(request)
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request): Promise<Response> {
|
||||
await ensureAuthBootstrap()
|
||||
await ensureSupportUserBootstrap()
|
||||
return authRouteHandlers.DELETE(request)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"use client"
|
||||
|
||||
import Link from "next/link"
|
||||
import { useRouter, useSearchParams } from "next/navigation"
|
||||
import { type FormEvent, useMemo, useState } from "react"
|
||||
|
||||
type LoginFormProps = {
|
||||
allowRegistration: boolean
|
||||
mode: "signin" | "signup-owner" | "signup-user"
|
||||
}
|
||||
|
||||
type AuthResponse = {
|
||||
@@ -23,7 +24,7 @@ function persistRoleCookie(role: unknown) {
|
||||
document.cookie = `cms_role=${encodeURIComponent(role)}; Path=/; SameSite=Lax`
|
||||
}
|
||||
|
||||
export function LoginForm({ allowRegistration }: LoginFormProps) {
|
||||
export function LoginForm({ mode }: LoginFormProps) {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
|
||||
@@ -72,7 +73,9 @@ export function LoginForm({ allowRegistration }: LoginFormProps) {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSignUp() {
|
||||
async function handleSignUp(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault()
|
||||
|
||||
if (!name.trim()) {
|
||||
setError("Name is required for account creation")
|
||||
return
|
||||
@@ -104,7 +107,11 @@ export function LoginForm({ allowRegistration }: LoginFormProps) {
|
||||
}
|
||||
|
||||
persistRoleCookie(payload?.user?.role)
|
||||
setSuccess("Account created. You can continue to the dashboard.")
|
||||
setSuccess(
|
||||
mode === "signup-owner"
|
||||
? "Owner account created. Registration is now disabled."
|
||||
: "Account created.",
|
||||
)
|
||||
router.push(nextPath)
|
||||
router.refresh()
|
||||
} catch {
|
||||
@@ -118,87 +125,147 @@ export function LoginForm({ allowRegistration }: LoginFormProps) {
|
||||
<main className="mx-auto flex min-h-screen w-full max-w-md flex-col justify-center px-6 py-16">
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm uppercase tracking-[0.2em] text-neutral-500">Admin Auth</p>
|
||||
<h1 className="text-3xl font-semibold tracking-tight">Sign in to CMS Admin</h1>
|
||||
<h1 className="text-3xl font-semibold tracking-tight">
|
||||
{mode === "signin"
|
||||
? "Sign in to CMS Admin"
|
||||
: mode === "signup-owner"
|
||||
? "Welcome to CMS Admin"
|
||||
: "Create an admin account"}
|
||||
</h1>
|
||||
<p className="text-sm text-neutral-600">
|
||||
Better Auth is active on this app via <code>/api/auth</code>.
|
||||
{mode === "signin" ? (
|
||||
<>
|
||||
Better Auth is active on this app via <code>/api/auth</code>.
|
||||
</>
|
||||
) : mode === "signup-owner" ? (
|
||||
"Create the first owner account to initialize this admin instance."
|
||||
) : (
|
||||
"Self-registration is enabled for admin users."
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form
|
||||
onSubmit={handleSignIn}
|
||||
className="mt-8 space-y-4 rounded-xl border border-neutral-200 p-6"
|
||||
>
|
||||
<div className="space-y-1">
|
||||
<label className="text-sm font-medium" htmlFor="email">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
className="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-sm font-medium" htmlFor="password">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
minLength={8}
|
||||
required
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
className="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isBusy}
|
||||
className="w-full rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white disabled:opacity-60"
|
||||
{mode === "signin" ? (
|
||||
<form
|
||||
onSubmit={handleSignIn}
|
||||
className="mt-8 space-y-4 rounded-xl border border-neutral-200 p-6"
|
||||
>
|
||||
{isBusy ? "Signing in..." : "Sign in"}
|
||||
</button>
|
||||
<div className="space-y-1">
|
||||
<label className="text-sm font-medium" htmlFor="email">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
className="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-sm font-medium" htmlFor="password">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
minLength={8}
|
||||
required
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
className="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isBusy}
|
||||
className="w-full rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white disabled:opacity-60"
|
||||
>
|
||||
{isBusy ? "Signing in..." : "Sign in"}
|
||||
</button>
|
||||
|
||||
{allowRegistration ? (
|
||||
<>
|
||||
<div className="space-y-1 pt-2">
|
||||
<label className="text-sm font-medium" htmlFor="name">
|
||||
Name (for first account creation)
|
||||
</label>
|
||||
<input
|
||||
id="name"
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
className="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void handleSignUp()
|
||||
}}
|
||||
disabled={isBusy}
|
||||
className="w-full rounded-md border border-neutral-300 px-4 py-2 text-sm font-medium disabled:opacity-60"
|
||||
>
|
||||
{isBusy ? "Creating account..." : "Create account"}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-xs text-neutral-600">
|
||||
Registration is disabled. Ask an owner or support user to create your account.
|
||||
Need an account?{" "}
|
||||
<Link href={`/register?next=${encodeURIComponent(nextPath)}`} className="underline">
|
||||
Register
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{error ? <p className="text-sm text-red-600">{error}</p> : null}
|
||||
{success ? <p className="text-sm text-green-700">{success}</p> : null}
|
||||
</form>
|
||||
{error ? <p className="text-sm text-red-600">{error}</p> : null}
|
||||
</form>
|
||||
) : (
|
||||
<form
|
||||
onSubmit={handleSignUp}
|
||||
className="mt-8 space-y-4 rounded-xl border border-neutral-200 p-6"
|
||||
>
|
||||
<div className="space-y-1">
|
||||
<label className="text-sm font-medium" htmlFor="name">
|
||||
Name
|
||||
</label>
|
||||
<input
|
||||
id="name"
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
className="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-sm font-medium" htmlFor="email">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
className="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-sm font-medium" htmlFor="password">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
minLength={8}
|
||||
required
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
className="w-full rounded-md border border-neutral-300 px-3 py-2 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isBusy}
|
||||
className="w-full rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white disabled:opacity-60"
|
||||
>
|
||||
{isBusy
|
||||
? "Creating account..."
|
||||
: mode === "signup-owner"
|
||||
? "Create owner account"
|
||||
: "Create account"}
|
||||
</button>
|
||||
|
||||
<p className="text-xs text-neutral-600">
|
||||
Already have an account?{" "}
|
||||
<Link href={`/login?next=${encodeURIComponent(nextPath)}`} className="underline">
|
||||
Go to sign in
|
||||
</Link>
|
||||
</p>
|
||||
|
||||
{error ? <p className="text-sm text-red-600">{error}</p> : null}
|
||||
{success ? <p className="text-sm text-green-700">{success}</p> : null}
|
||||
</form>
|
||||
)}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,18 +1,36 @@
|
||||
import { redirect } from "next/navigation"
|
||||
|
||||
import { resolveRoleFromServerContext } from "@/lib/access-server"
|
||||
import { isAdminRegistrationEnabled } from "@/lib/auth/server"
|
||||
import { hasOwnerUser } from "@/lib/auth/server"
|
||||
|
||||
import { LoginForm } from "./login-form"
|
||||
|
||||
export const dynamic = "force-dynamic"
|
||||
|
||||
export default async function LoginPage() {
|
||||
type SearchParams = Promise<Record<string, string | string[] | undefined>>
|
||||
|
||||
function getSingleValue(input: string | string[] | undefined): string | undefined {
|
||||
if (Array.isArray(input)) {
|
||||
return input[0]
|
||||
}
|
||||
|
||||
return input
|
||||
}
|
||||
|
||||
export default async function LoginPage({ searchParams }: { searchParams: SearchParams }) {
|
||||
const params = await searchParams
|
||||
const nextPath = getSingleValue(params.next) ?? "/"
|
||||
const role = await resolveRoleFromServerContext()
|
||||
|
||||
if (role) {
|
||||
redirect("/")
|
||||
}
|
||||
|
||||
return <LoginForm allowRegistration={isAdminRegistrationEnabled()} />
|
||||
const hasOwner = await hasOwnerUser()
|
||||
|
||||
if (!hasOwner) {
|
||||
redirect(`/welcome?next=${encodeURIComponent(nextPath)}`)
|
||||
}
|
||||
|
||||
return <LoginForm mode="signin" />
|
||||
}
|
||||
|
||||
40
apps/admin/src/app/register/page.tsx
Normal file
40
apps/admin/src/app/register/page.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import { redirect } from "next/navigation"
|
||||
import { LoginForm } from "@/app/login/login-form"
|
||||
import { resolveRoleFromServerContext } from "@/lib/access-server"
|
||||
import { hasOwnerUser, isSelfRegistrationEnabled } from "@/lib/auth/server"
|
||||
|
||||
export const dynamic = "force-dynamic"
|
||||
|
||||
type SearchParams = Promise<Record<string, string | string[] | undefined>>
|
||||
|
||||
function getSingleValue(input: string | string[] | undefined): string | undefined {
|
||||
if (Array.isArray(input)) {
|
||||
return input[0]
|
||||
}
|
||||
|
||||
return input
|
||||
}
|
||||
|
||||
export default async function RegisterPage({ searchParams }: { searchParams: SearchParams }) {
|
||||
const params = await searchParams
|
||||
const nextPath = getSingleValue(params.next) ?? "/"
|
||||
const role = await resolveRoleFromServerContext()
|
||||
|
||||
if (role) {
|
||||
redirect("/")
|
||||
}
|
||||
|
||||
const hasOwner = await hasOwnerUser()
|
||||
|
||||
if (!hasOwner) {
|
||||
redirect(`/welcome?next=${encodeURIComponent(nextPath)}`)
|
||||
}
|
||||
|
||||
const enabled = await isSelfRegistrationEnabled()
|
||||
|
||||
if (!enabled) {
|
||||
redirect(`/login?next=${encodeURIComponent(nextPath)}`)
|
||||
}
|
||||
|
||||
return <LoginForm mode="signup-user" />
|
||||
}
|
||||
23
apps/admin/src/app/support/[key]/page.tsx
Normal file
23
apps/admin/src/app/support/[key]/page.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { notFound, redirect } from "next/navigation"
|
||||
import { LoginForm } from "@/app/login/login-form"
|
||||
import { resolveRoleFromServerContext } from "@/lib/access-server"
|
||||
import { resolveSupportLoginKey } from "@/lib/auth/server"
|
||||
|
||||
export const dynamic = "force-dynamic"
|
||||
|
||||
type Params = Promise<{ key: string }>
|
||||
|
||||
export default async function SupportLoginPage({ params }: { params: Params }) {
|
||||
const { key } = await params
|
||||
const role = await resolveRoleFromServerContext()
|
||||
|
||||
if (role) {
|
||||
redirect("/")
|
||||
}
|
||||
|
||||
if (key !== resolveSupportLoginKey()) {
|
||||
notFound()
|
||||
}
|
||||
|
||||
return <LoginForm mode="signin" />
|
||||
}
|
||||
34
apps/admin/src/app/welcome/page.tsx
Normal file
34
apps/admin/src/app/welcome/page.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import { redirect } from "next/navigation"
|
||||
import { LoginForm } from "@/app/login/login-form"
|
||||
import { resolveRoleFromServerContext } from "@/lib/access-server"
|
||||
import { hasOwnerUser } from "@/lib/auth/server"
|
||||
|
||||
export const dynamic = "force-dynamic"
|
||||
|
||||
type SearchParams = Promise<Record<string, string | string[] | undefined>>
|
||||
|
||||
function getSingleValue(input: string | string[] | undefined): string | undefined {
|
||||
if (Array.isArray(input)) {
|
||||
return input[0]
|
||||
}
|
||||
|
||||
return input
|
||||
}
|
||||
|
||||
export default async function WelcomePage({ searchParams }: { searchParams: SearchParams }) {
|
||||
const params = await searchParams
|
||||
const nextPath = getSingleValue(params.next) ?? "/"
|
||||
const role = await resolveRoleFromServerContext()
|
||||
|
||||
if (role) {
|
||||
redirect("/")
|
||||
}
|
||||
|
||||
const hasOwner = await hasOwnerUser()
|
||||
|
||||
if (hasOwner) {
|
||||
redirect(`/login?next=${encodeURIComponent(nextPath)}`)
|
||||
}
|
||||
|
||||
return <LoginForm mode="signup-owner" />
|
||||
}
|
||||
@@ -24,6 +24,18 @@ const guardRules: GuardRule[] = [
|
||||
route: /^\/login(?:\/|$)/,
|
||||
requirement: null,
|
||||
},
|
||||
{
|
||||
route: /^\/register(?:\/|$)/,
|
||||
requirement: null,
|
||||
},
|
||||
{
|
||||
route: /^\/welcome(?:\/|$)/,
|
||||
requirement: null,
|
||||
},
|
||||
{
|
||||
route: /^\/support\/[^/]+(?:\/|$)/,
|
||||
requirement: null,
|
||||
},
|
||||
{
|
||||
route: /^\/todo(?:\/|$)/,
|
||||
requirement: {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import "server-only"
|
||||
|
||||
import { normalizeRole, type Role } from "@cms/content/rbac"
|
||||
import { db } from "@cms/db"
|
||||
import { betterAuth } from "better-auth"
|
||||
@@ -12,12 +10,10 @@ const isProduction = process.env.NODE_ENV === "production"
|
||||
|
||||
const adminOrigin = process.env.CMS_ADMIN_ORIGIN ?? "http://localhost:3001"
|
||||
const webOrigin = process.env.CMS_WEB_ORIGIN ?? "http://localhost:3000"
|
||||
const DEFAULT_OWNER_EMAIL = "owner@cms.local"
|
||||
const DEFAULT_OWNER_PASSWORD = "change-me-owner-password"
|
||||
const DEFAULT_OWNER_NAME = "Owner"
|
||||
const DEFAULT_SUPPORT_EMAIL = "support@cms.local"
|
||||
const DEFAULT_SUPPORT_USERNAME = "support"
|
||||
const DEFAULT_SUPPORT_PASSWORD = "change-me-support-password"
|
||||
const DEFAULT_SUPPORT_NAME = "Technical Support"
|
||||
const DEFAULT_SUPPORT_LOGIN_KEY = "support-access"
|
||||
|
||||
function resolveAuthSecret(): string {
|
||||
const value = process.env.BETTER_AUTH_SECRET
|
||||
@@ -33,18 +29,43 @@ function resolveAuthSecret(): string {
|
||||
return FALLBACK_DEV_SECRET
|
||||
}
|
||||
|
||||
export function isAdminRegistrationEnabled(): boolean {
|
||||
const value = process.env.CMS_ADMIN_REGISTRATION_ENABLED
|
||||
export async function hasOwnerUser(): Promise<boolean> {
|
||||
const ownerCount = await db.user.count({
|
||||
where: { role: "owner" },
|
||||
})
|
||||
|
||||
if (value === "true") {
|
||||
return ownerCount > 0
|
||||
}
|
||||
|
||||
export async function isInitialOwnerRegistrationOpen(): Promise<boolean> {
|
||||
return !(await hasOwnerUser())
|
||||
}
|
||||
|
||||
export async function isSelfRegistrationEnabled(): Promise<boolean> {
|
||||
// Temporary fallback until registration policy is managed from admin settings.
|
||||
return process.env.CMS_ADMIN_SELF_REGISTRATION_ENABLED === "true"
|
||||
}
|
||||
|
||||
export async function canUserSelfRegister(): Promise<boolean> {
|
||||
if (!(await hasOwnerUser())) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (value === "false") {
|
||||
return false
|
||||
return isSelfRegistrationEnabled()
|
||||
}
|
||||
|
||||
export function resolveSupportLoginKey(): string {
|
||||
const value = process.env.CMS_SUPPORT_LOGIN_KEY
|
||||
|
||||
if (value) {
|
||||
return value
|
||||
}
|
||||
|
||||
return !isProduction
|
||||
if (isProduction) {
|
||||
throw new Error("CMS_SUPPORT_LOGIN_KEY is required in production")
|
||||
}
|
||||
|
||||
return DEFAULT_SUPPORT_LOGIN_KEY
|
||||
}
|
||||
|
||||
function resolveBootstrapValue(
|
||||
@@ -77,7 +98,9 @@ export const auth = betterAuth({
|
||||
}),
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
disableSignUp: !isAdminRegistrationEnabled(),
|
||||
// Sign-up gating is handled in route layer so we can close registration
|
||||
// automatically after the first owner account is created.
|
||||
disableSignUp: false,
|
||||
},
|
||||
user: {
|
||||
additionalFields: {
|
||||
@@ -119,7 +142,7 @@ export const authRouteHandlers = toNextJsHandler(auth)
|
||||
|
||||
export type AuthSession = typeof auth.$Infer.Session
|
||||
|
||||
let bootstrapPromise: Promise<void> | null = null
|
||||
let supportBootstrapPromise: Promise<void> | null = null
|
||||
|
||||
type BootstrapUserConfig = {
|
||||
email: string
|
||||
@@ -188,7 +211,8 @@ async function ensureCredentialUser(config: BootstrapUserConfig): Promise<void>
|
||||
}
|
||||
|
||||
async function bootstrapSystemUsers(): Promise<void> {
|
||||
const supportEmail = resolveBootstrapValue("CMS_SUPPORT_EMAIL", DEFAULT_SUPPORT_EMAIL)
|
||||
const supportUsername = resolveBootstrapValue("CMS_SUPPORT_USERNAME", DEFAULT_SUPPORT_USERNAME)
|
||||
const supportEmail = resolveBootstrapValue("CMS_SUPPORT_EMAIL", `${supportUsername}@cms.local`)
|
||||
const supportPassword = resolveBootstrapValue("CMS_SUPPORT_PASSWORD", DEFAULT_SUPPORT_PASSWORD, {
|
||||
requiredInProduction: true,
|
||||
})
|
||||
@@ -201,58 +225,50 @@ async function bootstrapSystemUsers(): Promise<void> {
|
||||
role: "support",
|
||||
isHidden: true,
|
||||
})
|
||||
|
||||
const ownerCount = await db.user.count({
|
||||
where: { role: "owner" },
|
||||
})
|
||||
|
||||
if (ownerCount > 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const nonSupportUserCount = await db.user.count({
|
||||
where: {
|
||||
role: {
|
||||
not: "support",
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (nonSupportUserCount > 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const ownerEmail = resolveBootstrapValue("CMS_OWNER_EMAIL", DEFAULT_OWNER_EMAIL)
|
||||
const ownerPassword = resolveBootstrapValue("CMS_OWNER_PASSWORD", DEFAULT_OWNER_PASSWORD, {
|
||||
requiredInProduction: true,
|
||||
})
|
||||
const ownerName = resolveBootstrapValue("CMS_OWNER_NAME", DEFAULT_OWNER_NAME)
|
||||
|
||||
await ensureCredentialUser({
|
||||
email: ownerEmail,
|
||||
name: ownerName,
|
||||
password: ownerPassword,
|
||||
role: "owner",
|
||||
isHidden: false,
|
||||
})
|
||||
}
|
||||
|
||||
export async function ensureAuthBootstrap(): Promise<void> {
|
||||
if (bootstrapPromise) {
|
||||
await bootstrapPromise
|
||||
export async function ensureSupportUserBootstrap(): Promise<void> {
|
||||
if (supportBootstrapPromise) {
|
||||
await supportBootstrapPromise
|
||||
return
|
||||
}
|
||||
|
||||
bootstrapPromise = bootstrapSystemUsers()
|
||||
supportBootstrapPromise = bootstrapSystemUsers()
|
||||
|
||||
try {
|
||||
await bootstrapPromise
|
||||
await supportBootstrapPromise
|
||||
} catch (error) {
|
||||
bootstrapPromise = null
|
||||
supportBootstrapPromise = null
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function promoteFirstRegisteredUserToOwner(userId: string): Promise<boolean> {
|
||||
return db.$transaction(async (tx) => {
|
||||
const existingOwner = await tx.user.findFirst({
|
||||
where: { role: "owner" },
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
if (existingOwner) {
|
||||
return false
|
||||
}
|
||||
|
||||
await tx.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
role: "owner",
|
||||
isSystem: false,
|
||||
isHidden: false,
|
||||
isProtected: true,
|
||||
isBanned: false,
|
||||
},
|
||||
})
|
||||
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
export function resolveRoleFromAuthSession(session: AuthSession | null | undefined): Role | null {
|
||||
const sessionUserRole = session?.user?.role
|
||||
|
||||
|
||||
Reference in New Issue
Block a user