feat: integrate NextAuth.js for authentication, update database service to use better-sqlite3 adapter, and enhance header component with user session management

This commit is contained in:
Julien Froidefond
2025-11-27 13:08:09 +01:00
parent 68ef3731fa
commit 6a9bf88a65
15 changed files with 965 additions and 31 deletions

29
src/lib/auth.config.ts Normal file
View File

@@ -0,0 +1,29 @@
import type { NextAuthConfig } from 'next-auth';
export const authConfig: NextAuthConfig = {
pages: {
signIn: '/login',
},
callbacks: {
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user;
const isOnProtectedPage =
nextUrl.pathname.startsWith('/sessions') || nextUrl.pathname.startsWith('/api/sessions');
const isOnAuthPage =
nextUrl.pathname.startsWith('/login') || nextUrl.pathname.startsWith('/register');
if (isOnProtectedPage) {
if (isLoggedIn) return true;
return false; // Redirect to login
}
if (isOnAuthPage && isLoggedIn) {
return Response.redirect(new URL('/sessions', nextUrl));
}
return true;
},
},
providers: [], // Configured in auth.ts
};

62
src/lib/auth.ts Normal file
View File

@@ -0,0 +1,62 @@
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { compare } from 'bcryptjs';
import { prisma } from '@/services/database';
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
Credentials({
name: 'credentials',
credentials: {
email: { label: 'Email', type: 'email' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
return null;
}
const user = await prisma.user.findUnique({
where: { email: credentials.email as string },
});
if (!user) {
return null;
}
const isPasswordValid = await compare(credentials.password as string, user.password);
if (!isPasswordValid) {
return null;
}
return {
id: user.id,
email: user.email,
name: user.name,
};
},
}),
],
session: {
strategy: 'jwt',
},
pages: {
signIn: '/login',
},
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
}
return token;
},
async session({ session, token }) {
if (session.user) {
session.user.id = token.id as string;
}
return session;
},
},
});