Verbessere OAuth-Konfiguration mit zentraler Callback-URL

- Füge zentralen API-Konfigurationsmodul mit OAUTH_CALLBACK_URL hinzu
- Verwende konstante OAUTH_CALLBACK_URL in allen OAuth-Komponenten
- Vereinfache Code durch Entfernung von doppelter URL-Konstruktion
- Verbessere Logging für OAuth-Debugging
- Stelle Konsistenz zwischen API-Anfragen und OAuth-Validierung sicher

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Till Tomczak 2025-04-01 14:06:29 +02:00
parent a7760a12ce
commit 290d5b0ff2
4 changed files with 27 additions and 31 deletions

View File

@ -1,5 +1,6 @@
import { lucia } from "@/server/auth"; import { lucia } from "@/server/auth";
import { type GitHubUserResult, github } from "@/server/auth/oauth"; import { type GitHubUserResult, github } from "@/server/auth/oauth";
import { OAUTH_CALLBACK_URL } from "@/utils/api-config";
import { db } from "@/server/db"; import { db } from "@/server/db";
import { users } from "@/server/db/schema"; import { users } from "@/server/db/schema";
import { OAuth2RequestError } from "arctic"; import { OAuth2RequestError } from "arctic";
@ -34,11 +35,11 @@ export async function GET(request: Request): Promise<Response> {
} }
try { try {
// Explizit die redirect_uri übergeben, um Konsistenz zu gewährleisten // Verwende die zentral definierte Callback-URL für konsistente Validierung
const callbackUrl = new URL("/auth/login/callback", process.env.NEXT_PUBLIC_FRONTEND_URL || "http://localhost:3000").toString(); const tokens = await github.validateAuthorizationCode(code, OAUTH_CALLBACK_URL);
// Übergabe der redirect_uri bei der Token-Validierung // Log zur Fehlersuche
const tokens = await github.validateAuthorizationCode(code, callbackUrl); console.log(`GitHub OAuth Token-Validierung mit Callback-URL: ${OAUTH_CALLBACK_URL}`);
const githubUserResponse = await fetch("https://git.i.mercedes-benz.com/api/v3/user", { const githubUserResponse = await fetch("https://git.i.mercedes-benz.com/api/v3/user", {
headers: { headers: {

View File

@ -1,4 +1,5 @@
import { github } from "@/server/auth/oauth"; import { github } from "@/server/auth/oauth";
import { OAUTH_CALLBACK_URL } from "@/utils/api-config";
import { generateState } from "arctic"; import { generateState } from "arctic";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
@ -7,12 +8,10 @@ export const dynamic = "force-dynamic";
export async function GET(): Promise<Response> { export async function GET(): Promise<Response> {
const state = generateState(); const state = generateState();
// Explizit die redirect_uri übergeben, um Konsistenz zu gewährleisten // Verwende die zentral definierte Callback-URL
const callbackUrl = new URL("/auth/login/callback", process.env.NEXT_PUBLIC_FRONTEND_URL || "http://localhost:3000").toString();
const url = await github.createAuthorizationURL(state, { const url = await github.createAuthorizationURL(state, {
scopes: ["user"], scopes: ["user"],
redirectURI: callbackUrl, redirectURI: OAUTH_CALLBACK_URL,
}); });
const ONE_HOUR = 60 * 60; const ONE_HOUR = 60 * 60;
@ -26,7 +25,7 @@ export async function GET(): Promise<Response> {
// Log zur Fehlersuche // Log zur Fehlersuche
console.log(`GitHub OAuth redirect zu: ${url.toString()}`); console.log(`GitHub OAuth redirect zu: ${url.toString()}`);
console.log(`Verwendete Callback-URL: ${callbackUrl}`); console.log(`Verwendete Callback-URL: ${OAUTH_CALLBACK_URL}`);
return Response.redirect(url); return Response.redirect(url);
} }

View File

@ -1,30 +1,14 @@
import { GitHub } from "arctic"; import { GitHub } from "arctic";
import { FRONTEND_URL, OAUTH_CALLBACK_URL } from "@/utils/api-config";
// Bestimme die Callback-URL basierend auf der NEXT_PUBLIC_API_URL für das Backend // Bestimme die Callback-URL basierend auf der Frontend-URL
// und dem Standardport 3000 für das Frontend
const getCallbackUrl = () => { const getCallbackUrl = () => {
// Extrahiere die Basis-URL (Hostname) aus der Backend-URL, falls vorhanden console.log("Frontend URL:", FRONTEND_URL);
let baseUrl = "http://localhost:3000"; console.log("Verwende OAuth Callback URL:", OAUTH_CALLBACK_URL);
return OAUTH_CALLBACK_URL;
try {
const apiUrlEnv = process.env.NEXT_PUBLIC_API_URL;
if (apiUrlEnv) {
// Wenn wir eine Backend-URL haben, extrahieren wir nur den Hostname-Teil für das Frontend
const apiUrl = new URL(apiUrlEnv);
const hostname = apiUrl.hostname;
// Verwende den Hostname, aber mit Frontend-Port 3000
baseUrl = `http://${hostname}:3000`;
}
} catch (error) {
console.error("Fehler beim Parsen der API-URL:", error);
// Fallback auf localhost
}
return `${baseUrl}/auth/login/callback`;
}; };
// Erstelle GitHub OAuth-Client mit expliziter Redirect-URI
export const github = new GitHub( export const github = new GitHub(
process.env.OAUTH_CLIENT_ID as string, process.env.OAUTH_CLIENT_ID as string,
process.env.OAUTH_CLIENT_SECRET as string, process.env.OAUTH_CLIENT_SECRET as string,

View File

@ -1,9 +1,21 @@
// Basis-URL für Backend-API // Basis-URL für Backend-API
export const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://192.168.0.105:5000"; export const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://192.168.0.105:5000";
// Frontendurl für Callbacks
export const FRONTEND_URL = process.env.NEXT_PUBLIC_FRONTEND_URL || "http://localhost:3000";
// OAuth Callback URL
export const OAUTH_CALLBACK_URL = `${FRONTEND_URL}/auth/login/callback`;
// Endpunkte für die verschiedenen Ressourcen // Endpunkte für die verschiedenen Ressourcen
export const API_ENDPOINTS = { export const API_ENDPOINTS = {
PRINTERS: `${API_BASE_URL}/api/printers`, PRINTERS: `${API_BASE_URL}/api/printers`,
JOBS: `${API_BASE_URL}/api/jobs`, JOBS: `${API_BASE_URL}/api/jobs`,
USERS: `${API_BASE_URL}/api/users`, USERS: `${API_BASE_URL}/api/users`,
// OAuth-spezifische Endpunkte
AUTH: {
LOGIN: `${API_BASE_URL}/api/auth/login`,
CALLBACK: `${API_BASE_URL}/api/auth/callback`,
}
}; };