diff --git a/src/auth/ekirjastoFetch.ts b/src/auth/ekirjastoFetch.ts index 6f925a6..6f177f9 100644 --- a/src/auth/ekirjastoFetch.ts +++ b/src/auth/ekirjastoFetch.ts @@ -8,13 +8,18 @@ export async function fetchEAuthToken( url: string | undefined, token: string | undefined ) { - if (!url) { + if (!url || !token) { throw new ApplicationError({ title: "Incomplete Authentication Info", detail: "No URL or Token was provided for authentication" }); } + //If in some case, the bearer text is present, remove it so there is no repetition in the request + if (token?.startsWith("Bearer ")) { + token = token.replace("Bearer ", ""); + } + const response = await fetchWithHeaders(url, `Bearer ${token}`, {}, "POST"); const json = await response.json(); @@ -24,3 +29,24 @@ export async function fetchEAuthToken( return json; } + +export async function fetchEkirjastoToken( + url: string | undefined, + token: string | undefined +) { + if (!url || !token) { + throw new ApplicationError({ + title: "Incomplete Authentication Info", + detail: "No URL or Token was provided for authentication" + }); + } + + const response = await fetchWithHeaders(url, token, {}, "GET"); + const json = await response.json(); + + if (!response.ok) { + throw new ServerError(url, response.status, json); + } + + return json; +} diff --git a/src/auth/useCredentials.ts b/src/auth/useCredentials.ts index 1f6cbb1..cf144cb 100644 --- a/src/auth/useCredentials.ts +++ b/src/auth/useCredentials.ts @@ -113,6 +113,10 @@ function getCredentialsCookie( if (librarySlug === "ekirjasto") { // Get access token, for ekirjasto login credentials const accessToken = Cookie.get(cookieNameEkirjasto()); + if (!accessToken) { + console.log("No access token"); + return undefined; + } // Create ekirjasto authentication credentials const authCredentials: AuthCredentials = { token: `Bearer ${accessToken}`, diff --git a/src/components/context/UserContext.tsx b/src/components/context/UserContext.tsx index 81213bb..4786452 100644 --- a/src/components/context/UserContext.tsx +++ b/src/components/context/UserContext.tsx @@ -8,6 +8,7 @@ import * as React from "react"; import useSWR from "swr"; import { BasicTokenAuthType, EkirjastoAuthType } from "types/opds1"; import { addHours, isBefore } from "date-fns"; +import { fetchEkirjastoToken } from "auth/ekirjastoFetch"; type Status = "authenticated" | "loading" | "unauthenticated"; export type UserState = { @@ -22,6 +23,10 @@ export type UserState = { authenticationUrl: string | undefined ) => void; signOut: () => void; + getEkirjastoToken: ( + token: string, + fetchUrl: string | undefined + ) => Promise; setBook: (book: AnyBook, id?: string) => void; error: any; token: string | undefined; @@ -117,6 +122,17 @@ export const UserProvider = ({ children }: UserProviderProps) => { } ); + async function getEkirjastoToken( + token: string, + fetchUrl: string | undefined + ): Promise { + const { token: ekirjastoToken } = await fetchEkirjastoToken( + fetchUrl, + token + ); + return ekirjastoToken; + } + function signIn( token: string | Token, method: AppAuthMethod, @@ -160,6 +176,7 @@ export const UserProvider = ({ children }: UserProviderProps) => { refetchLoans: mutate, signIn, signOut, + getEkirjastoToken, setBook, error, token: stringifyToken(credentials), diff --git a/src/config/magazines.ts b/src/config/magazines.ts index ea4c4e8..e220c38 100644 --- a/src/config/magazines.ts +++ b/src/config/magazines.ts @@ -73,5 +73,5 @@ export const MAGAZINE_CONFIG = { // Default iframe sandbox permissions IFRAME_SANDBOX: - "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox" + "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation" } as const; diff --git a/src/pages/[library]/magazines/index.tsx b/src/pages/[library]/magazines/index.tsx index 9083b17..fe33a9b 100644 --- a/src/pages/[library]/magazines/index.tsx +++ b/src/pages/[library]/magazines/index.tsx @@ -17,12 +17,32 @@ import { } from "config/magazines"; import Head from "next/head"; import BreadcrumbBar from "components/BreadcrumbBar"; +import { EKIRJASTO_AUTH_TYPE } from "utils/constants"; const MagazinesFixedContent: React.FC = () => { const iframeRef = React.useRef(null); - const { token } = useUser(); + const { token, getEkirjastoToken } = useUser(); const { initLogin } = useLogin(); - const { slug } = useLibraryContext(); + const { slug, authMethods } = useLibraryContext(); + const ekirMethod = authMethods.find( + method => method.type === EKIRJASTO_AUTH_TYPE + ); + let ekirjastoToken: string | undefined; + if (ekirMethod && token) { + try { + //Get the ekirjastoToken + const ekirjastoTokenUrl = ekirMethod.links.find( + link => link.rel === "ekirjasto_token" + )?.href; + ekirjastoToken = getEkirjastoToken(token, ekirjastoTokenUrl); + } catch (error) { + //Can not start the reader so should show not logged in or something + } + } + if (!token) { + console.log("There is no token so should be logged out"); + ekirjastoToken = undefined; + } const storageKey = React.useMemo( () => `${MAGAZINE_CONFIG.STORAGE_KEY_PREFIX}${slug ?? "default"}`, @@ -45,12 +65,17 @@ const MagazinesFixedContent: React.FC = () => { const handleMessage = React.useCallback( (e: MessageEvent) => { const allowedOrigin = getMagazineAllowedOrigin(); + + if (!token) { + console.log("No token!"); + } + if (e.origin !== allowedOrigin || typeof e.data !== "string") return; if (e.data === "ewl:unauthorized") { - if (token) { + if (ekirjastoToken) { iframeRef.current?.contentWindow?.postMessage( - `ewl:login:${token}`, + `ewl:login:${ekirjastoToken}`, allowedOrigin ); } else { @@ -72,7 +97,7 @@ const MagazinesFixedContent: React.FC = () => { }); } }, - [initLogin, token, storageKey] + [initLogin, ekirjastoToken, token, storageKey] ); React.useEffect(() => {