Initial commit: page-manager Next.js app with Coolify deploy support
Replace Vercel-specific infra (Cron, Blob) with self-hosted equivalents for deployment to Coolify: in-container cron scheduler (scripts/cron-runner.mjs) and disk-based upload storage served via /api/uploads/[...path]. Add Dockerfile, .dockerignore, and /api/health for container health checks. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireUser } from "@/lib/auth/user";
|
||||
import { createSessionToken, COOKIE_NAME, SESSION_DURATION_SECONDS } from "@/lib/auth/session";
|
||||
import { hashPassword, passwordProblem, verifyPassword } from "@/lib/auth/password";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const auth = await requireUser();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
const currentPassword = typeof body?.currentPassword === "string" ? body.currentPassword : "";
|
||||
const newPassword = typeof body?.newPassword === "string" ? body.newPassword : "";
|
||||
|
||||
const user = await prisma.user.findUniqueOrThrow({ where: { id: auth.user.id } });
|
||||
|
||||
if (!(await verifyPassword(currentPassword, user.passwordHash))) {
|
||||
return NextResponse.json({ error: "รหัสผ่านปัจจุบันไม่ถูกต้อง" }, { status: 400 });
|
||||
}
|
||||
|
||||
const problem = passwordProblem(newPassword);
|
||||
if (problem) return NextResponse.json({ error: problem }, { status: 400 });
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { passwordHash: await hashPassword(newPassword), mustChangePassword: false },
|
||||
});
|
||||
|
||||
const token = await createSessionToken({
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.globalRole,
|
||||
mustChangePassword: false,
|
||||
});
|
||||
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.set(COOKIE_NAME, token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "strict",
|
||||
path: "/",
|
||||
maxAge: SESSION_DURATION_SECONDS,
|
||||
});
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { createSessionToken, COOKIE_NAME, sessionCookieOptions } from "@/lib/auth/session";
|
||||
import { checkRateLimit, recordFailedAttempt, resetAttempts } from "@/lib/auth/rateLimit";
|
||||
import { fakeVerifyDelay, verifyPassword } from "@/lib/auth/password";
|
||||
|
||||
const GENERIC_ERROR = "อีเมลหรือรหัสผ่านไม่ถูกต้อง";
|
||||
|
||||
function clientIp(request: Request): string {
|
||||
const fwd = request.headers.get("x-forwarded-for");
|
||||
return fwd?.split(",")[0]?.trim() || "unknown";
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const ip = clientIp(request);
|
||||
const limit = checkRateLimit(ip);
|
||||
if (!limit.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: `พยายามเข้าสู่ระบบบ่อยเกินไป กรุณารออีก ${limit.retryAfterSeconds} วินาที` },
|
||||
{ status: 429 }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const email = typeof body?.email === "string" ? body.email.trim().toLowerCase() : "";
|
||||
const password = typeof body?.password === "string" ? body.password : "";
|
||||
const remember = body?.remember !== false;
|
||||
|
||||
if (!email || !password) {
|
||||
return NextResponse.json({ error: "กรอกอีเมลและรหัสผ่าน" }, { status: 400 });
|
||||
}
|
||||
|
||||
const userCount = await prisma.user.count();
|
||||
if (userCount === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "ยังไม่มีผู้ใช้ในระบบ สร้างแอดมินคนแรกด้วย npm run user:create" },
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { email } });
|
||||
|
||||
// Same failure shape and roughly the same cost for unknown email, wrong
|
||||
// password, and deactivated account — no probing which emails are valid.
|
||||
if (!user || !user.isActive) {
|
||||
await fakeVerifyDelay();
|
||||
recordFailedAttempt(ip);
|
||||
return NextResponse.json({ error: GENERIC_ERROR }, { status: 401 });
|
||||
}
|
||||
|
||||
if (!(await verifyPassword(password, user.passwordHash))) {
|
||||
recordFailedAttempt(ip);
|
||||
return NextResponse.json({ error: GENERIC_ERROR }, { status: 401 });
|
||||
}
|
||||
|
||||
resetAttempts(ip);
|
||||
await prisma.user.update({ where: { id: user.id }, data: { lastLoginAt: new Date() } });
|
||||
|
||||
const token = await createSessionToken({
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.globalRole,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
});
|
||||
|
||||
const res = NextResponse.json({
|
||||
ok: true,
|
||||
user: { name: user.name, email: user.email, role: user.globalRole },
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
});
|
||||
res.cookies.set(COOKIE_NAME, token, sessionCookieOptions(remember));
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { COOKIE_NAME } from "@/lib/auth/session";
|
||||
|
||||
export async function POST() {
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.delete(COOKIE_NAME);
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { COOKIE_NAME, createSessionToken, sessionCookieOptions } from "@/lib/auth/session";
|
||||
import {
|
||||
fetchSocialProfile,
|
||||
parseProvider,
|
||||
resolveSocialUser,
|
||||
SOCIAL_STATE_COOKIE,
|
||||
SOCIAL_STATE_PATH,
|
||||
SocialLoginError,
|
||||
verifySocialState,
|
||||
type SocialErrorCode,
|
||||
} from "@/lib/auth/social";
|
||||
import { htmlRedirect } from "@/lib/http";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* The provider redirects here cross-site, so identity comes from the signed
|
||||
* Lax state cookie (route is under SELF_AUTH_PREFIXES in src/proxy.ts). Every
|
||||
* exit is an HTML hop so the next navigation is same-site and the Strict
|
||||
* session cookie set here is sent.
|
||||
*/
|
||||
export async function GET(req: Request, ctx: RouteContext<"/api/auth/oauth/[provider]/callback">) {
|
||||
const { provider: raw } = await ctx.params;
|
||||
const url = new URL(req.url);
|
||||
const jar = await cookies();
|
||||
const stateCookie = jar.get(SOCIAL_STATE_COOKIE)?.value;
|
||||
jar.delete({ name: SOCIAL_STATE_COOKIE, path: SOCIAL_STATE_PATH });
|
||||
|
||||
const provider = parseProvider(raw);
|
||||
const fail = (code: SocialErrorCode, email?: string) => {
|
||||
const q = new URLSearchParams({ error: code });
|
||||
if (provider) q.set("provider", provider);
|
||||
if (email) q.set("email", email);
|
||||
return htmlRedirect(`/login?${q}`);
|
||||
};
|
||||
if (!provider) return fail("not_configured");
|
||||
|
||||
const state = await verifySocialState(stateCookie, url.searchParams.get("state"), provider);
|
||||
if (!state) return fail("expired");
|
||||
|
||||
const providerError = url.searchParams.get("error");
|
||||
if (providerError) return fail(providerError === "access_denied" ? "cancelled" : "failed");
|
||||
|
||||
const code = url.searchParams.get("code");
|
||||
if (!code) return fail("failed");
|
||||
|
||||
try {
|
||||
const profile = await fetchSocialProfile(provider, url.origin, code);
|
||||
const user = await resolveSocialUser(provider, profile);
|
||||
await prisma.user.update({ where: { id: user.id }, data: { lastLoginAt: new Date() } });
|
||||
|
||||
const token = await createSessionToken({
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.globalRole,
|
||||
// The forced change exists because an admin knows the temporary
|
||||
// password. A social login never uses that password, so it isn't
|
||||
// forced here; the DB flag stays set and still applies to password login.
|
||||
mustChangePassword: false,
|
||||
});
|
||||
jar.set(COOKIE_NAME, token, sessionCookieOptions(state.remember));
|
||||
return htmlRedirect(state.from);
|
||||
} catch (e) {
|
||||
if (e instanceof SocialLoginError) return fail(e.code, e.email);
|
||||
console.error("[auth:social] callback failed", e instanceof Error ? e.message : e);
|
||||
return fail("failed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import {
|
||||
authorizeUrl,
|
||||
createSocialState,
|
||||
enabledProviders,
|
||||
parseProvider,
|
||||
safeRedirectPath,
|
||||
SOCIAL_STATE_COOKIE,
|
||||
SOCIAL_STATE_PATH,
|
||||
SOCIAL_STATE_TTL_SECONDS,
|
||||
} from "@/lib/auth/social";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Public: sends the browser to the Google / Facebook sign-in dialog. */
|
||||
export async function GET(req: Request, ctx: RouteContext<"/api/auth/oauth/[provider]/start">) {
|
||||
const { provider: raw } = await ctx.params;
|
||||
const url = new URL(req.url);
|
||||
const provider = parseProvider(raw);
|
||||
if (!provider || !enabledProviders().includes(provider)) {
|
||||
return NextResponse.redirect(new URL("/login?error=not_configured", url.origin));
|
||||
}
|
||||
|
||||
const { nonce, cookie } = await createSocialState(provider, {
|
||||
from: safeRedirectPath(url.searchParams.get("from")),
|
||||
remember: url.searchParams.get("remember") !== "0",
|
||||
});
|
||||
const res = NextResponse.redirect(authorizeUrl(provider, url.origin, nonce));
|
||||
res.cookies.set(SOCIAL_STATE_COOKIE, cookie, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
// Lax: must survive the top-level redirect back from the provider.
|
||||
sameSite: "lax",
|
||||
path: SOCIAL_STATE_PATH,
|
||||
maxAge: SOCIAL_STATE_TTL_SECONDS,
|
||||
});
|
||||
return res;
|
||||
}
|
||||
Reference in New Issue
Block a user