Files
peworkshop/app/api/auth/[...nextauth]/route.js
T

187 lines
5.4 KiB
JavaScript

export const runtime = "nodejs";
// Remove problematic import of NextAuth
import { validateCredentials } from "@/actions/auth";
// Define hardcoded values for NextAuth
const NEXTAUTH_SECRET = "banana";
const NEXTAUTH_URL = "http://localhost:3000";
// Use hardcoded values instead of environment variables
console.log("Using NextAuth Secret: banana");
console.log(`Using NextAuth URL: ${NEXTAUTH_URL}`);
// Custom credentials provider function that doesn't rely on the import
const createCredentialsProvider = (options) => {
return {
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) return null;
const user = await validateCredentials(
credentials.username,
credentials.password
);
return user
? {
id: user.id,
username: user.username,
role: user.role,
teamId: user.teamId,
}
: null;
} catch (error) {
console.error("NextAuth authorize error:", error);
return null;
}
},
...options,
};
};
export const authOptions = {
debug: process.env.NODE_ENV === "development",
providers: [
// Using our custom provider creator instead of the imported module
createCredentialsProvider({}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
token.role = user.role;
token.username = user.username;
token.teamId = 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;
},
},
session: { strategy: "jwt", maxAge: 30 * 24 * 60 * 60 },
secret: NEXTAUTH_SECRET, // Use the hardcoded secret
url: NEXTAUTH_URL, // Use the hardcoded URL
};
// Create the handler functions directly without calling NextAuth function
export async function GET(request) {
// Implement the GET handler for auth
try {
// Extract the necessary info from the request
const { searchParams } = new URL(request.url);
const callbackUrl = searchParams.get("callbackUrl") || "/";
const error = searchParams.get("error") || "";
// For sign-in requests
if (searchParams.get("csrf")) {
// Generate a simple CSRF token using the secret
const csrfToken = Buffer.from(`${Date.now()}-${NEXTAUTH_SECRET}`).toString('base64');
return new Response(JSON.stringify({ csrfToken }), {
status: 200,
headers: {
"Content-Type": "application/json",
},
});
}
// For session requests
if (request.headers.get("x-auth-return-session")) {
// Return the session info - would need more implementation
return new Response(JSON.stringify({ user: null }), {
status: 200,
headers: {
"Content-Type": "application/json",
},
});
}
// Default response for GET - normally this would redirect to the sign-in page
return new Response(JSON.stringify({ url: "/login", error }), {
status: 200,
headers: {
"Content-Type": "application/json",
},
});
} catch (error) {
console.error("Auth GET error:", error);
return new Response(JSON.stringify({ error: "Internal server error" }), {
status: 500,
headers: {
"Content-Type": "application/json",
},
});
}
}
export async function POST(request) {
// Implement the POST handler for auth
try {
const body = await request.json();
const { username, password } = body;
// Validate the credentials
const user = await validateCredentials(username, password);
if (!user) {
return new Response(JSON.stringify({ error: "Invalid credentials" }), {
status: 401,
headers: {
"Content-Type": "application/json",
},
});
}
// Create a session token
const token = {
id: user.id,
username: user.username,
role: user.role,
teamId: user.teamId,
// Add timestamp for token expiration checks
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (30 * 24 * 60 * 60), // 30 days
};
// Create a simple JWT-like token by encoding and signing with our secret
const encodedToken = Buffer.from(JSON.stringify(token)).toString('base64');
const signature = Buffer.from(`${encodedToken}-${NEXTAUTH_SECRET}`).toString('base64');
const jwtToken = `${encodedToken}.${signature}`;
return new Response(
JSON.stringify({
user: token,
url: body.callbackUrl || "/dashboard",
}),
{
status: 200,
headers: {
"Content-Type": "application/json",
"Set-Cookie": `next-auth.session-token=${jwtToken}; Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000`,
},
}
);
} catch (error) {
console.error("Auth POST error:", error);
return new Response(JSON.stringify({ error: "Internal server error" }), {
status: 500,
headers: {
"Content-Type": "application/json",
},
});
}
}