From f6cf3a0af5a35bb999cae441222235edba9964f6 Mon Sep 17 00:00:00 2001 From: "riho.takagi" Date: Fri, 6 Dec 2024 17:07:40 -0500 Subject: [PATCH] Changed to not cache tokens in cookies --- booking-app/app/api/nyu/auth/token/route.ts | 66 ------------------- .../app/api/nyu/identity/[uniqueId]/route.ts | 24 ++----- booking-app/lib/server/nyuApiAuth.ts | 64 +++++++++++------- 3 files changed, 45 insertions(+), 109 deletions(-) delete mode 100644 booking-app/app/api/nyu/auth/token/route.ts diff --git a/booking-app/app/api/nyu/auth/token/route.ts b/booking-app/app/api/nyu/auth/token/route.ts deleted file mode 100644 index e4affebf..00000000 --- a/booking-app/app/api/nyu/auth/token/route.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { TokenResponse } from "@/components/src/types"; -import { NYUTokenManager } from "@/lib/server/nyuTokenCache"; -import { Buffer } from "buffer"; -import { NextResponse } from "next/server"; - -const NYU_AUTH_URL = "https://auth.nyu.edu/oauth2/token"; - -function getBasicAuthHeader(): string { - const clientId = process.env.NYU_API_CLIENT_ID; - const clientSecret = process.env.NYU_API_CLIENT_SECRET; - - if (!clientId || !clientSecret) { - throw new Error("NYU credentials not configured"); - } - - const credentials = `${clientId}:${clientSecret}`; - return `Basic ${Buffer.from(credentials).toString("base64")}`; -} - -export async function GET() { - try { - const tokenManager = NYUTokenManager.getInstance(); - let tokenCache = await tokenManager.getToken(); - if (!tokenCache) { - const username = process.env.NYU_API_USER_NAME; - const password = process.env.NYU_API_PASSWORD; - - const params = new URLSearchParams({ - grant_type: "password", - username, - password, - scope: "openid", - }); - - const response = await fetch(NYU_AUTH_URL, { - method: "POST", - headers: { - Authorization: getBasicAuthHeader(), - "Content-Type": "application/x-www-form-urlencoded", - }, - body: params.toString(), - // @ts-ignore - rejectUnauthorized: false, - }); - - const tokenResponse: TokenResponse = await response.json(); - - tokenManager.setToken( - tokenResponse.access_token, - tokenResponse.expires_in, - tokenResponse.token_type, - ); - tokenCache = await tokenManager.getToken()!; - } - return NextResponse.json({ - isAuthenticated: true, - expiresAt: new Date(tokenCache.expires_at).toISOString(), - }); - } catch (error) { - console.error("NYU Auth error:", error); - return NextResponse.json( - { error: "Internal server error" }, - { status: 500 }, - ); - } -} diff --git a/booking-app/app/api/nyu/identity/[uniqueId]/route.ts b/booking-app/app/api/nyu/identity/[uniqueId]/route.ts index 0310c281..c5513975 100644 --- a/booking-app/app/api/nyu/identity/[uniqueId]/route.ts +++ b/booking-app/app/api/nyu/identity/[uniqueId]/route.ts @@ -1,5 +1,4 @@ -import { ensureNYUToken } from "@/lib/server/nyuApiAuth"; -import { NYUTokenManager } from "@/lib/server/nyuTokenCache"; +import { getNYUToken } from "@/lib/server/nyuApiAuth"; import { NextRequest, NextResponse } from "next/server"; const NYU_API_BASE = "https://api.nyu.edu/identity-v2-sys"; @@ -9,16 +8,15 @@ export async function GET( { params }: { params: { uniqueId: string } }, ) { try { - const authResult = await ensureNYUToken(); - if (!authResult.isAuthenticated || !authResult.token) { + const token = await getNYUToken(); + if (!token) { return NextResponse.json( - { error: authResult.error || "Authentication required" }, + { error: "Authentication failed" }, { status: 401 }, ); } const apiAccessId = process.env.NYU_API_ACCESS_ID; - if (!apiAccessId) { return NextResponse.json( { error: "API access ID not configured" }, @@ -33,24 +31,13 @@ export async function GET( const response = await fetch(url.toString(), { headers: { - Authorization: `Bearer ${authResult.token}`, + Authorization: `Bearer ${token}`, Accept: "application/json", }, }); console.log("response", response); if (!response.ok) { - const errorText = await response.text(); - console.error("NYU Identity API Error:", { - status: response.status, - body: errorText, - uniqueId: params.uniqueId, - }); - - if (response.status === 401) { - NYUTokenManager.getInstance().clearToken(); - } - return NextResponse.json( { error: `NYU API call failed: ${response.status}` }, { status: response.status }, @@ -58,7 +45,6 @@ export async function GET( } const userData = await response.json(); - return NextResponse.json(userData); } catch (error) { console.error("Identity API error:", error); diff --git a/booking-app/lib/server/nyuApiAuth.ts b/booking-app/lib/server/nyuApiAuth.ts index e21abe41..c7172b24 100644 --- a/booking-app/lib/server/nyuApiAuth.ts +++ b/booking-app/lib/server/nyuApiAuth.ts @@ -1,32 +1,48 @@ -import { AuthResult } from "@/components/src/types"; -import { NYUTokenManager } from "./nyuTokenCache"; +const NYU_AUTH_URL = "https://auth.nyu.edu/oauth2/token"; -export async function ensureNYUToken(): Promise { +export async function getNYUToken(): Promise { try { - const tokenManager = NYUTokenManager.getInstance(); - const tokenCache = await tokenManager.getToken(); + const clientId = process.env.NYU_API_CLIENT_ID; + const clientSecret = process.env.NYU_API_CLIENT_SECRET; + const username = process.env.NYU_API_USER_NAME; + const password = process.env.NYU_API_PASSWORD; - if (!tokenCache) { - return { - isAuthenticated: false, - token: "", - expiresAt: "", - error: "Failed to get token", - }; + if (!clientId || !clientSecret || !username || !password) { + throw new Error("NYU credentials not configured"); } - return { - isAuthenticated: true, - token: tokenCache.access_token, - expiresAt: new Date(tokenCache.expires_at).toISOString(), - }; + const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString( + "base64" + ); + + const params = new URLSearchParams({ + grant_type: "password", + username, + password, + scope: "openid", + }); + + const response = await fetch(NYU_AUTH_URL, { + method: "POST", + headers: { + Authorization: `Basic ${basicAuth}`, + "Content-Type": "application/x-www-form-urlencoded", + }, + cache: "no-store", + next: { revalidate: 0 }, + body: params.toString(), + }); + + if (!response.ok) { + console.log("Error response", response); + throw new Error(`Token fetch failed: ${response.status}`); + } + + const data = await response.json(); + console.log("token", data.access_token); + return data.access_token; } catch (error) { - console.error("NYU Auth error:", error); - return { - isAuthenticated: false, - token: "", - expiresAt: "", - error: error instanceof Error ? error.message : "Internal error", - }; + console.error("Failed to get NYU token:", error); + return null; } }