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
+12 -11
View File
@@ -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
View File
@@ -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' });
}
+13
View File
@@ -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;
}
}