- Centralize secret retrieval using `getAdminSessionSecret` - Replace manual session parsing with `verifyRequestAdminSession` utility - Tighten API validation and improve security headers handling - Enforce environment variable security for production deployments
159 lines
4.3 KiB
TypeScript
159 lines
4.3 KiB
TypeScript
import {
|
|
createAdminSessionToken,
|
|
getSessionCookieOptions,
|
|
} from "@/core/auth/adminSession";
|
|
import {
|
|
getAdminAccountInfo,
|
|
updateAdminAccount,
|
|
verifyRequestAdminSession,
|
|
} from "@/core/auth/adminUsers";
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
|
|
const SESSION_COOKIE = "datastack_admin_session";
|
|
const SESSION_SECONDS = 8 * 60 * 60;
|
|
|
|
function validEmail(email: string) {
|
|
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
|
|
}
|
|
|
|
export async function GET(request: NextRequest) {
|
|
const token = request.cookies.get(SESSION_COOKIE)?.value;
|
|
const auth = await verifyRequestAdminSession(token);
|
|
|
|
if (!auth.valid) {
|
|
const status = auth.reason === "UNAUTHORIZED" ? 401 : 503;
|
|
const message =
|
|
auth.reason === "UNAUTHORIZED"
|
|
? "Authentication required."
|
|
: "Admin authentication is temporarily unavailable.";
|
|
return NextResponse.json({ error: message }, { status });
|
|
}
|
|
|
|
try {
|
|
const account = await getAdminAccountInfo(auth.session.email);
|
|
return NextResponse.json({
|
|
profile: {
|
|
email: account.email,
|
|
role: "Owner",
|
|
storageMode: account.storageMode,
|
|
createdAt: account.createdAt,
|
|
sessionExpiresAt: new Date(auth.session.expiresAt).toISOString(),
|
|
},
|
|
});
|
|
} catch {
|
|
return NextResponse.json(
|
|
{ error: "Unable to load admin profile." },
|
|
{ status: 503 },
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function PUT(request: NextRequest) {
|
|
const token = request.cookies.get(SESSION_COOKIE)?.value;
|
|
const auth = await verifyRequestAdminSession(token);
|
|
|
|
if (!auth.valid) {
|
|
const status = auth.reason === "UNAUTHORIZED" ? 401 : 503;
|
|
const message =
|
|
auth.reason === "UNAUTHORIZED"
|
|
? "Authentication required."
|
|
: "Admin authentication is temporarily unavailable.";
|
|
return NextResponse.json({ error: message }, { status });
|
|
}
|
|
|
|
let body: Record<string, unknown>;
|
|
try {
|
|
const parsed = await request.json();
|
|
body =
|
|
parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
? (parsed as Record<string, unknown>)
|
|
: {};
|
|
} catch {
|
|
return NextResponse.json(
|
|
{ error: "Invalid profile payload." },
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
|
|
try {
|
|
const nextEmail =
|
|
typeof body.email === "string"
|
|
? body.email.trim().toLowerCase()
|
|
: auth.session.email;
|
|
const currentPassword =
|
|
typeof body.currentPassword === "string" ? body.currentPassword : "";
|
|
const newPassword =
|
|
typeof body.newPassword === "string" ? body.newPassword : "";
|
|
|
|
if (!validEmail(nextEmail)) {
|
|
return NextResponse.json(
|
|
{ error: "Enter a valid email address." },
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
|
|
if (!currentPassword) {
|
|
return NextResponse.json(
|
|
{ error: "Current password is required to save changes." },
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
|
|
if (newPassword && (newPassword.length < 8 || newPassword.length > 256)) {
|
|
return NextResponse.json(
|
|
{ error: "New password must be between 8 and 256 characters." },
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
|
|
const account = await getAdminAccountInfo(auth.session.email);
|
|
const result = await updateAdminAccount({
|
|
currentEmail: account.email,
|
|
currentPassword,
|
|
nextEmail,
|
|
nextPassword: newPassword || undefined,
|
|
});
|
|
|
|
if (!result.ok) {
|
|
return NextResponse.json({ error: result.error }, { status: 401 });
|
|
}
|
|
|
|
// Preserve remaining session duration (e.g., 30-day "Remember me" session)
|
|
const remainingSeconds = Math.max(
|
|
SESSION_SECONDS,
|
|
Math.ceil((auth.session.expiresAt - Date.now()) / 1000),
|
|
);
|
|
const expiresAt = Date.now() + remainingSeconds * 1000;
|
|
const nextToken = await createAdminSessionToken(
|
|
result.email,
|
|
auth.sessionSecret,
|
|
expiresAt,
|
|
result.tokenVersion,
|
|
);
|
|
|
|
const response = NextResponse.json({
|
|
success: true,
|
|
profile: {
|
|
email: result.email,
|
|
role: "Owner",
|
|
storageMode: account.storageMode,
|
|
createdAt: account.createdAt,
|
|
sessionExpiresAt: new Date(expiresAt).toISOString(),
|
|
},
|
|
});
|
|
|
|
response.cookies.set(
|
|
SESSION_COOKIE,
|
|
nextToken,
|
|
getSessionCookieOptions(request, remainingSeconds),
|
|
);
|
|
|
|
return response;
|
|
} catch {
|
|
return NextResponse.json(
|
|
{ error: "Unable to update profile." },
|
|
{ status: 500 },
|
|
);
|
|
}
|
|
}
|