From 851fd9c051a10e4aafd3d30e3a833140e4ee3a2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20FAMIBELLE-PRONZOLA?= Date: Mon, 20 May 2024 04:14:16 +0400 Subject: [PATCH] Create the Login API --- app/api/auth/[...nextauth]/options.js | 72 +++++++++++++++++++++++++++ app/api/auth/[...nextauth]/route.js | 7 +++ 2 files changed, 79 insertions(+) create mode 100644 app/api/auth/[...nextauth]/options.js create mode 100644 app/api/auth/[...nextauth]/route.js diff --git a/app/api/auth/[...nextauth]/options.js b/app/api/auth/[...nextauth]/options.js new file mode 100644 index 0000000..5c60e43 --- /dev/null +++ b/app/api/auth/[...nextauth]/options.js @@ -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 + } + } +} diff --git a/app/api/auth/[...nextauth]/route.js b/app/api/auth/[...nextauth]/route.js new file mode 100644 index 0000000..674146c --- /dev/null +++ b/app/api/auth/[...nextauth]/route.js @@ -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}