Skip to content
This repository has been archived by the owner on Feb 10, 2025. It is now read-only.

Commit

Permalink
fix: build signin url properly
Browse files Browse the repository at this point in the history
  • Loading branch information
joonatank committed Feb 15, 2024
1 parent ada90ae commit c5002f7
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
14 changes: 6 additions & 8 deletions apps/ui/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSignInUrl } from "@/modules/const";
import { env } from "@/env.mjs";

function redirectProtectedRoute(req: NextRequest) {
// TODO check that the cookie is valid not just present
const { cookies, headers } = req;
const hasSession = cookies.has("sessionid");
const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL ?? "";
const apiBaseUrl = env.TILAVARAUS_API_URL ?? "";

if (!hasSession) {
// on the server we are behind a gateway so get the forwarded headers
// localhost has no headers
const currentUrl = req.url;
const url = new URL(currentUrl);
const protocol = headers.get("x-forwarded-proto") ?? "http";
const host = headers.get("x-forwarded-host");
const originalUrl = headers.get("x-original-url");
if (host && originalUrl) {
const origin = `${protocol}://${host}`;
return getSignInUrl(apiBaseUrl, originalUrl, origin);
}
return getSignInUrl(apiBaseUrl, currentUrl);
const host = headers.get("x-forwarded-host") ?? url.host;
const origin = `${protocol}://${host}`;
return getSignInUrl(apiBaseUrl, url.pathname, origin);
}
return undefined;
}
Expand Down
6 changes: 4 additions & 2 deletions packages/common/src/urlBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,15 @@ export function getSignInUrl(
originOverride?: string
): string {
const authUrl = buildAuthUrl(apiBaseUrl);
// TODO why is originOveride only used when on logout?
if (callBackUrl.includes(`/logout`)) {
// TODO this is unsound if the callback url is not a full url but this at least redirects to an error page
const baseUrl =
originOverride != null ? originOverride : new URL(callBackUrl).origin;
return `${authUrl}login?next=${baseUrl}`;
}
return `${authUrl}login?next=${callBackUrl}`;
const next =
originOverride != null ? `${originOverride}/${callBackUrl}` : callBackUrl;
return `${authUrl}login?next=${next}`;
}

/// @param apiBaseUrl - base url for api (hostname typically)
Expand Down

0 comments on commit c5002f7

Please sign in to comment.