Files
fintrack/lib/auth.ts

93 lines
2.4 KiB
TypeScript

import { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { authService } from "@/services/auth.service";
// Get secret with fallback for development
const secret =
process.env.NEXTAUTH_SECRET || "dev-secret-key-change-in-production";
// Debug: log secret status (remove in production)
if (process.env.NODE_ENV === "development") {
console.log(
"🔐 NextAuth secret:",
process.env.NEXTAUTH_SECRET
? "✅ Loaded from .env.local"
: "⚠️ Using fallback"
);
}
if (!process.env.NEXTAUTH_SECRET && process.env.NODE_ENV === "production") {
throw new Error(
"NEXTAUTH_SECRET is required in production. Please set it in your environment variables."
);
}
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
password: { label: "Mot de passe", type: "password" },
},
async authorize(credentials) {
try {
if (!credentials?.password) {
return null;
}
const isValid = await authService.verifyPassword(
credentials.password
);
if (!isValid) {
return null;
}
// Return a user object (we don't need a real user, just authentication)
return {
id: "admin",
email: "admin@local",
};
} catch (error) {
console.error("Error in authorize:", error);
return null;
}
},
}),
],
pages: {
signIn: "/login",
},
session: {
strategy: "jwt",
maxAge: 24 * 60 * 60, // 24 hours
},
callbacks: {
async jwt({ token, user }) {
// On first sign in, set expiration time
if (user) {
token.id = user.id;
token.exp = Math.floor(Date.now() / 1000) + 24 * 60 * 60; // 24 hours from now
}
// Check if token has expired
if (token.exp && Date.now() >= token.exp * 1000) {
return { ...token, error: "TokenExpired" };
}
return token;
},
async session({ session, token }) {
// If token is expired, return null session
if (token.error === "TokenExpired") {
return null as unknown as typeof session;
}
if (session.user && token.id) {
session.user.id = token.id;
}
return session;
},
},
secret,
};