change our current auth system for NextAuth.js (now Auth.js): This is th
This commit is contained in:
@@ -17,7 +17,7 @@ import {
|
||||
SidebarFooter,
|
||||
} from '@/components/ui/sidebar';
|
||||
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 {
|
||||
DropdownMenu,
|
||||
@@ -28,17 +28,18 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
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({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const session = (await getSession()) as User | null;
|
||||
const userInitials = session?.name
|
||||
? session.name
|
||||
const session = await auth();
|
||||
const user = session?.user;
|
||||
|
||||
const userInitials = user?.name
|
||||
? user.name
|
||||
.split(' ')
|
||||
.map((n) => n[0])
|
||||
.join('')
|
||||
@@ -108,14 +109,14 @@ export default async function AdminLayout({
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="secondary" size="icon" className="rounded-full">
|
||||
<Avatar>
|
||||
<AvatarImage src={`https://placehold.co/100x100.png`} alt={session?.name ?? ''} />
|
||||
<AvatarImage src={`https://placehold.co/100x100.png`} alt={user?.name ?? ''} />
|
||||
<AvatarFallback>{userInitials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="sr-only">Toggle user menu</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuLabel>My Account</DropdownMenuLabel>
|
||||
<DropdownMenuLabel>{user?.name}</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/admin/settings/user">Settings</Link>
|
||||
@@ -123,7 +124,7 @@ export default async function AdminLayout({
|
||||
<DropdownMenuSeparator />
|
||||
<form action={signOut} className="w-full">
|
||||
<DropdownMenuItem asChild>
|
||||
<button type="submit" className="w-full">
|
||||
<button type="submit" className="w-full text-left">
|
||||
Sign Out
|
||||
</button>
|
||||
</DropdownMenuItem>
|
||||
|
||||
@@ -18,7 +18,6 @@ import { Label } from "@/components/ui/label";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { useEffect, useTransition } from "react";
|
||||
import { getUser, updateUser } from "@/lib/actions/user";
|
||||
import { User } from "@/lib/types";
|
||||
|
||||
const userProfileSchema = z.object({
|
||||
name: z.string().min(1, "Name is required"),
|
||||
|
||||
@@ -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
@@ -4,15 +4,14 @@ import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { signIn, getSession } from '@/lib/auth';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { signIn } from '@/app/api/auth/[...nextauth]/route';
|
||||
|
||||
async function handleSignIn(formData: FormData) {
|
||||
'use server';
|
||||
await signIn('credentials', formData);
|
||||
}
|
||||
|
||||
export default async function LoginPage() {
|
||||
const session = await getSession();
|
||||
if (session) {
|
||||
redirect('/admin');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-background">
|
||||
<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>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form action={signIn} className="grid gap-4">
|
||||
<form action={handleSignIn} className="grid gap-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
@@ -35,11 +34,11 @@ export default async function LoginPage() {
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
name="password"
|
||||
required
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
name="password"
|
||||
required
|
||||
defaultValue="password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
+12
-11
@@ -2,9 +2,9 @@
|
||||
'use server';
|
||||
|
||||
import db from '@/lib/db';
|
||||
import { User } from '@/lib/types';
|
||||
import type { User } from '@/lib/types';
|
||||
import { z } from 'zod';
|
||||
import { getSession } from '../auth';
|
||||
import { auth } from '@/app/api/auth/[...nextauth]/route';
|
||||
|
||||
const UserUpdateSchema = z.object({
|
||||
name: z.string().min(1, 'Name is required'),
|
||||
@@ -12,15 +12,16 @@ const UserUpdateSchema = z.object({
|
||||
password: z.string().optional(),
|
||||
});
|
||||
|
||||
export async function getUser(): Promise<User | null> {
|
||||
const session = await getSession();
|
||||
if (!session?.userId) {
|
||||
export async function getUser(): Promise<(User & { id: string }) | null> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const stmt = db.prepare('SELECT id, name, email FROM users WHERE id = ?');
|
||||
const user = stmt.get(session.userId) as User | undefined;
|
||||
return user ?? null;
|
||||
const user = stmt.get(session.user.id) as User | undefined;
|
||||
if (!user) return null;
|
||||
return { ...user, id: user.id.toString() };
|
||||
} catch (error) {
|
||||
console.error('Failed to get user:', error);
|
||||
return null;
|
||||
@@ -30,8 +31,8 @@ export async function getUser(): Promise<User | null> {
|
||||
export async function updateUser(
|
||||
data: z.infer<typeof UserUpdateSchema>
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
const session = await getSession();
|
||||
if (!session?.userId) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Not authenticated. Please log in again.' };
|
||||
}
|
||||
|
||||
@@ -50,10 +51,10 @@ export async function updateUser(
|
||||
const stmt = db.prepare(
|
||||
'UPDATE users SET name = ?, email = ?, password = ? WHERE id = ?'
|
||||
);
|
||||
stmt.run(name, email, password, session.userId);
|
||||
stmt.run(name, email, password, session.user.id);
|
||||
} else {
|
||||
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 };
|
||||
} catch (error: any) {
|
||||
|
||||
+2
-74
@@ -1,79 +1,7 @@
|
||||
|
||||
'use server';
|
||||
|
||||
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');
|
||||
}
|
||||
}
|
||||
import { signOut as nextAuthSignOut } from '@/app/api/auth/[...nextauth]/route';
|
||||
|
||||
export async function signOut() {
|
||||
cookies().delete('session');
|
||||
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;
|
||||
}
|
||||
await nextAuthSignOut({ redirectTo: '/login' });
|
||||
}
|
||||
|
||||
@@ -5,3 +5,16 @@ export interface User {
|
||||
password?: string; // Should be handled securely, not sent to client
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user