Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add: keycloak logout url redirect #1420

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/admin-ui/src/common/Error403.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { H1 } from "common/src/common/typography";
import { breakpoints } from "common/src/common/style";
import { useSession } from "@/hooks/auth";
import { PUBLIC_URL } from "./const";
import { env } from "@/env.mjs";

const Wrapper = styled.div`
padding: var(--spacing-layout-s);
Expand Down Expand Up @@ -67,7 +68,7 @@ const LogoutSection = ({
</Link>
{isAuthenticated && (
<ButtonContainer>
<Button onClick={() => signOut(apiBaseUrl)}>
<Button onClick={() => signOut(apiBaseUrl, env.NEXT_PUBLIC_BASE_URL)}>
{t("Navigation.logout")}
</Button>
</ButtonContainer>
Expand Down
2 changes: 1 addition & 1 deletion apps/admin-ui/src/component/Navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ const Navigation = ({ apiBaseUrl }: Props) => {
<IconSignout />
</>
}
onClick={() => signOut(apiBaseUrl)}
onClick={() => signOut(apiBaseUrl, env.NEXT_PUBLIC_BASE_URL)}
/>
</Header.ActionBarItem>
) : (
Expand Down
8 changes: 0 additions & 8 deletions apps/admin-ui/src/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,6 @@ i18n.addResourceBundle("en", "common", {
month: "Month",
today: "Today",
});
i18n.addResourceBundle("fi", "logout", {
message: "Olet kirjautunut ulos Varaamosta",
signOutFromOtherServices: "Kirjaudu ulos myös muista Helsingin palveluista",
});
i18n.addResourceBundle("en", "logout", {
message: "You have signed out from Varaamo",
signOutFromOtherServices: "Sign out from other Helsinki services also",
});
i18n.addResourceBundle("fi", "reservationCalendar", {
showCurrentDay: "Näytä tämä päivä",
showPrevious: "Naytä edellinen {{view}}",
Expand Down
74 changes: 15 additions & 59 deletions apps/admin-ui/src/pages/auth/logout/index.tsx
Original file line number Diff line number Diff line change
@@ -1,72 +1,28 @@
import React from "react";
import styled from "styled-components";
import { useTranslation } from "react-i18next";
import ClientOnly from "common/src/ClientOnly";
import KorosHeading, { Heading } from "@/component/KorosHeading";
import { HERO_IMAGE_URL } from "@/common/const";
import Navigation from "@/component/Navigation";
import { env } from "@/env.mjs";
import BaseLayout from "../../layout";
import { useEffect } from "react";
// NOTE not using App.tsx so need to import i18n here also
import "@/i18n";
import { getVersion } from "@/helpers/serverUtils";
import { useRouter } from "next/router";

// TODO move these to a common layout (PageWrapper, copies from)
const Wrapper = styled.main`
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
flex-grow: 1;
`;

const Ingress = styled.p`
font-size: 1.5rem;
line-height: 1.8125rem;
display: flex;
flex-direction: column;
align-items: center;
flex-grow: 1;
`;

function Layout(props: { children: React.ReactNode } & Pick<Props, "version">) {
const { children, version } = props;
return (
<BaseLayout version={version}>
<Wrapper>{children}</Wrapper>
</BaseLayout>
);
}

function LogoutPage({ apiBaseUrl, logoutUrl, version }: Props) {
const { t } = useTranslation(["common", "logout"]);
type Props = Awaited<ReturnType<typeof getServerSideProps>>["props"];

// Can't use SSR because of translations
return (
<Layout version={version}>
<ClientOnly>
<Navigation apiBaseUrl={apiBaseUrl} />
<KorosHeading heroImage={HERO_IMAGE_URL}>
<Heading>{t("common:applicationName")}</Heading>
<p style={{ fontSize: "1.8rem" }}>{t("logout:message")}</p>
</KorosHeading>
<Ingress>
<a href={logoutUrl}>{t("logout:signOutFromOtherServices")}</a>
</Ingress>
</ClientOnly>
</Layout>
);
/* Page to redirect to the front page after a succesful logout
* TODO might be able to replace this with middleware
* */
function LogoutPage({ redirectUrl }: Props) {
const router = useRouter();

useEffect(() => {
router.replace(redirectUrl);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return null;
}

type Props = Awaited<ReturnType<typeof getServerSideProps>>["props"];

export async function getServerSideProps() {
const logoutUrl = env.TUNNISTAMO_URL ? `${env.TUNNISTAMO_URL}/logout/` : "";
const apiBaseUrl = env.TILAVARAUS_API_URL ?? "";
return {
props: {
logoutUrl,
apiBaseUrl,
redirectUrl: "/",
version: getVersion(),
// TODO can't use SSR translations because our translations aren't in public folder
// ...(await serverSideTranslations(locale ?? "fi")),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,33 @@ import type { GetServerSidePropsContext } from "next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { useRouter } from "next/router";
import { useEffect } from "react";
import { env } from "@/env.mjs";
import { getCommonServerSideProps } from "@/modules/serverUtils";

type Props = Awaited<ReturnType<typeof getServerSideProps>>["props"];

export const getServerSideProps = async ({
/* Page to redirect to the front page after a succesful logout
* TODO might be able to replace this with middleware
* */
function LogoutPage({ redirectUrl }: Props) {
const router = useRouter();

useEffect(() => {
router.replace(redirectUrl);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return null;
}

export async function getServerSideProps({
locale,
}: GetServerSidePropsContext) => {
}: GetServerSidePropsContext) {
return {
props: {
...getCommonServerSideProps(),
redirectUrl: env.NEXT_PUBLIC_BASE_URL || "/",
redirectUrl: "/",
...(await serverSideTranslations(locale ?? "fi")),
},
};
};

// TODO what is the purpose of this page?
const LogoutPage = ({ redirectUrl }: Props) => {
const router = useRouter();

useEffect(() => {
router.push(redirectUrl);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return null;
};
}

export default LogoutPage;
30 changes: 23 additions & 7 deletions packages/common/src/browserHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,25 @@ export function signIn(apiBaseUrl: string, returnUrl?: unknown) {
window.location.href = url;
}

// Log the user out and redirect to route /logout
function removeTrailingSlash(url: string): string {
return url.endsWith("/") ? url.slice(0, -1) : url;
}

/// Sign the user out and redirect to route /auth/logout/ after the session is destroyed
/// Thows if called on the server
export function signOut(apiBaseUrl: string) {
/// @param apiBaseUrl - base url for api
/// @param appUrlBasePath - base path for the app (only required if next app is not in host root)
export function signOut(apiBaseUrl: string, appUrlBasePath = "") {
if (!isBrowser) {
throw new Error("signIn can only be called in the browser");
}
const url = new URL(window.location.href);
const logoutUrl = getSignOutUrl(apiBaseUrl);
const csrfToken = getCookie("csrftoken");
const logoutPath = "/auth/logout/";
const origin = url.origin;
const returnUrlBase = `${removeTrailingSlash(origin)}${removeTrailingSlash(appUrlBasePath)}`;
const returnUrl = `${returnUrlBase}${logoutPath}`;
if (!csrfToken) {
throw new Error("csrf token not found");
}
Expand All @@ -44,12 +55,17 @@ export function signOut(apiBaseUrl: string) {
form.method = "POST";
form.action = logoutUrl;
form.style.display = "none";
const csrfTokenInput = document.createElement("input");
csrfTokenInput.type = "hidden";
csrfTokenInput.name = "csrfmiddlewaretoken";
csrfTokenInput.value = csrfToken;
form.appendChild(csrfTokenInput);
addFormParam(form, "csrfmiddlewaretoken", csrfToken);
addFormParam(form, "redirect_to", returnUrl);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}

function addFormParam(form: HTMLFormElement, name: string, value: string) {
const input = document.createElement("input");
input.type = "hidden";
input.name = name;
input.value = value;
form.appendChild(input);
}