Create the Login API

This commit is contained in:
2024-05-20 04:14:16 +04:00
parent 2d477644fb
commit 851fd9c051
2 changed files with 79 additions and 0 deletions
+72
View File
@@ -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
}
}
}
+7
View File
@@ -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}