change our current auth system for NextAuth.js (now Auth.js): This is th

This commit is contained in:
Leon Serfaty G
2025-07-17 11:34:27 +00:00
parent ba897d5c3e
commit 1d2b63ae70
11 changed files with 240 additions and 119 deletions
+2 -1
View File
@@ -1 +1,2 @@
GEMINI_API_KEY=
AUTH_SECRET="your-super-secret-auth-secret-change-me"
+17 -10
View File
@@ -1,18 +1,25 @@
import {NextResponse} from 'next/server'; import { auth } from '@/app/api/auth/[...nextauth]/route';
import type {NextRequest} from 'next/server'; import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) { export async function middleware(request: NextRequest) {
const session = request.cookies.get('session'); const session = await auth();
const { pathname } = request.nextUrl;
// Redirect to login if trying to access /admin without a session const isAuthPage = pathname === '/login';
if (request.nextUrl.pathname.startsWith('/admin') && !session) {
return NextResponse.redirect(new URL('/login', request.url)); if (isAuthPage) {
if (session) {
return NextResponse.redirect(new URL('/admin', request.url));
}
return null;
} }
// Redirect to admin if trying to access /login with a session if (!session && pathname.startsWith('/admin')) {
if (request.nextUrl.pathname === '/login' && session) { const signInUrl = new URL('/login', request.url);
return NextResponse.redirect(new URL('/admin', request.url)); signInUrl.searchParams.set('callbackUrl', pathname);
return NextResponse.redirect(signInUrl);
} }
return NextResponse.next(); return NextResponse.next();
+103
View File
@@ -43,6 +43,7 @@
"genkit": "^1.14.1", "genkit": "^1.14.1",
"lucide-react": "^0.475.0", "lucide-react": "^0.475.0",
"next": "15.3.3", "next": "15.3.3",
"next-auth": "^5.0.0-beta.19",
"nodemailer": "^6.9.14", "nodemailer": "^6.9.14",
"patch-package": "^8.0.0", "patch-package": "^8.0.0",
"react": "^18.3.1", "react": "^18.3.1",
@@ -90,6 +91,35 @@
"zod": "^3.20.2" "zod": "^3.20.2"
} }
}, },
"node_modules/@auth/core": {
"version": "0.40.0",
"resolved": "https://registry.npmjs.org/@auth/core/-/core-0.40.0.tgz",
"integrity": "sha512-n53uJE0RH5SqZ7N1xZoMKekbHfQgjd0sAEyUbE+IYJnmuQkbvuZnXItCU7d+i7Fj8VGOgqvNO7Mw4YfBTlZeQw==",
"license": "ISC",
"dependencies": {
"@panva/hkdf": "^1.2.1",
"jose": "^6.0.6",
"oauth4webapi": "^3.3.0",
"preact": "10.24.3",
"preact-render-to-string": "6.5.11"
},
"peerDependencies": {
"@simplewebauthn/browser": "^9.0.1",
"@simplewebauthn/server": "^9.0.2",
"nodemailer": "^6.8.0"
},
"peerDependenciesMeta": {
"@simplewebauthn/browser": {
"optional": true
},
"@simplewebauthn/server": {
"optional": true
},
"nodemailer": {
"optional": true
}
}
},
"node_modules/@babel/runtime": { "node_modules/@babel/runtime": {
"version": "7.26.9", "version": "7.26.9",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.9.tgz", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.9.tgz",
@@ -2671,6 +2701,15 @@
"node": ">=14" "node": ">=14"
} }
}, },
"node_modules/@panva/hkdf": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@panva/hkdf/-/hkdf-1.2.1.tgz",
"integrity": "sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/@pkgjs/parseargs": { "node_modules/@pkgjs/parseargs": {
"version": "0.11.0", "version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
@@ -7268,6 +7307,15 @@
"jiti": "bin/jiti.js" "jiti": "bin/jiti.js"
} }
}, },
"node_modules/jose": {
"version": "6.0.12",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.0.12.tgz",
"integrity": "sha512-T8xypXs8CpmiIi78k0E+Lk7T2zlK4zDyg+o1CZ4AkOHgDg98ogdP2BeZ61lTFKFyoEwJ9RgAgN+SdM3iPgNonQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/js-tokens": { "node_modules/js-tokens": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -7811,6 +7859,33 @@
} }
} }
}, },
"node_modules/next-auth": {
"version": "5.0.0-beta.29",
"resolved": "https://registry.npmjs.org/next-auth/-/next-auth-5.0.0-beta.29.tgz",
"integrity": "sha512-Ukpnuk3NMc/LiOl32njZPySk7pABEzbjhMUFd5/n10I0ZNC7NCuVv8IY2JgbDek2t/PUOifQEoUiOOTLy4os5A==",
"license": "ISC",
"dependencies": {
"@auth/core": "0.40.0"
},
"peerDependencies": {
"@simplewebauthn/browser": "^9.0.1",
"@simplewebauthn/server": "^9.0.2",
"next": "^14.0.0-0 || ^15.0.0-0",
"nodemailer": "^6.6.5",
"react": "^18.2.0 || ^19.0.0-0"
},
"peerDependenciesMeta": {
"@simplewebauthn/browser": {
"optional": true
},
"@simplewebauthn/server": {
"optional": true
},
"nodemailer": {
"optional": true
}
}
},
"node_modules/next/node_modules/postcss": { "node_modules/next/node_modules/postcss": {
"version": "8.4.31", "version": "8.4.31",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz",
@@ -7902,6 +7977,15 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/oauth4webapi": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.6.0.tgz",
"integrity": "sha512-OwXPTXjKPOldTpAa19oksrX9TYHA0rt+VcUFTkJ7QKwgmevPpNm9Cn5vFZUtIo96FiU6AfPuUUGzoXqgOzibWg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/object-assign": { "node_modules/object-assign": {
"version": "4.1.1", "version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@@ -8359,6 +8443,25 @@
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==" "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ=="
}, },
"node_modules/preact": {
"version": "10.24.3",
"resolved": "https://registry.npmjs.org/preact/-/preact-10.24.3.tgz",
"integrity": "sha512-Z2dPnBnMUfyQfSQ+GBdsGa16hz35YmLmtTLhM169uW944hYL6xzTYkJjC07j+Wosz733pMWx0fgON3JNw1jJQA==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/preact"
}
},
"node_modules/preact-render-to-string": {
"version": "6.5.11",
"resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-6.5.11.tgz",
"integrity": "sha512-ubnauqoGczeGISiOh6RjX0/cdaF8v/oDXIjO85XALCQjwQP+SB4RDXXtvZ6yTYSjG+PC1QRP2AhPgCEsM2EvUw==",
"license": "MIT",
"peerDependencies": {
"preact": ">=10"
}
},
"node_modules/prebuild-install": { "node_modules/prebuild-install": {
"version": "7.1.3", "version": "7.1.3",
"resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
+1
View File
@@ -48,6 +48,7 @@
"genkit": "^1.14.1", "genkit": "^1.14.1",
"lucide-react": "^0.475.0", "lucide-react": "^0.475.0",
"next": "15.3.3", "next": "15.3.3",
"next-auth": "^5.0.0-beta.19",
"nodemailer": "^6.9.14", "nodemailer": "^6.9.14",
"patch-package": "^8.0.0", "patch-package": "^8.0.0",
"react": "^18.3.1", "react": "^18.3.1",
+10 -9
View File
@@ -17,7 +17,7 @@ import {
SidebarFooter, SidebarFooter,
} from '@/components/ui/sidebar'; } from '@/components/ui/sidebar';
import { LayoutDashboard, LogOut, Settings, Mail, User as UserIcon } from 'lucide-react'; import { LayoutDashboard, LogOut, Settings, Mail, User as UserIcon } from 'lucide-react';
import { signOut, getSession } from '@/lib/auth'; import { signOut } from '@/lib/auth';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { import {
DropdownMenu, DropdownMenu,
@@ -28,17 +28,18 @@ import {
DropdownMenuTrigger, DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'; } from '@/components/ui/dropdown-menu';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import type { User } from '@/lib/types'; import { auth } from '@/app/api/auth/[...nextauth]/route';
export default async function AdminLayout({ export default async function AdminLayout({
children, children,
}: { }: {
children: React.ReactNode; children: React.ReactNode;
}) { }) {
const session = (await getSession()) as User | null; const session = await auth();
const userInitials = session?.name const user = session?.user;
? session.name
const userInitials = user?.name
? user.name
.split(' ') .split(' ')
.map((n) => n[0]) .map((n) => n[0])
.join('') .join('')
@@ -108,14 +109,14 @@ export default async function AdminLayout({
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<Button variant="secondary" size="icon" className="rounded-full"> <Button variant="secondary" size="icon" className="rounded-full">
<Avatar> <Avatar>
<AvatarImage src={`https://placehold.co/100x100.png`} alt={session?.name ?? ''} /> <AvatarImage src={`https://placehold.co/100x100.png`} alt={user?.name ?? ''} />
<AvatarFallback>{userInitials}</AvatarFallback> <AvatarFallback>{userInitials}</AvatarFallback>
</Avatar> </Avatar>
<span className="sr-only">Toggle user menu</span> <span className="sr-only">Toggle user menu</span>
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end"> <DropdownMenuContent align="end">
<DropdownMenuLabel>My Account</DropdownMenuLabel> <DropdownMenuLabel>{user?.name}</DropdownMenuLabel>
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<DropdownMenuItem asChild> <DropdownMenuItem asChild>
<Link href="/admin/settings/user">Settings</Link> <Link href="/admin/settings/user">Settings</Link>
@@ -123,7 +124,7 @@ export default async function AdminLayout({
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<form action={signOut} className="w-full"> <form action={signOut} className="w-full">
<DropdownMenuItem asChild> <DropdownMenuItem asChild>
<button type="submit" className="w-full"> <button type="submit" className="w-full text-left">
Sign Out Sign Out
</button> </button>
</DropdownMenuItem> </DropdownMenuItem>
-1
View File
@@ -18,7 +18,6 @@ import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { useEffect, useTransition } from "react"; import { useEffect, useTransition } from "react";
import { getUser, updateUser } from "@/lib/actions/user"; import { getUser, updateUser } from "@/lib/actions/user";
import { User } from "@/lib/types";
const userProfileSchema = z.object({ const userProfileSchema = z.object({
name: z.string().min(1, "Name is required"), name: z.string().min(1, "Name is required"),
+68
View File
@@ -0,0 +1,68 @@
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import db from '@/lib/db';
import type { User } from '@/lib/types';
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
providers: [
CredentialsProvider({
name: 'Credentials',
credentials: {
email: { label: 'Email', type: 'email' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials) {
if (!credentials?.email || !credentials.password) {
return null;
}
const email = credentials.email as string;
const password = credentials.password as string;
try {
const stmt = db.prepare('SELECT * FROM users WHERE email = ?');
const user = stmt.get(email) as User | undefined;
// In a real app, you would use a secure password hashing library like bcrypt
if (user && user.password === password) {
// Return a user object that NextAuth will use to create the session
return {
id: user.id.toString(),
name: user.name,
email: user.email,
};
} else {
// Invalid credentials
return null;
}
} catch (error) {
console.error('Database error during authorization:', error);
return null;
}
},
}),
],
callbacks: {
jwt({ token, user }) {
if (user) {
token.id = user.id;
}
return token;
},
session({ session, token }) {
if (session.user) {
session.user.id = token.id as string;
}
return session;
},
},
pages: {
signIn: '/login',
},
});
+12 -13
View File
@@ -4,15 +4,14 @@ import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { signIn, getSession } from '@/lib/auth'; import { signIn } from '@/app/api/auth/[...nextauth]/route';
import { redirect } from 'next/navigation';
async function handleSignIn(formData: FormData) {
'use server';
await signIn('credentials', formData);
}
export default async function LoginPage() { export default async function LoginPage() {
const session = await getSession();
if (session) {
redirect('/admin');
}
return ( return (
<div className="flex min-h-screen items-center justify-center bg-background"> <div className="flex min-h-screen items-center justify-center bg-background">
<Card className="w-full max-w-sm"> <Card className="w-full max-w-sm">
@@ -21,7 +20,7 @@ export default async function LoginPage() {
<CardDescription>Enter your credentials to access the dashboard.</CardDescription> <CardDescription>Enter your credentials to access the dashboard.</CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<form action={signIn} className="grid gap-4"> <form action={handleSignIn} className="grid gap-4">
<div className="grid gap-2"> <div className="grid gap-2">
<Label htmlFor="email">Email</Label> <Label htmlFor="email">Email</Label>
<Input <Input
@@ -35,11 +34,11 @@ export default async function LoginPage() {
</div> </div>
<div className="grid gap-2"> <div className="grid gap-2">
<Label htmlFor="password">Password</Label> <Label htmlFor="password">Password</Label>
<Input <Input
id="password" id="password"
type="password" type="password"
name="password" name="password"
required required
defaultValue="password" defaultValue="password"
/> />
</div> </div>
+12 -11
View File
@@ -2,9 +2,9 @@
'use server'; 'use server';
import db from '@/lib/db'; import db from '@/lib/db';
import { User } from '@/lib/types'; import type { User } from '@/lib/types';
import { z } from 'zod'; import { z } from 'zod';
import { getSession } from '../auth'; import { auth } from '@/app/api/auth/[...nextauth]/route';
const UserUpdateSchema = z.object({ const UserUpdateSchema = z.object({
name: z.string().min(1, 'Name is required'), name: z.string().min(1, 'Name is required'),
@@ -12,15 +12,16 @@ const UserUpdateSchema = z.object({
password: z.string().optional(), password: z.string().optional(),
}); });
export async function getUser(): Promise<User | null> { export async function getUser(): Promise<(User & { id: string }) | null> {
const session = await getSession(); const session = await auth();
if (!session?.userId) { if (!session?.user?.id) {
return null; return null;
} }
try { try {
const stmt = db.prepare('SELECT id, name, email FROM users WHERE id = ?'); const stmt = db.prepare('SELECT id, name, email FROM users WHERE id = ?');
const user = stmt.get(session.userId) as User | undefined; const user = stmt.get(session.user.id) as User | undefined;
return user ?? null; if (!user) return null;
return { ...user, id: user.id.toString() };
} catch (error) { } catch (error) {
console.error('Failed to get user:', error); console.error('Failed to get user:', error);
return null; return null;
@@ -30,8 +31,8 @@ export async function getUser(): Promise<User | null> {
export async function updateUser( export async function updateUser(
data: z.infer<typeof UserUpdateSchema> data: z.infer<typeof UserUpdateSchema>
): Promise<{ success: boolean; error?: string }> { ): Promise<{ success: boolean; error?: string }> {
const session = await getSession(); const session = await auth();
if (!session?.userId) { if (!session?.user?.id) {
return { success: false, error: 'Not authenticated. Please log in again.' }; return { success: false, error: 'Not authenticated. Please log in again.' };
} }
@@ -50,10 +51,10 @@ export async function updateUser(
const stmt = db.prepare( const stmt = db.prepare(
'UPDATE users SET name = ?, email = ?, password = ? WHERE id = ?' 'UPDATE users SET name = ?, email = ?, password = ? WHERE id = ?'
); );
stmt.run(name, email, password, session.userId); stmt.run(name, email, password, session.user.id);
} else { } else {
const stmt = db.prepare('UPDATE users SET name = ?, email = ? WHERE id = ?'); const stmt = db.prepare('UPDATE users SET name = ?, email = ? WHERE id = ?');
stmt.run(name, email, session.userId); stmt.run(name, email, session.user.id);
} }
return { success: true }; return { success: true };
} catch (error: any) { } catch (error: any) {
+2 -74
View File
@@ -1,79 +1,7 @@
'use server'; 'use server';
import { signOut as nextAuthSignOut } from '@/app/api/auth/[...nextauth]/route';
import { redirect } from 'next/navigation';
import { cookies } from 'next/headers';
import db from './db';
import type { User } from './types';
export async function signIn(formData: FormData) {
const email = formData.get('email');
const password = formData.get('password');
if (typeof email !== 'string' || typeof password !== 'string') {
// Handle case where form data is missing or not strings
redirect('/login?error=Invalid%20input');
return;
}
try {
const stmt = db.prepare('SELECT * FROM users WHERE email = ?');
const user = stmt.get(email) as User | undefined;
// In a real app, you would use a secure password hashing library like bcrypt
// For this example, we'll compare plain text passwords.
if (user && user.password === password) {
const sessionData = {
isLoggedIn: true,
userId: user.id,
email: user.email,
name: user.name,
};
// Set the session cookie
cookies().set('session', JSON.stringify(sessionData), {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60 * 24 * 7, // One week
path: '/',
});
redirect('/admin');
} else {
// Failed login
redirect('/login?error=Invalid%20credentials');
}
} catch (error) {
console.error('Failed to sign in:', error);
redirect('/login?error=Database%20error');
}
}
export async function signOut() { export async function signOut() {
cookies().delete('session'); await nextAuthSignOut({ redirectTo: '/login' });
redirect('/login');
}
export async function getSession() {
const cookieStore = cookies();
const sessionCookie = cookieStore.get('session');
if (!sessionCookie?.value) {
return null;
}
try {
const session = JSON.parse(sessionCookie.value);
// Basic validation to ensure the session object has expected properties
if (session && typeof session === 'object' && session.userId) {
return session as User & { isLoggedIn: boolean; userId: number };
}
return null;
} catch (error) {
console.error('Failed to parse session cookie:', error);
// If parsing fails, the cookie is invalid. Clear it.
cookieStore.delete('session');
return null;
}
} }
+13
View File
@@ -5,3 +5,16 @@ export interface User {
password?: string; // Should be handled securely, not sent to client password?: string; // Should be handled securely, not sent to client
name: string; name: string;
} }
// Augment the default NextAuth session and user types
declare module 'next-auth' {
interface Session {
user: {
id: string;
} & DefaultSession['user'];
}
interface User {
id: string;
}
}