feat: Monadical SSO as replacement of Fief (#393)

* sso: first pass for integrating SSO

still have issue on refreshing
maybe customize the login page, or completely avoid it
make 100% to understand how session server/client are working
need to test with different configuration option (features flags and
requireLogin)

* sso: correctly handle refresh token, with pro-active refresh

Going on interceptors make extra calls to reflector when 401.
We need then to circle back with NextJS backend to update the jwt,
session, then retry the failed request.

I prefered to go pro-active, and ensure the session AND jwt are always
up to date.

A minute before the expiration, we'll try to refresh it. useEffect() of
NextJS cannot be asynchronous, so we cannot wait for the token to be
refreshed.

Every 20s, a minute before the expiration (so 3x in total max) we'll try
to renew. When the accessToken is renewed, the session is updated, and
dispatching up to the client, which updates the useApi().

Therefore, no component will left without a incorrect token.

* fixes: issue with missing key on react-select-search because the default value is undefined

* sso: fixes login/logout button, and avoid seeing the login with authentik page when clicking

* sso: ensure /transcripts/new is not behind protected page, and feature flags page are honored

* sso: fixes user sub->id

* fixes: remove old layout not used

* fixes: set default NEXT_PUBLIC_SITE_URL as localhost

* fixes: removing fief again due to merge with main

* sso: ensure session is always ready before doing any action

* sso: add migration from fief to jwt in server, only from transcripts list

* fixes: user tests

* fixes: compilation issues
This commit is contained in:
2024-09-03 19:27:15 +02:00
committed by GitHub
parent 28fe6c11f7
commit 03561453c5
30 changed files with 707 additions and 280 deletions

View File

@@ -40,7 +40,6 @@ import {
} from "@chakra-ui/react";
import { PlusSquareIcon } from "@chakra-ui/icons";
import { ExpandableText } from "../../lib/expandableText";
// import { useFiefUserinfo } from "@fief/fief/nextjs/react";
export default function TranscriptBrowser() {
const [page, setPage] = useState<number>(1);
@@ -53,10 +52,6 @@ export default function TranscriptBrowser() {
React.useState<string>();
const [deletedItemIds, setDeletedItemIds] = React.useState<string[]>();
// Todo: fief add name field to userinfo
// const user = useFiefUserinfo();
// console.log(user);
useEffect(() => {
setDeletedItemIds([]);
}, [page, response]);

View File

@@ -10,19 +10,23 @@ import { useRouter } from "next/navigation";
import useCreateTranscript from "../createTranscript";
import SelectSearch from "react-select-search";
import { supportedLanguages } from "../../../supportedLanguages";
import { useFiefIsAuthenticated } from "@fief/fief/nextjs/react";
import { useSession } from "next-auth/react";
import { featureEnabled } from "../../../domainContext";
import { Button, Text } from "@chakra-ui/react";
import { signIn } from "next-auth/react";
import { Spinner } from "@chakra-ui/react";
const TranscriptCreate = () => {
const router = useRouter();
const isAuthenticated = useFiefIsAuthenticated();
const { status } = useSession();
const sessionReady = status !== "loading";
const isAuthenticated = status === "authenticated";
const requireLogin = featureEnabled("requireLogin");
const [name, setName] = useState<string>("");
const nameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setName(event.target.value);
};
const [targetLanguage, setTargetLanguage] = useState<string>();
const [targetLanguage, setTargetLanguage] = useState<string>("NOTRANSLATION");
const onLanguageChange = (newval) => {
(!newval || typeof newval === "string") && setTargetLanguage(newval);
@@ -33,16 +37,21 @@ const TranscriptCreate = () => {
const [loadingRecord, setLoadingRecord] = useState(false);
const [loadingUpload, setLoadingUpload] = useState(false);
const getTargetLanguage = () => {
if (targetLanguage === "NOTRANSLATION") return;
return targetLanguage;
};
const send = () => {
if (loadingRecord || createTranscript.loading || permissionDenied) return;
setLoadingRecord(true);
createTranscript.create({ name, target_language: targetLanguage });
createTranscript.create({ name, target_language: getTargetLanguage() });
};
const uploadFile = () => {
if (loadingUpload || createTranscript.loading || permissionDenied) return;
setLoadingUpload(true);
createTranscript.create({ name, target_language: targetLanguage });
createTranscript.create({ name, target_language: getTargetLanguage() });
};
useEffect(() => {
@@ -87,10 +96,12 @@ const TranscriptCreate = () => {
</div>
</section>
<section className="flex flex-col justify-center items-center w-full h-full">
{requireLogin && !isAuthenticated ? (
{!sessionReady ? (
<Spinner />
) : requireLogin && !isAuthenticated ? (
<button
className="mt-4 bg-blue-400 hover:bg-blue-500 focus-visible:bg-blue-500 text-white font-bold py-2 px-4 rounded"
onClick={() => router.push("/login")}
onClick={() => signIn("authentik")}
>
Log in
</button>

View File

@@ -15,8 +15,9 @@ import {
Text,
} from "@chakra-ui/react";
import { FaShare } from "react-icons/fa";
import { useFiefUserinfo } from "@fief/fief/build/esm/nextjs/react";
import useApi from "../../lib/useApi";
import { useSession } from "next-auth/react";
import { CustomSession } from "../../lib/types";
import { Select } from "chakra-react-select";
import ShareLink from "./shareLink";
import ShareCopy from "./shareCopy";
@@ -69,7 +70,9 @@ export default function ShareAndPrivacy(props: ShareAndPrivacyProps) {
setShareLoading(false);
};
const userId = useFiefUserinfo()?.sub;
const { data: session } = useSession();
const customSession = session as CustomSession;
const userId = customSession?.user?.id;
useEffect(() => {
setIsOwner(!!(requireLogin && userId === props.transcriptResponse.user_id));

View File

@@ -1,7 +1,6 @@
import { useContext, useEffect, useState } from "react";
import { DomainContext } from "../../domainContext";
import getApi from "../../lib/useApi";
import { useFiefAccessTokenInfo } from "@fief/fief/build/esm/nextjs/react";
export type Mp3Response = {
media: HTMLMediaElement | null;
@@ -15,7 +14,8 @@ const useMp3 = (id: string, waiting?: boolean): Mp3Response => {
const [loading, setLoading] = useState<boolean>(false);
const api = getApi();
const { api_url } = useContext(DomainContext);
const accessTokenInfo = useFiefAccessTokenInfo();
const accessTokenInfo = api?.httpRequest?.config?.TOKEN;
const [serviceWorker, setServiceWorker] =
useState<ServiceWorkerRegistration | null>(null);
@@ -37,7 +37,7 @@ const useMp3 = (id: string, waiting?: boolean): Mp3Response => {
// Send the token to the service worker
navigator.serviceWorker.controller.postMessage({
type: "SET_AUTH_TOKEN",
token: accessTokenInfo?.access_token,
token: accessTokenInfo,
});
}, [navigator.serviceWorker, !serviceWorker, accessTokenInfo]);

View File

@@ -1,18 +0,0 @@
"use client";
import { FiefAuthProvider } from "@fief/fief/nextjs/react";
import { createContext } from "react";
export const CookieContext = createContext<{ hasAuthCookie: boolean }>({
hasAuthCookie: false,
});
export default function FiefWrapper({ children, hasAuthCookie }) {
return (
<CookieContext.Provider value={{ hasAuthCookie }}>
<FiefAuthProvider currentUserPath="/api/current-user">
{children}
</FiefAuthProvider>
</CookieContext.Provider>
);
}

View File

@@ -1,20 +1,35 @@
"use client";
import { useFiefIsAuthenticated } from "@fief/fief/nextjs/react";
import { useSession, signOut, signIn } from "next-auth/react";
import { Spinner } from "@chakra-ui/react";
import Link from "next/link";
export default function UserInfo() {
const isAuthenticated = useFiefIsAuthenticated();
const { status } = useSession();
const sessionReady = status !== "loading";
const isAuthenticated = status === "authenticated";
return !isAuthenticated ? (
return !sessionReady ? (
<Spinner size="xs" thickness="1px" className="mx-3" />
) : !isAuthenticated ? (
<span className="hover:underline focus-within:underline underline-offset-2 decoration-[.5px] font-light px-2">
<Link href="/login" className="outline-none" prefetch={false}>
<Link
href="/"
onClick={() => signIn("authentik")}
className="outline-none"
prefetch={false}
>
Log in
</Link>
</span>
) : (
<span className="font-light px-2">
<span className="hover:underline focus-within:underline underline-offset-2 decoration-[.5px]">
<Link href="/logout" className="outline-none" prefetch={false}>
<Link
href="#"
onClick={() => signOut({ callbackUrl: "/" })}
className="outline-none"
prefetch={false}
>
Log out
</Link>
</span>

View File

@@ -4,7 +4,7 @@ import "@whereby.com/browser-sdk/embed";
import { useCallback, useEffect, useRef } from "react";
import useRoomMeeting from "./useRoomMeeting";
import { useRouter } from "next/navigation";
import { useFiefIsAuthenticated } from "@fief/fief/build/esm/nextjs/react";
import { useSession } from "next-auth/react";
export type RoomDetails = {
params: {
@@ -17,7 +17,9 @@ export default function Room(details: RoomDetails) {
const roomName = details.params.roomName;
const meeting = useRoomMeeting(roomName);
const router = useRouter();
const isAuthenticated = useFiefIsAuthenticated();
const { status } = useSession();
const sessionReady = status !== "loading";
const isAuthenticated = status === "authenticated";
const roomUrl = meeting?.response?.host_room_url
? meeting?.response?.host_room_url
@@ -28,7 +30,7 @@ export default function Room(details: RoomDetails) {
}, []);
useEffect(() => {
if (!isAuthenticated || !roomUrl) return;
if (!sessionReady || !isAuthenticated || !roomUrl) return;
wherebyRef.current?.addEventListener("leave", handleLeave);

View File

@@ -0,0 +1,9 @@
// NextAuth route handler for Authentik
// Refresh rotation has been taken from https://next-auth.js.org/v3/tutorials/refresh-token-rotation even if we are using 4.x
import NextAuth from "next-auth";
import { authOptions } from "../../../lib/auth";
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

View File

@@ -1,14 +1,12 @@
import "./styles/globals.scss";
import { Poppins } from "next/font/google";
import { Metadata, Viewport } from "next";
import FiefWrapper from "./(auth)/fiefWrapper";
import SessionProvider from "./lib/SessionProvider";
import { ErrorProvider } from "./(errors)/errorContext";
import ErrorMessage from "./(errors)/errorMessage";
import { DomainContextProvider } from "./domainContext";
import { getConfig } from "./lib/edgeConfig";
import { ErrorBoundary } from "@sentry/nextjs";
import { cookies } from "next/dist/client/components/headers";
import { SESSION_COOKIE_NAME } from "./lib/fief";
import { Providers } from "./providers";
const poppins = Poppins({ subsets: ["latin"], weight: ["200", "400", "600"] });
@@ -67,7 +65,6 @@ export default async function RootLayout({
children: React.ReactNode;
}) {
const config = await getConfig();
const hasAuthCookie = !!cookies().get(SESSION_COOKIE_NAME);
return (
<html lang="en">
@@ -76,7 +73,7 @@ export default async function RootLayout({
poppins.className + "h-[100svh] w-[100svw] overflow-hidden relative"
}
>
<FiefWrapper hasAuthCookie={hasAuthCookie}>
<SessionProvider>
<DomainContextProvider config={config}>
<ErrorBoundary fallback={<p>"something went really wrong"</p>}>
<ErrorProvider>
@@ -85,7 +82,7 @@ export default async function RootLayout({
</ErrorProvider>
</ErrorBoundary>
</DomainContextProvider>
</FiefWrapper>
</SessionProvider>
</body>
</html>
);

View File

@@ -0,0 +1,36 @@
/**
* This is a custom hook that automatically refreshes the session when the access token is about to expire.
* When communicating with the reflector API, we need to ensure that the access token is always valid.
*
* We could have implemented that as an interceptor on the API client, but not everything is using the
* API client, or have access to NextJS directly (serviceWorker).
*/
"use client";
import { useSession } from "next-auth/react";
import { useEffect } from "react";
import { CustomSession } from "./types";
export function SessionAutoRefresh({
children,
refreshInterval = 20 /* seconds */,
}) {
const { data: session, update } = useSession();
const customSession = session as CustomSession;
const accessTokenExpires = customSession?.accessTokenExpires;
useEffect(() => {
const interval = setInterval(() => {
if (accessTokenExpires) {
const timeLeft = accessTokenExpires - Date.now();
if (timeLeft < refreshInterval * 1000) {
update();
}
}
}, refreshInterval * 1000);
return () => clearInterval(interval);
}, [accessTokenExpires, refreshInterval, update]);
return children;
}

View File

@@ -0,0 +1,11 @@
"use client";
import { SessionProvider as SessionProviderNextAuth } from "next-auth/react";
import { SessionAutoRefresh } from "./SessionAutoRefresh";
export default function SessionProvider({ children }) {
return (
<SessionProviderNextAuth refetchInterval={60} refetchOnWindowFocus={true}>
<SessionAutoRefresh>{children}</SessionAutoRefresh>
</SessionProviderNextAuth>
);
}

101
www/app/lib/auth.ts Normal file
View File

@@ -0,0 +1,101 @@
import { AuthOptions } from "next-auth";
import AuthentikProvider from "next-auth/providers/authentik";
import { JWT } from "next-auth/jwt";
import { JWTWithAccessToken, CustomSession } from "./types";
const PRETIMEOUT = 60; // seconds before token expires to refresh it
export const authOptions: AuthOptions = {
providers: [
AuthentikProvider({
clientId: process.env.AUTHENTIK_CLIENT_ID as string,
clientSecret: process.env.AUTHENTIK_CLIENT_SECRET as string,
issuer: process.env.AUTHENTIK_ISSUER,
authorization: {
params: {
scope: "openid email profile offline_access",
},
},
}),
],
session: {
strategy: "jwt",
},
callbacks: {
async jwt({ token, account, user }) {
const extendedToken = token as JWTWithAccessToken;
if (account && user) {
// called only on first login
// XXX account.expires_in used in example is not defined for authentik backend, but expires_at is
const expiresAt = (account.expires_at as number) - PRETIMEOUT;
return {
...extendedToken,
accessToken: account.access_token,
accessTokenExpires: expiresAt * 1000,
refreshToken: account.refresh_token,
};
}
if (Date.now() < extendedToken.accessTokenExpires) {
return token;
}
// access token has expired, try to update it
return await refreshAccessToken(token);
},
async session({ session, token }) {
const extendedToken = token as JWTWithAccessToken;
const customSession = session as CustomSession;
customSession.accessToken = extendedToken.accessToken;
customSession.accessTokenExpires = extendedToken.accessTokenExpires;
customSession.error = extendedToken.error;
customSession.user = {
id: extendedToken.sub,
name: extendedToken.name,
email: extendedToken.email,
};
return customSession;
},
},
};
async function refreshAccessToken(token: JWT) {
try {
const url = `${process.env.AUTHENTIK_REFRESH_TOKEN_URL}`;
const options = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
client_id: process.env.AUTHENTIK_CLIENT_ID as string,
client_secret: process.env.AUTHENTIK_CLIENT_SECRET as string,
grant_type: "refresh_token",
refresh_token: token.refreshToken as string,
}).toString(),
method: "POST",
};
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`Failed to refresh access token: ${response.statusText}`);
}
const refreshedTokens = await response.json();
return {
...token,
accessToken: refreshedTokens.access_token,
accessTokenExpires:
Date.now() + (refreshedTokens.expires_in - PRETIMEOUT) * 1000,
refreshToken: refreshedTokens.refresh_token,
};
} catch (error) {
console.error("Error refreshing access token", error);
return {
...token,
error: "RefreshAccessTokenError",
};
}
}

View File

@@ -1,79 +0,0 @@
import { Fief, FiefUserInfo } from "@fief/fief";
import { FiefAuth, IUserInfoCache } from "@fief/fief/nextjs";
import { getConfig } from "./edgeConfig";
export const SESSION_COOKIE_NAME = "reflector-auth";
export const fiefClient = new Fief({
baseURL: process.env.FIEF_URL ?? "",
clientId: process.env.FIEF_CLIENT_ID ?? "",
clientSecret: process.env.FIEF_CLIENT_SECRET ?? "",
});
class MemoryUserInfoCache implements IUserInfoCache {
private storage: Record<string, any>;
constructor() {
this.storage = {};
}
async get(id: string): Promise<FiefUserInfo | null> {
const userinfo = this.storage[id];
if (userinfo) {
return userinfo;
}
return null;
}
async set(id: string, userinfo: FiefUserInfo): Promise<void> {
this.storage[id] = userinfo;
}
async remove(id: string): Promise<void> {
this.storage[id] = undefined;
}
async clear(): Promise<void> {
this.storage = {};
}
}
const FIEF_AUTHS = {} as { [domain: string]: FiefAuth };
export const getFiefAuth = async (url: URL) => {
if (FIEF_AUTHS[url.hostname]) {
return FIEF_AUTHS[url.hostname];
} else {
const config = url && (await getConfig());
if (config) {
FIEF_AUTHS[url.hostname] = new FiefAuth({
client: fiefClient,
sessionCookieName: SESSION_COOKIE_NAME,
redirectURI: config.auth_callback_url,
logoutRedirectURI: url.origin,
userInfoCache: new MemoryUserInfoCache(),
});
return FIEF_AUTHS[url.hostname];
} else {
throw new Error("Fief intanciation failed");
}
}
};
export const getFiefAuthMiddleware = async (url) => {
const protectedPaths = [
{
matcher: "/transcripts",
parameters: {},
},
{
matcher: "/browse",
parameters: {},
},
{
matcher: "/rooms",
parameters: {},
},
];
return (await getFiefAuth(url))?.middleware(protectedPaths);
};

20
www/app/lib/types.ts Normal file
View File

@@ -0,0 +1,20 @@
import { Session } from "next-auth";
import { JWT } from "next-auth/jwt";
export interface JWTWithAccessToken extends JWT {
accessToken: string;
accessTokenExpires: number;
refreshToken: string;
error?: string;
}
export interface CustomSession extends Session {
accessToken: string;
accessTokenExpires: number;
error?: string;
user: {
id?: string;
name?: string | null;
email?: string | null;
};
}

View File

@@ -1,30 +1,40 @@
import { useFiefAccessTokenInfo } from "@fief/fief/nextjs/react";
import { useSession, signOut } from "next-auth/react";
import { useContext, useEffect, useState } from "react";
import { DomainContext, featureEnabled } from "../domainContext";
import { CookieContext } from "../(auth)/fiefWrapper";
import { OpenApi, DefaultService } from "../api";
import { CustomSession } from "./types";
export default function useApi(): DefaultService | null {
const accessTokenInfo = useFiefAccessTokenInfo();
const api_url = useContext(DomainContext).api_url;
const requireLogin = featureEnabled("requireLogin");
const [api, setApi] = useState<OpenApi | null>(null);
const { hasAuthCookie } = useContext(CookieContext);
const { data: session, status } = useSession();
const customSession = session as CustomSession;
const accessToken = customSession?.accessToken;
if (!api_url) throw new Error("no API URL");
useEffect(() => {
if (hasAuthCookie && requireLogin && !accessTokenInfo) {
if (customSession?.error === "RefreshAccessTokenError") {
signOut();
}
}, [session]);
useEffect(() => {
if (status === "loading") {
return;
}
if (status === "authenticated" && !accessToken) {
return;
}
const openApi = new OpenApi({
BASE: api_url,
TOKEN: accessTokenInfo ? accessTokenInfo?.access_token : undefined,
TOKEN: accessToken,
});
setApi(openApi);
}, [!accessTokenInfo, hasAuthCookie]);
}, [accessToken, status]);
return api?.default ?? null;
}

View File

@@ -1,21 +0,0 @@
export async function getCurrentUser(): Promise<any> {
try {
const response = await fetch("/api/current-user");
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
// Ensure the data structure is as expected
if (data.userinfo && data.access_token_info) {
return data;
} else {
throw new Error("Unexpected data structure");
}
} catch (error) {
console.error("Error fetching the user data:", error);
throw error; // or you can return an appropriate fallback or error indicator
}
}

View File

@@ -489,6 +489,6 @@ const supportedLanguages: LanguageOption[] = [
},
];
supportedLanguages.push({ value: undefined, name: "No Translation" });
supportedLanguages.push({ value: "NOTRANSLATION", name: "No Translation" });
export { supportedLanguages };