Create the Login API
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import CredentialsProvider from 'next-auth/providers/credentials'
|
||||
import {readMe, withToken} from '@directus/sdk'
|
||||
import {directusClient} from '@/lib/directus.js'
|
||||
|
||||
const apiUrl = process.env.DIRECTUS_API_URL
|
||||
const nextauthSecret = process.env.NEXTAUTH_SECRET
|
||||
|
||||
export const options = {
|
||||
providers: [
|
||||
CredentialsProvider({ // eslint-disable-line new-cap
|
||||
name: 'Credentials',
|
||||
credentials: {
|
||||
email: {},
|
||||
password: {}
|
||||
},
|
||||
async authorize(credentials) {
|
||||
const res = await fetch(`${apiUrl}/auth/login`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(credentials),
|
||||
headers: {'Content-Type': 'application/json'}
|
||||
})
|
||||
|
||||
const user = await res.json()
|
||||
|
||||
if (!res.ok && user) {
|
||||
throw new Error('E-mail ou mot de passe incorrect')
|
||||
}
|
||||
|
||||
if (res.ok && user) {
|
||||
return user
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
})
|
||||
],
|
||||
secret: nextauthSecret,
|
||||
pages: {
|
||||
signIn: '/login'
|
||||
},
|
||||
callbacks: {
|
||||
async jwt({
|
||||
token,
|
||||
user,
|
||||
account
|
||||
}) {
|
||||
if (account && user) {
|
||||
const userData = await directusClient.request(
|
||||
withToken(
|
||||
user.data.access_token,
|
||||
readMe({
|
||||
fields: ['id', 'first_name']
|
||||
})
|
||||
)
|
||||
)
|
||||
return {
|
||||
...token,
|
||||
accessToken: user.data.access_token,
|
||||
refreshToken: user.data.refresh_token,
|
||||
user: userData
|
||||
}
|
||||
}
|
||||
|
||||
return token
|
||||
},
|
||||
async session({session, token}) {
|
||||
session.user.acessToken = token.accessToken
|
||||
session.user.rereshToken = token.refreshToken
|
||||
return session
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/* eslint-disable new-cap */
|
||||
import NextAuth from 'next-auth'
|
||||
import {options} from './options.js'
|
||||
|
||||
const handler = NextAuth(options)
|
||||
|
||||
export {handler as GET, handler as POST}
|
||||
Reference in New Issue
Block a user