mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-08 03:50:21 +00:00
163 lines
4.6 KiB
JavaScript
163 lines
4.6 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";
|
|
import { queryOne } from "@/lib/db";
|
|
|
|
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;
|
|
}
|
|
|
|
// If teamId is not set on the token, query DB for the latest value.
|
|
if (!token.teamId) {
|
|
try {
|
|
const freshUser = await queryOne(
|
|
"SELECT team_id FROM users WHERE id = ?",
|
|
[token.id]
|
|
);
|
|
token.teamId = freshUser?.team_id;
|
|
} catch (error) {
|
|
console.error("Error refreshing teamId from database:", error);
|
|
}
|
|
}
|
|
|
|
// Ensure both sub and id exist for maximum compatibility
|
|
if (token.id && !token.sub) {
|
|
token.sub = token.id.toString();
|
|
}
|
|
if (token.sub && !token.id) {
|
|
token.id = parseInt(token.sub, 10);
|
|
}
|
|
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) {
|
|
console.error("No token provided");
|
|
return null;
|
|
}
|
|
|
|
console.log("Verifying token:", token.substring(0, 10) + "...");
|
|
|
|
const secret =
|
|
process.env.NEXTAUTH_SECRET ||
|
|
"your-fallback-secret-should-be-at-least-32-chars";
|
|
|
|
const decoded = jwt.verify(token, secret);
|
|
|
|
// Validate that we have the minimum required fields
|
|
if (!decoded.sub && !decoded.id) {
|
|
console.error("Token missing required user identifier");
|
|
return null;
|
|
}
|
|
|
|
// Log successful token verification with user ID
|
|
console.log(
|
|
"Token verified successfully for user:",
|
|
decoded.sub || decoded.id
|
|
);
|
|
|
|
return decoded;
|
|
} catch (error) {
|
|
// Provide more detailed error logs
|
|
if (error.name === "TokenExpiredError") {
|
|
console.error("Token expired at:", error.expiredAt);
|
|
} else if (error.name === "JsonWebTokenError") {
|
|
console.error("Invalid token:", error.message);
|
|
} else {
|
|
console.error("Token verification error:", error.message);
|
|
}
|
|
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";
|