Files
peworkshop/app/api/auth/[...nextauth]/route.js
T
2025-03-14 23:50:25 +00:00

131 lines
3.7 KiB
JavaScript

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { validateCredentials } from "@/actions/auth";
import jwt from "jsonwebtoken";
import { cookies } from "next/headers";
const JWT_SECRET =
process.env.NEXTAUTH_SECRET ||
"your-fallback-secret-should-be-at-least-32-chars";
export const authOptions = {
providers: [
{
id: "credentials",
name: "Credentials",
type: "credentials",
credentials: {
username: { label: "Username", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
try {
if (!credentials?.username || !credentials?.password) {
console.log("Missing credentials");
return null;
}
const user = await validateCredentials(
credentials.username,
credentials.password
);
if (user) {
console.log("User authenticated:", user.username);
return user;
}
console.log("Invalid credentials for:", credentials.username);
return null;
} catch (error) {
console.error("Authentication error:", error);
return null;
}
},
},
],
session: {
strategy: "jwt",
maxAge: 30 * 24 * 60 * 60,
},
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
token.role = user.role;
token.username = user.username;
token.teamId = user.team_id || user.teamId;
}
return token;
},
async session({ session, token }) {
if (token) {
session.user = session.user || {};
session.user.id = token.id;
session.user.role = token.role;
session.user.username = token.username;
session.user.teamId = token.teamId;
}
return session;
},
async redirect({ baseUrl, session }) {
// Redirect admins to dashboard, users with a team to their team page,
// otherwise to team selection.
if (session?.user) {
if (session.user.role === "admin") {
return `${baseUrl}/admin/dashboard`;
}
if (session.user.teamId) {
return `${baseUrl}/team/${session.user.teamId}`;
}
}
return `${baseUrl}/team-selection`;
},
},
pages: {
signIn: "/login",
error: "/login?error=true",
},
debug: process.env.NODE_ENV === "development",
secret: JWT_SECRET,
};
export function createToken(payload) {
return jwt.sign(payload, JWT_SECRET, { expiresIn: "30d" });
}
export function verifyToken(token) {
try {
if (!token) return null;
const parts = token.split(".");
if (parts.length === 2) {
// Custom token verification
const [encodedData, signature] = parts;
const expectedSignature = Buffer.from(
`${encodedData}.${JWT_SECRET}`
).toString("base64");
if (signature !== expectedSignature) {
console.error("Signature mismatch");
return null;
}
const data = JSON.parse(
Buffer.from(encodedData, "base64").toString("utf-8")
);
if (data.exp && data.exp < Math.floor(Date.now() / 1000)) return null;
return data;
} else if (parts.length === 3) {
// Standard JWT verification
return jwt.verify(token, JWT_SECRET);
} else {
throw new Error("Invalid token format");
}
} catch (error) {
console.error("Token verification error:", error);
return null;
}
}
// Ensure that the NextAuth export is callable over interop
const NextAuthFn = NextAuth.default ? NextAuth.default : NextAuth;
const handler = NextAuthFn(authOptions);
export { handler as GET, handler as POST };
export const runtime = "nodejs";