Skip to content

Commit

Permalink
Added auth with react-oidc-context
Browse files Browse the repository at this point in the history
  • Loading branch information
sergesoroka committed Nov 18, 2024
1 parent 2f072ad commit 04df611
Show file tree
Hide file tree
Showing 9 changed files with 56 additions and 189 deletions.
57 changes: 23 additions & 34 deletions components/Header/Header.jsx
Original file line number Diff line number Diff line change
@@ -1,48 +1,37 @@
import { useAuth } from "react-oidc-context";
import { useNavigate } from "react-router-dom";

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

export default function Header() {
const { keycloak } = useKeycloak();
const auth = useAuth();
const navigate = useNavigate();

const username = keycloak.tokenParsed?.preferred_username
? keycloak.tokenParsed?.preferred_username
: localStorage.getItem("username");

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

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

return (
<div className="logo">
<h1 onClick={() => navigate("/")}>Raman spectra search</h1>
<div className="usersInfo">
<div className="username">
{keycloak.authenticated || username ? username : ""}
</div>
{keycloak.authenticated || stored_token ? (
<button
className="shareBtn"
onClick={() => {
navigate("/");
keycloak.logout();
logoutHandle();
}}
>
Log out
</button>
<div className="helpUserMenu">
{/* <Link
to="https://zenodo.org/records/14163315"
target="_blank"
rel="noopener noreferrer"
>
<button className="shareBtn">Help</button>
</Link> */}
{auth.isAuthenticated ? (
<div className="userInfo">
<p className="userName">{auth.user?.profile.name}</p>
<button
className="shareBtn"
style={{ marginLeft: "18px" }}
onClick={() => void auth.removeUser()}
>
Log out
</button>
</div>
) : (
<button
className="shareBtn"
onClick={() => {
navigate("/");
keycloak.login();
}}
style={{ marginLeft: "18px" }}
onClick={() => void auth.signinRedirect()}
>
Log in
</button>
Expand Down
11 changes: 0 additions & 11 deletions components/SearchComp/SearchComp.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,6 @@ export default function SearchComp({ setDomain }) {

const [file, setFile] = useState(null);

// const searchQuery = `${
// import.meta.env.VITE_BaseURL
// }db/query?q=${qQuery}&img=thumbnail&query_type=text&q_reference=${reference}&q_provider=${provider}&q_instrument=${instrument}&q_wavelength=${wavelengths}&page=${pages}&pagesize=${pagesize}`;

// const fileSearchQuery = `${
// import.meta.env.VITE_BaseURL
// }db/query?q=${qQuery}&img=thumbnail&query_type=${type}&q_reference=${reference}&q_provider=${provider}&q_instrument=${instrument}&q_wavelength=${wavelengths}&page=${pages}&pagesize=${pagesize}&ann=${
// imageData?.cdf
// }`;

const searchUrlPath = `db/query?q=${qQuery}&img=thumbnail&query_type=text&q_reference=${reference}&q_provider=${provider}&q_instrument=${instrument}&q_wavelength=${wavelengths}&page=${pages}&pagesize=${pagesize}`;

const fileSearchUrlPath = `db/query?q=${qQuery}&img=thumbnail&query_type=${type}&q_reference=${reference}&q_provider=${provider}&q_instrument=${instrument}&q_wavelength=${wavelengths}&page=${pages}&pagesize=${pagesize}&ann=${imageData?.cdf}`;
Expand All @@ -62,7 +52,6 @@ export default function SearchComp({ setDomain }) {
<div>
<div className="toggleSidebar" onClick={() => setOpen(!open)}>
<SideBarToggle />
{/* <h1>Raman Spectra Search</h1> */}
</div>
<AnimatePresence>
{open && (
Expand Down
12 changes: 0 additions & 12 deletions components/UploadFile/UploadFile.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,15 @@ import { useEffect, useState } from "react";
import Close from "../Icons/Close";
import Spinner from "../Icons/Spinner";

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

// eslint-disable-next-line react/prop-types
export default function UploadFile({ setImageData, setType, file, setFile }) {
const fileQuery = `${import.meta.env.VITE_BaseURL}db/download?what=knnquery`;

const [isNotRightFile, setIsNotRightFile] = useState(false);
const [isLoading, setIsLoading] = useState(false);

const { keycloak } = useKeycloak();

useEffect(() => {
async function fetchDate() {
try {
await keycloak.updateToken(30);
console.log("Upload file Comp: UPDATED");
localStorage.setItem("token", keycloak.token);
} catch (error) {
console.error("Upload file Comp: Failed to refresh token:", error);
}

const formData = new FormData();
formData.append("files", file);

Expand Down
3 changes: 0 additions & 3 deletions public/serviceWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ self.addEventListener("activate", (event) => {
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "TOKEN") {
accessToken = event.data.token;
console.log(accessToken);
}
});

Expand All @@ -37,8 +36,6 @@ self.addEventListener("fetch", (event) => {
mode: "cors",
});
event.respondWith(fetch(authRequest));
console.log("with token");
} else {
console.log("without token");
}
});
54 changes: 1 addition & 53 deletions src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import "./App.css";
import { useEffect, useState } from "react";
import { useState } from "react";
import { useLocation } from "react-router-dom";

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

import { lazy } from "react";

import { useAuth } from "react-oidc-context";

const H5web = lazy(() => import("../components/h5web/h5web"));

import SearchComp from "../components/SearchComp/SearchComp";
Expand All @@ -23,54 +19,6 @@ function App() {

let [domain, setDomain] = useState(null);

const { keycloak } = useKeycloak();
const auth = useAuth();

console.log(auth);

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 handleFocus = () => {
console.log("on focus");
keycloak
.updateToken(30)
.then((refreshed) => {
if (refreshed) {
console.log(
"App on focus: Token refreshed and updated in localStorage.",
keycloak.token
);
localStorage.setItem("token", keycloak.token);
} else {
console.log("app: Token is still valid.");
}
})
.catch(() => {
console.error("App on focus: Failed to refresh token.");
// keycloak.logout();
});
};

const handleBlur = () => {
console.log("blur");
};

window.addEventListener("focus", handleFocus);
window.addEventListener("blur", handleBlur);

return () => {
window.removeEventListener("focus", handleFocus);
window.removeEventListener("blur", handleBlur);
};
});

return (
<>
<Header />
Expand Down
11 changes: 11 additions & 0 deletions src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@ button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}

.userInfo {
display: flex;
justify-content: flex-end;
align-items: center;
}

.userName {
font-size: 0.9rem;
font-weight: 600;
}

@media (prefers-color-scheme: light) {
:root {
color: #213547;
Expand Down
45 changes: 16 additions & 29 deletions src/main.jsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
import React, { useEffect, useState } from "react";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { AuthProvider } from "react-oidc-context";
import { ReactKeycloakProvider } from "@react-keycloak/web";
import { useAuth } from "react-oidc-context";

import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import "./index.css";

import _kc from "../utils/keycloak.jsx";
import { useKeycloak } from "@react-keycloak/web";

const oidcConfig = {
authority: "https://iam.ideaconsult.net/auth",
authority: "https://iam.ideaconsult.net/auth/realms/nano",
client_id: "idea-ui",
client_secret: "idea-ui",
redirect_uri: window.location.origin,
response_type: "code", // or 'token' for implicit flow
scope: "openid profile email", // Adjust according to your needs
post_logout_redirect_uri: window.location.origin,
redirect_uri: "http://localhost:5173/search/",
response_type: "code",
scope: "openid profile email",
};

const router = createBrowserRouter(
Expand All @@ -31,10 +26,9 @@ const router = createBrowserRouter(
);

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

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

const base_url = import.meta.env.PROD
? "/search/serviceWorker.js"
Expand Down Expand Up @@ -69,22 +63,15 @@ const Main = () => {
}, [token]);
return <></>;
};
function onSigninCallback() {
window.location.href = "/";
}

ReactDOM.createRoot(document.getElementById("root")).render(
<ReactKeycloakProvider
authClient={_kc}
initOptions={{
onLoad: "check-sso",
checkLoginIframe: false,
silentCheckSsoRedirectUri:
window.location.origin + "/silent-check-sso.html",
}}
>
<AuthProvider {...oidcConfig}>
<React.StrictMode>
<Main />
<RouterProvider router={router} />
</React.StrictMode>
</AuthProvider>
</ReactKeycloakProvider>
<AuthProvider {...oidcConfig} onSigninCallback={onSigninCallback}>
<React.StrictMode>
<Main />
<RouterProvider router={router} />
</React.StrictMode>
</AuthProvider>
);
14 changes: 0 additions & 14 deletions utils/keycloak.jsx

This file was deleted.

38 changes: 5 additions & 33 deletions utils/useFetch.jsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
import { useState, useEffect } from "react";
import { useKeycloak } from "@react-keycloak/web";
import { useAuth } from "react-oidc-context";
import axios from "axios";
import { useNavigate } from "react-router-dom";

function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [accessToken, setAccessToken] = useState(null);
const [auth, setAuth] = useState(false);

const { keycloak } = useKeycloak();
const navigate = useNavigate();
const auth = useAuth();

const stored_token = localStorage.getItem("token");
const kc_token = keycloak.token ? keycloak.token : stored_token;
const kc_token = auth?.user?.access_token;

const axiosInstance = axios.create({
baseURL: `${import.meta.env.VITE_BaseURL}`,
Expand All @@ -25,7 +20,6 @@ function useFetch(url) {
function (config) {
if (kc_token) {
config.headers.Authorization = `Bearer ${kc_token}`;
console.log("axios interseption");
}
return config;
},
Expand All @@ -35,44 +29,22 @@ function useFetch(url) {
);

useEffect(() => {
if (keycloak.authenticated) {
setAccessToken(keycloak.token);
setAuth(true);
}

if (kc_token) {
keycloak
.updateToken(30)
.then((refreshed) => {
if (refreshed) {
console.log(
"useFetch: Token refreshed and updated in localStorage."
);
localStorage.setItem("token", keycloak.token);
} else {
console.log("useFetch: Token is still valid.");
}
})
.catch(() => {
console.error("useFetch: Failed to refresh token.");
});
axiosInstance
.get(url)
.then((response) => {
setData(response.data);
})
.catch((error) => {
// navigate("/");
// keycloak.login();
console.error("Error fetching data:", error);
})
.finally(() => {
setLoading(false);
});
}
}, [kc_token, url, keycloak]);
}, [kc_token, url]);

return { data, loading, auth };
return { data, loading };
}

export default useFetch;

0 comments on commit 04df611

Please sign in to comment.