Add authentication system with next-auth (CredentialsProvider + JWT)
- Login page with email/password - Auth middleware (proxy) protecting all routes - Seed endpoint for admin user creation (admin@optiquestock.com / admin123) - Session provider wrapping root layout - User info + logout button in header - Updated POS sales route to track authenticated user
This commit is contained in:
58
src/lib/auth.ts
Normal file
58
src/lib/auth.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { NextAuthOptions } from 'next-auth'
|
||||
import CredentialsProvider from 'next-auth/providers/credentials'
|
||||
import bcrypt from 'bcryptjs'
|
||||
import { db } from './db'
|
||||
|
||||
export const authOptions: NextAuthOptions = {
|
||||
providers: [
|
||||
CredentialsProvider({
|
||||
name: 'credentials',
|
||||
credentials: {
|
||||
email: { label: 'Email', type: 'email' },
|
||||
password: { label: 'Mot de passe', type: 'password' },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
if (!credentials?.email || !credentials?.password) return null
|
||||
|
||||
const employe = await db.employe.findUnique({
|
||||
where: { email: credentials.email },
|
||||
})
|
||||
|
||||
if (!employe || !employe.actif) return null
|
||||
|
||||
const isValid = await bcrypt.compare(credentials.password, employe.motDePasse)
|
||||
if (!isValid) return null
|
||||
|
||||
return {
|
||||
id: employe.id,
|
||||
email: employe.email,
|
||||
name: `${employe.prenom} ${employe.nom}`,
|
||||
role: employe.role,
|
||||
}
|
||||
},
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
async jwt({ token, user }) {
|
||||
if (user) {
|
||||
token.id = user.id
|
||||
token.role = (user as any).role
|
||||
}
|
||||
return token
|
||||
},
|
||||
async session({ session, token }) {
|
||||
if (session.user) {
|
||||
(session.user as any).id = token.id
|
||||
(session.user as any).role = token.role
|
||||
}
|
||||
return session
|
||||
},
|
||||
},
|
||||
pages: {
|
||||
signIn: '/login',
|
||||
},
|
||||
session: {
|
||||
strategy: 'jwt',
|
||||
},
|
||||
secret: process.env.NEXTAUTH_SECRET,
|
||||
}
|
||||
Reference in New Issue
Block a user