Skip to content

Commit

Permalink
Added ServiceWorker
Browse files Browse the repository at this point in the history
  • Loading branch information
sergesoroka committed Oct 16, 2024
1 parent 80f226c commit 64b36fb
Show file tree
Hide file tree
Showing 9 changed files with 253 additions and 20 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_BaseURL="https://api-test.ramanchada.ideaconsult.net/"
88 changes: 84 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@radix-ui/react-slot": "^1.0.2",
"@react-keycloak/web": "^3.4.0",
"@tanstack/react-table": "^8.13.2",
"axios": "^1.7.7",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"easy-autocomplete": "^1.3.5",
Expand Down
44 changes: 44 additions & 0 deletions public/serviceWorker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
let accessToken = "";

self.addEventListener("install", (event) => {
self.skipWaiting();
});

self.addEventListener("activate", (event) => {
event.waitUntil(self.clients.claim());
});

self.addEventListener("message", (event) => {
if (event.data && event.data.type === "TOKEN") {
accessToken = event.data.token;
console.log(accessToken);
}
});

self.addEventListener("fetch", (event) => {
const { request } = event;
const url = new URL(event.request.url);

if (
accessToken &&
url.origin.startsWith("https://") &&
url.origin.endsWith(".ideaconsult.net/template") &&
request.method === "GET" &&
url.origin !== "https://iam.ideaconsult.net" &&
url.origin !== "https://idp.ideaconsult.net" &&
// request.destination === "image" &&
event.request.headers["Authorization"] == undefined
) {
const authRequest = new Request(request, {
headers: new Headers({
...request.headers,
Authorization: `Bearer ${accessToken}`,
}),
mode: "cors",
});
event.respondWith(fetch(authRequest));
console.log("with token");
} else {
console.log("without token");
}
});
34 changes: 18 additions & 16 deletions src/StartScreenComp/StartScreenComp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import useSWR from "swr";

import { fetcher } from "../lib/fetcher";

import useFetch from "../utils/useFetch.jsx";

import {
useIsShosen,
useSetIsShosen,
Expand Down Expand Up @@ -47,13 +49,13 @@ export default function StartScreenComp({}) {

const { keycloak } = useKeycloak();

useEffect(() => {
if (keycloak.authenticated) {
localStorage.setItem("refreshToken", keycloak.refreshToken);
localStorage.setItem("token", keycloak.token);
localStorage.setItem("username", keycloak.tokenParsed.preferred_username);
}
}, [keycloak.authenticated]);
// useEffect(() => {
// if (keycloak.authenticated) {
// localStorage.setItem("refreshToken", keycloak.refreshToken);
// localStorage.setItem("token", keycloak.token);
// localStorage.setItem("username", keycloak.tokenParsed.preferred_username);
// }
// }, [keycloak.authenticated]);

useEffect(() => {
const interval = setInterval(() => {
Expand Down Expand Up @@ -84,20 +86,20 @@ export default function StartScreenComp({}) {

const stored_token = localStorage.getItem("token");

const logoutHandle = () => {
localStorage.removeItem("username");
localStorage.removeItem("token");
localStorage.removeItem("refreshToken");
};
// const logoutHandle = () => {
// localStorage.removeItem("username");
// localStorage.removeItem("token");
// localStorage.removeItem("refreshToken");
// };

const apiUrl = config.apiUrl;

const templateURL = `${apiUrl}/${idShosen}?format=xlsx&project=${projectID}`;

const { data, isLoading, error } = useSWR(`${apiUrl}`, fetcher, {
cachePolicy: "no-cache",
});

// const { data, isLoading, error } = useSWR(`${apiUrl}`, fetcher, {
// cachePolicy: "no-cache",
// });
const { data, isLoading, error } = useFetch(`template`);
const templateData = [];
data &&
data.template.map((item) => {
Expand Down
41 changes: 41 additions & 0 deletions src/main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ import WizardPage from "./pages/WizardPage.tsx";
import PreferencesPage from "./pages/PreferencesPage.tsx";

import { ReactKeycloakProvider } from "@react-keycloak/web";
import { useKeycloak } from "@react-keycloak/web";

import _kc from "./utils/keycloak.js";

import "./index.css";
import { useEffect } from "react";

const router = createBrowserRouter(
[
Expand All @@ -35,6 +37,44 @@ const router = createBrowserRouter(
{ basename: "/templates/" }
);

const Main = () => {
const { keycloak } = useKeycloak();

useEffect(() => {
if (keycloak.authenticated) {
localStorage.setItem("refreshToken", keycloak.refreshToken);
localStorage.setItem("token", keycloak.token);
localStorage.setItem("username", keycloak.tokenParsed.preferred_username);
}
}, [keycloak.authenticated]);

const stored_token = localStorage.getItem("token");
const token = keycloak.token ? keycloak.token : stored_token;

const base_url = import.meta.env.PROD
? "/templates/serviceWorker.js"
: "/serviceWorker.js";

const registerServiceWorker = async () => {
if ("serviceWorker" in navigator) {
try {
const registration = await navigator.serviceWorker.register(base_url, {
scope: "/templates/",
});

await registration.active.postMessage({
type: "TOKEN",
token: token,
});
} catch (error) {
console.log(`Registration failed with ${error}`);
}
}
};

registerServiceWorker();
};

ReactDOM.createRoot(document.getElementById("root")).render(
<ReactKeycloakProvider
authClient={_kc}
Expand All @@ -46,6 +86,7 @@ ReactDOM.createRoot(document.getElementById("root")).render(
}}
>
<React.StrictMode>
<Main />
<RouterProvider router={router} />
</React.StrictMode>
</ReactKeycloakProvider>
Expand Down
2 changes: 2 additions & 0 deletions src/ui/Select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import "./Select.css";
import SearchIcon from "@/IconsComponents/SearchIcon";
import CloseIcon from "@/IconsComponents/CloseIcon";
import useSWR from "swr";
import useFetch from "../utils/useFetch.jsx";
import { fetcher } from "@/lib/fetcher";
import { useSetProjectID } from "../store/store";

Expand All @@ -22,6 +23,7 @@ export default function Select({ url, setProjectName, projectName }) {
revalidateOnFocus: false,
revalidateOnReconnect: false,
});
// const { data, isLoading, error } = useFetch(`template`);

useEffect(
() =>
Expand Down
1 change: 1 addition & 0 deletions src/utils/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// config.ts
const config = {
apiUrl: "https://api-test.ramanchada.ideaconsult.net/template",
baseUrl: "https://api-test.ramanchada.ideaconsult.net/",
};

export default config;
Loading

0 comments on commit 64b36fb

Please sign in to comment.