mirror_match/lib/auth.ts
ilia 888ffef8e3 feat: Enable host trust for authentication and update example environment configuration
- Set AUTH_TRUST_HOST to true in env.example for improved security.
- Updated NextAuth configuration to trust the host during authentication.
2026-01-04 11:01:00 -05:00

80 lines
1.9 KiB
TypeScript

import NextAuth from "next-auth"
import Credentials from "next-auth/providers/credentials"
import { prisma } from "./prisma"
import bcrypt from "bcryptjs"
const nextAuthSecret = process.env.NEXTAUTH_SECRET
if (!nextAuthSecret) {
throw new Error("NEXTAUTH_SECRET is not set. Define it to enable authentication.")
}
export const { handlers, auth, signIn, signOut } = NextAuth({
trustHost: true,
providers: [
Credentials({
name: "Credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" }
},
async authorize(credentials) {
try {
if (!credentials?.email || !credentials?.password) {
return null
}
const email = credentials.email as string
const password = credentials.password as string
const user = await prisma.user.findUnique({
where: { email }
})
if (!user || !user.passwordHash) {
return null
}
const isValid = await bcrypt.compare(password, user.passwordHash)
if (!isValid) {
return null
}
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
}
} catch (err) {
console.error("Auth authorize error:", err)
return null
}
}
})
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id
token.role = (user as { role: string }).role
}
return token
},
async session({ session, token }) {
if (session.user) {
session.user.id = token.id as string
session.user.role = token.role as string
}
return session
}
},
pages: {
signIn: "/login",
},
session: {
strategy: "jwt",
},
secret: nextAuthSecret,
})