feat: add authentication support and user model
- Updated `env.example` to include NextAuth configuration for authentication. - Added `next-auth` dependency to manage user sessions. - Introduced `User` model in Prisma schema with fields for user details and password hashing. - Integrated `AuthProvider` in layout for session management across the app. - Enhanced `Header` component with `AuthButton` for user authentication controls.
This commit is contained in:
72
src/lib/auth.ts
Normal file
72
src/lib/auth.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { NextAuthOptions } from "next-auth"
|
||||
import CredentialsProvider from "next-auth/providers/credentials"
|
||||
import { usersService } from "@/services/users"
|
||||
|
||||
export const authOptions: NextAuthOptions = {
|
||||
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
|
||||
}
|
||||
|
||||
try {
|
||||
// Chercher l'utilisateur dans la base de données
|
||||
const user = await usersService.getUserByEmail(credentials.email)
|
||||
|
||||
if (!user) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Vérifier le mot de passe
|
||||
const isValidPassword = await usersService.verifyPassword(
|
||||
credentials.password,
|
||||
user.password
|
||||
)
|
||||
|
||||
if (!isValidPassword) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name || `${user.firstName || ''} ${user.lastName || ''}`.trim() || user.email,
|
||||
firstName: user.firstName || undefined,
|
||||
lastName: user.lastName || undefined,
|
||||
avatar: user.avatar || undefined,
|
||||
role: user.role,
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Auth error:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
})
|
||||
],
|
||||
pages: {
|
||||
signIn: "/login",
|
||||
},
|
||||
session: {
|
||||
strategy: "jwt",
|
||||
},
|
||||
callbacks: {
|
||||
async jwt({ token, user }) {
|
||||
if (user) {
|
||||
token.id = user.id
|
||||
}
|
||||
return token
|
||||
},
|
||||
async session({ session, token }) {
|
||||
if (token && session.user) {
|
||||
session.user.id = token.id as string
|
||||
}
|
||||
return session
|
||||
},
|
||||
},
|
||||
}
|
||||
Reference in New Issue
Block a user