proj/Frontend/app/api/auth/[...nextauth]/route.ts
2026-01-21 09:52:33 +01:00

66 lines
2.2 KiB
TypeScript

import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
import { type User } from "@/lib/types"
const handler = NextAuth({
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 {
const res = await fetch(`${process.env.API_URL || 'http://localhost:8080'}/api/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: credentials.email,
password: credentials.password
})
})
if (res.ok) {
const user = await res.json()
// Attach basic auth token to user object temporarily to pass to jwt callback
user.authHeader = "Basic " + btoa(`${credentials.email}:${credentials.password}`)
return user
}
return null
} catch (e) {
console.error(e)
return null
}
}
})
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.user = user
// @ts-ignore
token.authHeader = user.authHeader
}
return token
},
async session({ session, token }) {
if (token.user) {
// @ts-ignore
session.user = token.user as User
// @ts-ignore
session.authHeader = token.authHeader as string
}
return session
}
},
pages: {
signIn: "/auth",
error: "/auth" // Redirect to custom auth page on error
}
})
export { handler as GET, handler as POST }