auth handling

This commit is contained in:
zramsay 2025-03-11 16:14:18 -04:00
parent 17818749ab
commit ed6148407b
3 changed files with 90 additions and 11 deletions

View File

@ -3,25 +3,42 @@ import GoogleProvider from "next-auth/providers/google";
// Check for required environment variables and environment
console.log("Next-Auth initializing with NODE_ENV:", process.env.NODE_ENV);
console.log("NEXTAUTH_URL:", process.env.NEXTAUTH_URL); // Log the actual URL
if (!process.env.NEXTAUTH_SECRET) {
console.error("Error: NEXTAUTH_SECRET environment variable is missing");
// Create safe versions of required variables with fallbacks
const nextAuthSecret = process.env.NEXTAUTH_SECRET ||
(process.env.NODE_ENV === 'production'
? undefined // In production, we want this to error if not set
: 'DEV_SECRET_DO_NOT_USE_IN_PRODUCTION');
const googleClientId = process.env.GOOGLE_CLIENT_ID || '';
const googleClientSecret = process.env.GOOGLE_CLIENT_SECRET || '';
// Perform validation checks with detailed logging
if (!nextAuthSecret) {
console.error("CRITICAL: NEXTAUTH_SECRET environment variable is missing");
} else {
console.log("NEXTAUTH_SECRET is set (value hidden)");
}
if (!process.env.GOOGLE_CLIENT_ID || !process.env.GOOGLE_CLIENT_SECRET) {
console.error("Error: Google OAuth credentials are missing");
if (!googleClientId || !googleClientSecret) {
console.error("Error: Google OAuth credentials are missing or incomplete");
if (!googleClientId) console.error("- GOOGLE_CLIENT_ID is missing");
if (!googleClientSecret) console.error("- GOOGLE_CLIENT_SECRET is missing");
} else {
console.log("Google OAuth credentials are properly configured");
}
if (!process.env.NEXTAUTH_URL) {
console.log("Warning: NEXTAUTH_URL not explicitly set, will use default");
if (!process.env.NEXTAUTH_URL && process.env.NODE_ENV === 'production') {
console.log("Warning: NEXTAUTH_URL not explicitly set in production, Next.js will use the Host header");
}
// Define auth options
const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID || '',
clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
clientId: googleClientId,
clientSecret: googleClientSecret,
}),
],
pages: {
@ -37,8 +54,13 @@ const authOptions = {
}
return session;
},
// Provide detailed logs for debugging
async signIn({ user, account, profile }) {
console.log(`User attempting to sign in: ${user.email}`);
return true;
}
},
secret: process.env.NEXTAUTH_SECRET,
secret: nextAuthSecret,
// Ensure cookies work in production
cookies: {
sessionToken: {
@ -53,7 +75,18 @@ const authOptions = {
}
}
},
debug: process.env.NODE_ENV !== 'production',
debug: true, // Enable debug mode to diagnose the issue
logger: {
error(code, ...message) {
console.error(`NextAuth Error [${code}]:`, ...message);
},
warn(code, ...message) {
console.warn(`NextAuth Warning [${code}]:`, ...message);
},
debug(code, ...message) {
console.log(`NextAuth Debug [${code}]:`, ...message);
}
}
};
// Create a handler with the auth options

23
src/app/api/debug/env/route.ts vendored Normal file
View File

@ -0,0 +1,23 @@
/**
* DEBUG ONLY: This endpoint returns information about the server environment.
* Should be disabled or removed in production.
*/
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
// Only show minimal safe information to avoid security issues
const envInfo = {
node_env: process.env.NODE_ENV,
is_production: process.env.NODE_ENV === 'production',
has_nextauth_url: !!process.env.NEXTAUTH_URL,
has_nextauth_secret: !!process.env.NEXTAUTH_SECRET,
has_google_client_id: !!process.env.GOOGLE_CLIENT_ID,
has_google_client_secret: !!process.env.GOOGLE_CLIENT_SECRET,
nextauth_url_hostname: process.env.NEXTAUTH_URL
? new URL(process.env.NEXTAUTH_URL).hostname
: null,
request_hostname: request.headers.get('host'),
};
return NextResponse.json(envInfo);
};

View File

@ -8,6 +8,7 @@ import Navigation from '../../components/Navigation';
export default function DebugPage() {
const { data: session, status } = useSession();
const [authData, setAuthData] = useState<any>(null);
const [serverEnv, setServerEnv] = useState<any>(null);
useEffect(() => {
const checkAuth = async () => {
@ -20,7 +21,22 @@ export default function DebugPage() {
}
};
const checkServerEnv = async () => {
try {
const res = await fetch('/api/debug/env');
if (res.ok) {
const data = await res.json();
setServerEnv(data);
} else {
console.error('Failed to fetch server environment:', res.statusText);
}
} catch (error) {
console.error('Error fetching server environment:', error);
}
};
checkAuth();
checkServerEnv();
}, []);
// Environment variables check (public variables only)
@ -63,12 +79,19 @@ export default function DebugPage() {
</div>
<div className="bg-gray-700 p-4 rounded-lg">
<h2 className="text-xl font-bold text-emerald-300 mb-2">Environment Variables</h2>
<h2 className="text-xl font-bold text-emerald-300 mb-2">Client Environment Variables</h2>
<pre className="bg-gray-900 p-4 rounded mt-2 overflow-auto max-h-60">
{JSON.stringify(envCheck, null, 2)}
</pre>
</div>
<div className="bg-gray-700 p-4 rounded-lg">
<h2 className="text-xl font-bold text-emerald-300 mb-2">Server Environment</h2>
<pre className="bg-gray-900 p-4 rounded mt-2 overflow-auto max-h-60">
{serverEnv ? JSON.stringify(serverEnv, null, 2) : "Loading server environment..."}
</pre>
</div>
<div className="bg-gray-700 p-4 rounded-lg flex flex-col space-y-4">
<h2 className="text-xl font-bold text-emerald-300 mb-2">Auth Actions</h2>
<div className="flex flex-wrap gap-4">