refactor(auth): standardize session management and security
- 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
This commit is contained in:
1 parent
34519c07df
commit
177ed4a844
78 files changed
+6748
-3157
No files matched your search
+102
-79
@@ -1,11 +1,12 @@
|
||||
import {
|
||||
createAdminSessionToken,
|
||||
getAdminSessionSecret,
|
||||
getSessionCookieOptions,
|
||||
} from "@/core/auth/adminSession";
|
||||
import {
|
||||
authenticateAdminCredentials,
|
||||
clearAdminLoginAttempts,
|
||||
consumeAdminLoginAttempt,
|
||||
verifyAdminCredentials,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
@@ -13,10 +14,19 @@ const SESSION_COOKIE = "datastack_admin_session";
|
||||
const SESSION_SECONDS = 8 * 60 * 60;
|
||||
const REMEMBERED_SESSION_SECONDS = 30 * 24 * 60 * 60;
|
||||
|
||||
function extractClientIp(request: NextRequest) {
|
||||
const forwardedFor = request.headers.get("x-forwarded-for");
|
||||
if (forwardedFor) {
|
||||
const first = forwardedFor.split(",")[0]?.trim();
|
||||
if (first) return first;
|
||||
}
|
||||
const realIp = request.headers.get("x-real-ip")?.trim();
|
||||
if (realIp) return realIp;
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const sessionSecret =
|
||||
process.env.DATASTACK_ADMIN_SESSION_SECRET ||
|
||||
"datastack-admin-session-default-secret-32-chars";
|
||||
const sessionSecret = getAdminSessionSecret();
|
||||
|
||||
if (!sessionSecret || sessionSecret.length < 32) {
|
||||
return NextResponse.json(
|
||||
@@ -27,86 +37,99 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
const body = await request.json();
|
||||
const email =
|
||||
typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
|
||||
const password = typeof body.password === "string" ? body.password : "";
|
||||
if (!email || password.length === 0 || password.length > 1024) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid email or password." },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
let throttleDecision;
|
||||
try {
|
||||
throttleDecision = await consumeAdminLoginAttempt(email, sessionSecret);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Admin authentication is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
if (!throttleDecision.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: "Too many sign-in attempts. Try again later." },
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
"Retry-After": String(throttleDecision.retryAfterSeconds),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let authenticated = false;
|
||||
try {
|
||||
authenticated = await verifyAdminCredentials(email, password);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Admin authentication is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
if (!authenticated) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid email or password." },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await clearAdminLoginAttempts(email, sessionSecret);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Admin authentication is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
const remember = body.remember === true;
|
||||
const maxAge = remember ? REMEMBERED_SESSION_SECONDS : SESSION_SECONDS;
|
||||
const expiresAt = Date.now() + maxAge * 1000;
|
||||
const token = await createAdminSessionToken(
|
||||
email,
|
||||
sessionSecret,
|
||||
expiresAt,
|
||||
);
|
||||
const response = NextResponse.json({ success: true });
|
||||
|
||||
response.cookies.set(
|
||||
SESSION_COOKIE,
|
||||
token,
|
||||
getSessionCookieOptions(request, maxAge),
|
||||
);
|
||||
|
||||
return response;
|
||||
const parsed = await request.json();
|
||||
body =
|
||||
parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: {};
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid login request." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const email =
|
||||
typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
|
||||
const password = typeof body.password === "string" ? body.password : "";
|
||||
if (!email || password.length === 0 || password.length > 1024) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid email or password." },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
const clientIp = extractClientIp(request);
|
||||
|
||||
let throttleDecision;
|
||||
try {
|
||||
throttleDecision = await consumeAdminLoginAttempt(
|
||||
email,
|
||||
sessionSecret,
|
||||
clientIp,
|
||||
);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Admin authentication is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
if (!throttleDecision.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: "Too many sign-in attempts. Try again later." },
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
"Retry-After": String(throttleDecision.retryAfterSeconds),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let authResult: { authenticated: boolean; tokenVersion: number };
|
||||
try {
|
||||
authResult = await authenticateAdminCredentials(email, password);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Admin authentication is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
if (!authResult.authenticated) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid email or password." },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await clearAdminLoginAttempts(email, sessionSecret, clientIp);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Admin authentication is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
const remember = body.remember === true;
|
||||
const maxAge = remember ? REMEMBERED_SESSION_SECONDS : SESSION_SECONDS;
|
||||
const expiresAt = Date.now() + maxAge * 1000;
|
||||
const token = await createAdminSessionToken(
|
||||
email,
|
||||
sessionSecret,
|
||||
expiresAt,
|
||||
authResult.tokenVersion,
|
||||
);
|
||||
const response = NextResponse.json({ success: true });
|
||||
|
||||
response.cookies.set(
|
||||
SESSION_COOKIE,
|
||||
token,
|
||||
getSessionCookieOptions(request, maxAge),
|
||||
);
|
||||
|
||||
return response;
|
||||
}
|
||||
Reference in new issue
Block a user