feat: NextAuth credentials + JWT 8h + rate limiting
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
import type { NextAuthOptions } from 'next-auth'
|
||||
import CredentialsProvider from 'next-auth/providers/credentials'
|
||||
import { compare } from 'bcryptjs'
|
||||
import { prisma } from './prisma'
|
||||
import { checkRateLimit, recordFailedAttempt, clearAttempts } from './rate-limit'
|
||||
|
||||
export const authOptions: NextAuthOptions = {
|
||||
session: {
|
||||
strategy: 'jwt',
|
||||
maxAge: 8 * 60 * 60, // 8 heures
|
||||
},
|
||||
pages: {
|
||||
signIn: '/login',
|
||||
},
|
||||
callbacks: {
|
||||
async jwt({ token, user }) {
|
||||
if (user) {
|
||||
token.role = (user as any).role
|
||||
token.id = user.id
|
||||
}
|
||||
return token
|
||||
},
|
||||
async session({ session, token }) {
|
||||
if (session.user) {
|
||||
(session.user as any).role = token.role
|
||||
;(session.user as any).id = token.id
|
||||
}
|
||||
return session
|
||||
},
|
||||
},
|
||||
providers: [
|
||||
CredentialsProvider({
|
||||
name: 'Credentials',
|
||||
credentials: {
|
||||
email: { label: 'Email', type: 'email' },
|
||||
password: { label: 'Mot de passe', type: 'password' },
|
||||
},
|
||||
async authorize(credentials, req) {
|
||||
if (!credentials?.email || !credentials?.password) return null
|
||||
|
||||
const ip =
|
||||
(req as any)?.headers?.['x-forwarded-for']?.split(',')[0]?.trim() ?? 'unknown'
|
||||
const key = `${ip}:${credentials.email}`
|
||||
|
||||
if (!checkRateLimit(key)) {
|
||||
throw new Error('RATE_LIMITED')
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: credentials.email },
|
||||
})
|
||||
|
||||
if (!user || !(await compare(credentials.password, user.password))) {
|
||||
recordFailedAttempt(key)
|
||||
return null
|
||||
}
|
||||
|
||||
clearAttempts(key)
|
||||
return { id: user.id, email: user.email, name: user.name, role: user.role }
|
||||
},
|
||||
}),
|
||||
],
|
||||
}
|
||||
Reference in New Issue
Block a user