Files
OpticZ/src/lib/auth.ts

61 lines
1.5 KiB
TypeScript

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.userId = user.id
token.role = (user as any).role
}
return token
},
async session({ session, token }) {
if (session.user) {
Object.assign(session.user, {
id: token.userId,
role: token.role,
})
}
return session
},
},
pages: {
signIn: '/login',
},
session: {
strategy: 'jwt',
},
secret: process.env.NEXTAUTH_SECRET,
}