Skip to content

Commit a0b0e18

Browse files
Add token fetch and enable magazine opening
1 parent ba4c3e2 commit a0b0e18

File tree

5 files changed

+81
-8
lines changed

5 files changed

+81
-8
lines changed

src/auth/ekirjastoFetch.ts

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,19 @@ export async function fetchEAuthToken(
88
url: string | undefined,
99
token: string | undefined
1010
) {
11-
if (!url) {
11+
if (!url || !token) {
1212
throw new ApplicationError({
1313
title: "Incomplete Authentication Info",
1414
detail: "No URL or Token was provided for authentication"
1515
});
1616
}
1717

18+
//If in some case, the bearer text is present, remove it so there is no repetition in the request
19+
if (token?.startsWith("Bearer ")) {
20+
token = token.replace("Bearer ", "")
21+
console.log(token)
22+
}
23+
1824
const response = await fetchWithHeaders(url, `Bearer ${token}`, {}, "POST");
1925
const json = await response.json();
2026

@@ -24,3 +30,24 @@ export async function fetchEAuthToken(
2430

2531
return json;
2632
}
33+
34+
export async function fetchEkirjastoToken(
35+
url: string | undefined,
36+
token: string | undefined
37+
) {
38+
if (!url || !token) {
39+
throw new ApplicationError({
40+
title: "Incomplete Authentication Info",
41+
detail: "No URL or Token was provided for authentication"
42+
});
43+
}
44+
45+
const response = await fetchWithHeaders(url, token, {}, "GET");
46+
const json = await response.json();
47+
48+
if (!response.ok) {
49+
throw new ServerError(url, response.status, json);
50+
}
51+
52+
return json;
53+
}

src/auth/useCredentials.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,10 @@ function getCredentialsCookie(
113113
if (librarySlug === "ekirjasto") {
114114
// Get access token, for ekirjasto login credentials
115115
const accessToken = Cookie.get(cookieNameEkirjasto());
116+
if(!accessToken) {
117+
console.log("No access token")
118+
return undefined
119+
}
116120
// Create ekirjasto authentication credentials
117121
const authCredentials: AuthCredentials = {
118122
token: `Bearer ${accessToken}`,

src/components/context/UserContext.tsx

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@ import useCredentials from "auth/useCredentials";
33
import useLibraryContext from "components/context/LibraryContext";
44
import { fetchCollection } from "dataflow/opds1/fetch";
55
import { ServerError } from "errors";
6-
import { AppAuthMethod, AnyBook, AuthCredentials, Token } from "interfaces";
6+
import { AppAuthMethod, AnyBook, AuthCredentials, Token, ClientEkirjastoMethod } from "interfaces";
77
import * as React from "react";
88
import useSWR from "swr";
99
import { BasicTokenAuthType, EkirjastoAuthType } from "types/opds1";
1010
import { addHours, isBefore } from "date-fns";
11+
import { fetchEkirjastoToken } from "auth/ekirjastoFetch";
1112

1213
type Status = "authenticated" | "loading" | "unauthenticated";
1314
export type UserState = {
@@ -22,6 +23,10 @@ export type UserState = {
2223
authenticationUrl: string | undefined
2324
) => void;
2425
signOut: () => void;
26+
getEkirjastoToken: (
27+
token: string,
28+
fetchUrl: string | undefined
29+
) => Promise<string>;
2530
setBook: (book: AnyBook, id?: string) => void;
2631
error: any;
2732
token: string | undefined;
@@ -116,6 +121,14 @@ export const UserProvider = ({ children }: UserProviderProps) => {
116121
}
117122
}
118123
);
124+
125+
async function getEkirjastoToken(
126+
token: string,
127+
fetchUrl: string | undefined
128+
) : Promise<string> {
129+
const { token : ekirjastoToken} = await fetchEkirjastoToken(fetchUrl, token)
130+
return ekirjastoToken
131+
}
119132

120133
function signIn(
121134
token: string | Token,
@@ -160,6 +173,7 @@ export const UserProvider = ({ children }: UserProviderProps) => {
160173
refetchLoans: mutate,
161174
signIn,
162175
signOut,
176+
getEkirjastoToken,
163177
setBook,
164178
error,
165179
token: stringifyToken(credentials),

src/config/magazines.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,5 +73,5 @@ export const MAGAZINE_CONFIG = {
7373

7474
// Default iframe sandbox permissions
7575
IFRAME_SANDBOX:
76-
"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"
76+
"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation"
7777
} as const;

src/pages/[library]/magazines/index.tsx

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,41 @@ import withAppProps, { AppProps } from "dataflow/withAppProps";
1010
import useUser from "components/context/UserContext";
1111
import useLogin from "auth/useLogin";
1212
import useLibraryContext from "components/context/LibraryContext";
13+
import useCredentials from "auth/useCredentials";
1314
import {
1415
getMagazineReaderUrl,
1516
getMagazineAllowedOrigin,
1617
MAGAZINE_CONFIG
1718
} from "config/magazines";
1819
import Head from "next/head";
1920
import BreadcrumbBar from "components/BreadcrumbBar";
21+
import { EkirjastoAuthType } from "types/opds1";
22+
import { EKIRJASTO_AUTH_TYPE } from "utils/constants";
2023

2124
const MagazinesFixedContent: React.FC = () => {
2225
const iframeRef = React.useRef<HTMLIFrameElement | null>(null);
23-
const { token } = useUser();
26+
const { token, signIn, getEkirjastoToken } = useUser();
2427
const { initLogin } = useLogin();
25-
const { slug } = useLibraryContext();
28+
const { slug, authMethods } = useLibraryContext();
29+
const { credentials, setCredentials, clearCredentials } = useCredentials(
30+
slug,
31+
authMethods
32+
);
33+
const ekirMethod = authMethods.find(method => method.type === EKIRJASTO_AUTH_TYPE)
34+
let ekirjastoToken: string | undefined
35+
if (ekirMethod && token) {
36+
try {
37+
//Get the ekirjastoToken
38+
const ekirjastoTokenUrl = ekirMethod.links.find(link => link.rel === "ekirjasto_token")?.href
39+
ekirjastoToken = getEkirjastoToken(token, ekirjastoTokenUrl)
40+
} catch (error) {
41+
//Can not start the reader so should show not logged in or something
42+
}
43+
}
44+
if (!token) {
45+
console.log("There is no token so should be logged out")
46+
ekirjastoToken = undefined
47+
}
2648

2749
const storageKey = React.useMemo(
2850
() => `${MAGAZINE_CONFIG.STORAGE_KEY_PREFIX}${slug ?? "default"}`,
@@ -45,12 +67,18 @@ const MagazinesFixedContent: React.FC = () => {
4567
const handleMessage = React.useCallback(
4668
(e: MessageEvent) => {
4769
const allowedOrigin = getMagazineAllowedOrigin();
70+
71+
if (!token) {
72+
console.log("No token!")
73+
74+
}
75+
4876
if (e.origin !== allowedOrigin || typeof e.data !== "string") return;
4977

5078
if (e.data === "ewl:unauthorized") {
51-
if (token) {
79+
if (ekirjastoToken) {
5280
iframeRef.current?.contentWindow?.postMessage(
53-
`ewl:login:${token}`,
81+
`ewl:login:${ekirjastoToken}`,
5482
allowedOrigin
5583
);
5684
} else {
@@ -72,7 +100,7 @@ const MagazinesFixedContent: React.FC = () => {
72100
});
73101
}
74102
},
75-
[initLogin, token, storageKey]
103+
[initLogin, ekirjastoToken, storageKey]
76104
);
77105

78106
React.useEffect(() => {

0 commit comments

Comments
 (0)