Skip to content
Merged
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
28 changes: 27 additions & 1 deletion src/auth/ekirjastoFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -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;
}
4 changes: 4 additions & 0 deletions src/auth/useCredentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`,
Expand Down
17 changes: 17 additions & 0 deletions src/components/context/UserContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -22,6 +23,10 @@ export type UserState = {
authenticationUrl: string | undefined
) => void;
signOut: () => void;
getEkirjastoToken: (
token: string,
fetchUrl: string | undefined
) => Promise<string>;
setBook: (book: AnyBook, id?: string) => void;
error: any;
token: string | undefined;
Expand Down Expand Up @@ -117,6 +122,17 @@ export const UserProvider = ({ children }: UserProviderProps) => {
}
);

async function getEkirjastoToken(
token: string,
fetchUrl: string | undefined
): Promise<string> {
const { token: ekirjastoToken } = await fetchEkirjastoToken(
fetchUrl,
token
);
return ekirjastoToken;
}

function signIn(
token: string | Token,
method: AppAuthMethod,
Expand Down Expand Up @@ -160,6 +176,7 @@ export const UserProvider = ({ children }: UserProviderProps) => {
refetchLoans: mutate,
signIn,
signOut,
getEkirjastoToken,
setBook,
error,
token: stringifyToken(credentials),
Expand Down
2 changes: 1 addition & 1 deletion src/config/magazines.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
35 changes: 30 additions & 5 deletions src/pages/[library]/magazines/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLIFrameElement | null>(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"}`,
Expand All @@ -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 {
Expand All @@ -72,7 +97,7 @@ const MagazinesFixedContent: React.FC = () => {
});
}
},
[initLogin, token, storageKey]
[initLogin, ekirjastoToken, token, storageKey]
);

React.useEffect(() => {
Expand Down
Loading