Skip to content

Commit

Permalink
Added serviceWorker
Browse files Browse the repository at this point in the history
  • Loading branch information
sergesoroka committed Sep 20, 2024
1 parent b818466 commit c9e2efc
Show file tree
Hide file tree
Showing 7 changed files with 111 additions and 60 deletions.
34 changes: 15 additions & 19 deletions components/Header/Header.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,42 +8,38 @@ export default function Header() {
const { keycloak } = useKeycloak()
const navigate = useNavigate();

const [authenticated, setAuthenticated] = useState(false);
const refreshToken = async () => {
try {
await keycloak.updateToken(30);
} catch (error) {
console.error('Failed to refresh token:', error);
}
}



useEffect(() => { refreshToken() }, [])

if (keycloak.authenticated) {
localStorage.setItem("refreshToken", keycloak.refreshToken)
localStorage.setItem("token", keycloak.token)
const userName = keycloak.tokenParsed.preferred_username;
localStorage.setItem("username", userName)
}

const [username, setUsername] = useState(() => localStorage.getItem("username"))

useEffect(() => {
if (keycloak.authenticated) {
const userName = keycloak.tokenParsed.preferred_username;
setUsername(userName)
localStorage.setItem("token", keycloak.token)
console.log("header", keycloak.token);

}
}, [keycloak.authenticated])


const logoutHandle = () => {
localStorage.removeItem("token")

localStorage.removeItem("username")
setIsAuthenticated(false)
}

const stored_token = localStorage.getItem("token")


return (
<div className="logo">
<h1 onClick={() => navigate("/")}>Raman spectra search</h1>
<div className="usersInfo">
<div className="username">{username}</div>
{stored_token ?
<div className="username">{localStorage.getItem("username")}</div>
{keycloak.authenticated ?
<button className="shareBtn" onClick={() => {
keycloak.logout()
logoutHandle()
Expand Down
8 changes: 5 additions & 3 deletions components/SearchComp/SearchComp.jsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
/* eslint-disable react/prop-types */
import { AnimatePresence, motion } from "framer-motion";
import { useState } from "react";
import { useEffect, useState } from "react";
import { ErrorBoundary } from "react-error-boundary";
import { useLocation } from "react-router-dom";
import { useKeycloak } from "@react-keycloak/web";
import useSWR from "swr";
import Chart from "../Chart/Chart";
import SideBarToggle from "../Icons/SideBarToggle";
Expand All @@ -19,14 +20,15 @@ export default function SearchComp({ setDomain }) {
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const domainParams = queryParams.get("domain");

let [open, setOpen] = useState(true);
let [imageSelected, setImageSelected] = useState(
domainParams ? domainParams : ""
);

let isNexusFile = false;



let [reference, setReference] = useState("*");
let [provider, setProvider] = useState("*");
let [pages, setPages] = useState("0");
Expand Down
20 changes: 17 additions & 3 deletions src/main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,31 @@ const router = createBrowserRouter(
{ basename: "/search" }
);

if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('../utils/serviceWorker.js')
.then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch(error => {
console.log('Service Worker registration failed:', error);
});
});
}


ReactDOM.createRoot(document.getElementById("root")).render(
<ReactKeycloakProvider authClient={keycloak}
<ReactKeycloakProvider authClient={keycloak}
initOptions={{
onLoad: 'check-sso',
checkLoginIframe: false,
// Optionally add automatic silent refresh
silentCheckSsoRedirectUri:
window.location.origin + '/silent-check-sso.html',
}}
>
<RouterProvider router={router} />
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
</ReactKeycloakProvider>

);
32 changes: 0 additions & 32 deletions utils/auth.jsx

This file was deleted.

3 changes: 0 additions & 3 deletions utils/fetcher.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ import keycloak from "./keycloak";

const stored_token = localStorage.getItem("token")

console.log("token", keycloak.token);
console.log("stored_token", stored_token);


const fetcher = (url) => fetch(url, {
headers: {
Expand Down
26 changes: 26 additions & 0 deletions utils/serviceWorker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
self.addEventListener('fetch', (e) => {
var url = new URL(e.request.url);
if (
url.origin.endsWith(".ideaconsult.net")
&& (e.request.destination === 'image')
&& isGeneratedImage(url)
&& url.origin.startsWith("https://")
&& (url.origin !== "https://iam.ideaconsult.net")
&& (url.origin !== "https://idp.ideaconsult.net")
&& (e.request.method == "GET")
&& (e.request.headers["Authorization"] == undefined)) {
e.respondWith(localStorage.getItem("token").then((value) => {
var _headers = {};
var header = "Bearer "+value;
_headers["Authorization"] = header;
const newRequest = new Request(e.request, {
headers : {"Authorization" : header},
mode: "cors"
});
return fetch(newRequest);

}) )
} else {
return fetch(e.request);
}
});
48 changes: 48 additions & 0 deletions utils/test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import React, { useEffect, useState } from 'react';
import { useKeycloak } from '@react-keycloak/web';

const App = () => {
const { keycloak } = useKeycloak();
const [token, setToken] = useState(null);
const [isAuthenticated, setIsAuthenticated] = useState(false);

useEffect(() => {
if (keycloak && keycloak.authenticated) {
setIsAuthenticated(true);
setToken(keycloak.token);

const intervalId = setInterval(() => {
if (keycloak.isTokenExpired(30)) {
keycloak.updateToken(30).then((refreshed) => {
if (refreshed) {
console.log('Token automatically refreshed');
setToken(keycloak.token); // Update token state
} else {
console.warn('Token still valid, no need to refresh');
}
}).catch((error) => {
console.error('Failed to refresh token', error);
});
}
}, 60000); // Check every 60 seconds

return () => clearInterval(intervalId); // Cleanup on unmount
}
}, [keycloak]);

return (
<div>
<h1>ReactKeycloakProvider Token Management</h1>
{isAuthenticated ? (
<div>
<p>Authenticated! Token is available.</p>
<pre>{token}</pre>
</div>
) : (
<p>Not authenticated</p>
)}
</div>
);
};

export default App;

0 comments on commit c9e2efc

Please sign in to comment.