feat(02-01): extend proxy.ts with admin session guard, add login page
- Extend src/proxy.ts to guard /admin/* routes with getToken() JWT check
- /admin/login and /api/auth/* exempted from session guard (pass-through)
- Unauthenticated /admin/* requests redirect to /admin/login?callbackUrl=...
- /c/:path* client token validation logic preserved unchanged
- matcher updated: ["/admin/:path*", "/c/:path*"]
- Create src/app/admin/login/page.tsx: email+password form, signIn('credentials'), error on failure, redirect on success
- Fix: Next.js 16 requires export named 'proxy' not 'middleware'
- Fix: useSearchParams wrapped in Suspense boundary (Next.js App Router requirement)
This commit is contained in:
@@ -0,0 +1,90 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Suspense, useState } from "react";
|
||||||
|
import { signIn } from "next-auth/react";
|
||||||
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
|
||||||
|
function AdminLoginForm() {
|
||||||
|
const router = useRouter();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const callbackUrl = searchParams.get("callbackUrl") ?? "/admin";
|
||||||
|
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
const result = await signIn("credentials", {
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
redirect: false, // handle redirect manually to show errors
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result?.error) {
|
||||||
|
setError("Email o password non corretti.");
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
router.replace(callbackUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label htmlFor="email">Email</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
autoComplete="email"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label htmlFor="password">Password</Label>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
autoComplete="current-password"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{error && (
|
||||||
|
<p className="text-sm text-red-600">{error}</p>
|
||||||
|
)}
|
||||||
|
<Button type="submit" className="w-full" disabled={loading}>
|
||||||
|
{loading ? "Accesso in corso..." : "Accedi"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AdminLoginPage() {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||||
|
<Card className="w-full max-w-sm">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-xl">Admin — ClientHub</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Suspense fallback={<div className="text-sm text-gray-500">Caricamento...</div>}>
|
||||||
|
<AdminLoginForm />
|
||||||
|
</Suspense>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+39
-10
@@ -1,35 +1,64 @@
|
|||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { getToken } from "next-auth/jwt";
|
||||||
|
|
||||||
export async function proxy(request: NextRequest) {
|
export async function proxy(request: NextRequest) {
|
||||||
const pathname = request.nextUrl.pathname;
|
const pathname = request.nextUrl.pathname;
|
||||||
|
|
||||||
// Extract token from path: /c/[token]/...
|
// ── ADMIN GUARD ──────────────────────────────────────────────────────────
|
||||||
const tokenMatch = pathname.match(/^\/c\/([a-zA-Z0-9_-]+)/);
|
if (pathname.startsWith("/admin")) {
|
||||||
if (!tokenMatch) {
|
// Allow the login page and NextAuth API routes through without session check
|
||||||
return NextResponse.rewrite(new URL('/not-found', request.url));
|
if (
|
||||||
|
pathname === "/admin/login" ||
|
||||||
|
pathname.startsWith("/api/auth")
|
||||||
|
) {
|
||||||
|
return NextResponse.next();
|
||||||
}
|
}
|
||||||
|
|
||||||
const token = tokenMatch[1];
|
const token = await getToken({
|
||||||
|
req: request,
|
||||||
|
secret: process.env.NEXTAUTH_SECRET,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
const loginUrl = new URL("/admin/login", request.url);
|
||||||
|
loginUrl.searchParams.set("callbackUrl", pathname);
|
||||||
|
return NextResponse.redirect(loginUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── CLIENT TOKEN GUARD ───────────────────────────────────────────────────
|
||||||
|
if (pathname.startsWith("/c/")) {
|
||||||
|
const tokenMatch = pathname.match(/^\/c\/([a-zA-Z0-9_-]+)/);
|
||||||
|
if (!tokenMatch) {
|
||||||
|
return NextResponse.rewrite(new URL("/not-found", request.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
const clientToken = tokenMatch[1];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Call internal Node.js API route — Edge middleware cannot use postgres-js directly
|
// Call internal Node.js API route — Edge middleware cannot use postgres-js directly
|
||||||
// postgres-js requires Node.js net/tls which are unavailable in the Edge runtime
|
// postgres-js requires Node.js net/tls which are unavailable in the Edge runtime
|
||||||
const validateUrl = new URL(
|
const validateUrl = new URL(
|
||||||
`/api/internal/validate-token?token=${encodeURIComponent(token)}`,
|
`/api/internal/validate-token?token=${encodeURIComponent(clientToken)}`,
|
||||||
request.url
|
request.url
|
||||||
);
|
);
|
||||||
const res = await fetch(validateUrl.toString());
|
const res = await fetch(validateUrl.toString());
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
return NextResponse.rewrite(new URL('/not-found', request.url));
|
return NextResponse.rewrite(new URL("/not-found", request.url));
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.next();
|
return NextResponse.next();
|
||||||
} catch {
|
} catch {
|
||||||
return NextResponse.rewrite(new URL('/not-found', request.url));
|
return NextResponse.rewrite(new URL("/not-found", request.url));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.next();
|
||||||
}
|
}
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
matcher: ['/c/:path*'],
|
matcher: ["/admin/:path*", "/c/:path*"],
|
||||||
};
|
};
|
||||||
Reference in New Issue
Block a user