Skip to content

Commit

Permalink
Auto sign out when care_access_token is no longer present in local …
Browse files Browse the repository at this point in the history
…storage. (#5021)

* fixes #4836

* fixes #5024
  • Loading branch information
rithviknishad committed Mar 6, 2023
1 parent 9484f9d commit 6761e6b
Show file tree
Hide file tree
Showing 9 changed files with 54 additions and 29 deletions.
11 changes: 6 additions & 5 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import axios from "axios";
import { HistoryAPIProvider } from "./CAREUI/misc/HistoryAPIProvider";
import * as Sentry from "@sentry/browser";
import { IConfig } from "./Common/hooks/useConfig";
import { LocalStorageKeys } from "./Common/constants";

const Loading = loadable(() => import("./Components/Common/Loading"));

Expand All @@ -35,10 +36,10 @@ const App: React.FC = () => {
}, [dispatch]);

const updateRefreshToken = () => {
const refresh = localStorage.getItem("care_refresh_token");
const access = localStorage.getItem("care_access_token");
const refresh = localStorage.getItem(LocalStorageKeys.refreshToken);
const access = localStorage.getItem(LocalStorageKeys.accessToken);
if (!access && refresh) {
localStorage.removeItem("care_refresh_token");
localStorage.removeItem(LocalStorageKeys.refreshToken);
document.location.reload();
return;
}
Expand All @@ -50,8 +51,8 @@ const App: React.FC = () => {
refresh,
})
.then((resp) => {
localStorage.setItem("care_access_token", resp.data.access);
localStorage.setItem("care_refresh_token", resp.data.refresh);
localStorage.setItem(LocalStorageKeys.accessToken, resp.data.access);
localStorage.setItem(LocalStorageKeys.refreshToken, resp.data.refresh);
});
};
useEffect(() => {
Expand Down
8 changes: 8 additions & 0 deletions src/Common/constants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ export const KeralaLogo = "images/kerala-logo.png";

export const RESULTS_PER_PAGE_LIMIT = 14;
export const PAGINATION_LIMIT = 36;

/**
* Contains local storage keys that are potentially used in multiple places.
*/
export const LocalStorageKeys = {
accessToken: "care_access_token",
refreshToken: "care_refresh_token",
};
export interface OptionsType {
id: number;
text: string;
Expand Down
8 changes: 6 additions & 2 deletions src/Components/Assets/AssetImportModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ import { useDispatch } from "react-redux";
import { Link } from "raviger";
import SelectMenuV2 from "../Form/SelectMenuV2";
import readXlsxFile from "read-excel-file";
import { XLSXAssetImportSchema } from "../../Common/constants";
import {
LocalStorageKeys,
XLSXAssetImportSchema,
} from "../../Common/constants";
import { parseCsvFile } from "../../Utils/utils";
import useConfig from "../../Common/hooks/useConfig";

Expand Down Expand Up @@ -133,7 +136,8 @@ const AssetImportModal = ({ open, onClose, facility }: Props) => {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + localStorage.getItem("care_access_token"),
Authorization:
"Bearer " + localStorage.getItem(LocalStorageKeys.accessToken),
},
body: asset_data,
});
Expand Down
5 changes: 3 additions & 2 deletions src/Components/Auth/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import LanguageSelectorLogin from "../Common/LanguageSelectorLogin";
import CareIcon from "../../CAREUI/icons/CareIcon";
import useConfig from "../../Common/hooks/useConfig";
import { classNames } from "../../Utils/utils";
import { LocalStorageKeys } from "../../Common/constants";

export const Login = (props: { forgot?: boolean }) => {
const {
Expand Down Expand Up @@ -105,8 +106,8 @@ export const Login = (props: { forgot?: boolean }) => {
// captcha displayed set back to login button
setLoading(false);
} else if (res && statusCode === 200) {
localStorage.setItem("care_access_token", res.access);
localStorage.setItem("care_refresh_token", res.refresh);
localStorage.setItem(LocalStorageKeys.accessToken, res.access);
localStorage.setItem(LocalStorageKeys.refreshToken, res.refresh);

if (
window.location.pathname === "/" ||
Expand Down
3 changes: 2 additions & 1 deletion src/Components/Auth/ResetPassword.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import ExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails";
import { postResetPassword, checkResetToken } from "../../Redux/actions";
import { navigate } from "raviger";
import { useTranslation } from "react-i18next";
import { LocalStorageKeys } from "../../Common/constants";

const panelStyles = makeStyles((theme: Theme) =>
createStyles({
Expand Down Expand Up @@ -84,7 +85,7 @@ export const ResetPassword = (props: any) => {
dispatch(postResetPassword(valid)).then((resp: any) => {
const res = resp && resp.data;
if (res && res.status === "OK") {
localStorage.removeItem("care_access_token");
localStorage.removeItem(LocalStorageKeys.accessToken);
Notification.Success({
msg: t("password_reset_success"),
});
Expand Down
3 changes: 2 additions & 1 deletion src/Components/Facility/CoverImageEditModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import useWindowDimensions from "../../Common/hooks/useWindowDimensions";
import CareIcon from "../../CAREUI/icons/CareIcon";
import * as Notification from "../../Utils/Notifications.js";
import { useTranslation } from "react-i18next";
import { LocalStorageKeys } from "../../Common/constants";
interface Props {
open: boolean;
onClose: (() => void) | undefined;
Expand Down Expand Up @@ -116,7 +117,7 @@ const CoverImageEditModal = ({
headers: {
"Content-Type": "multipart/form-data",
Authorization:
"Bearer " + localStorage.getItem("care_access_token"),
"Bearer " + localStorage.getItem(LocalStorageKeys.accessToken),
},
}
);
Expand Down
25 changes: 13 additions & 12 deletions src/Redux/fireRequest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import axios from "axios";
import api from "./api";
import * as Notification from "../Utils/Notifications.js";
import { isEmpty, omitBy } from "lodash";
import { LocalStorageKeys } from "../Common/constants";
const requestMap: any = api;
export const actions = {
FETCH_REQUEST: "FETCH_REQUEST",
Expand Down Expand Up @@ -89,9 +90,9 @@ export const fireRequest = (
const config: any = {
headers: {},
};
if (!request.noAuth && localStorage.getItem("care_access_token")) {
if (!request.noAuth && localStorage.getItem(LocalStorageKeys.accessToken)) {
config.headers["Authorization"] =
"Bearer " + localStorage.getItem("care_access_token");
"Bearer " + localStorage.getItem(LocalStorageKeys.accessToken);
}
const axiosApiCall: any = axios.create(config);

Expand Down Expand Up @@ -124,8 +125,8 @@ export const fireRequest = (
// currentUser is ignored because on the first page load
// 403 error is displayed for invalid credential.
if (error.response.status === 403 && key === "currentUser") {
if (localStorage.getItem("care_access_token")) {
localStorage.removeItem("care_access_token");
if (localStorage.getItem(LocalStorageKeys.accessToken)) {
localStorage.removeItem(LocalStorageKeys.accessToken);
}
return;
}
Expand Down Expand Up @@ -209,9 +210,9 @@ export const fireRequestV2 = (
const config: any = {
headers: {},
};
if (!request.noAuth && localStorage.getItem("care_access_token")) {
if (!request.noAuth && localStorage.getItem(LocalStorageKeys.accessToken)) {
config.headers["Authorization"] =
"Bearer " + localStorage.getItem("care_access_token");
"Bearer " + localStorage.getItem(LocalStorageKeys.accessToken);
}
const axiosApiCall: any = axios.create(config);

Expand Down Expand Up @@ -241,8 +242,8 @@ export const fireRequestV2 = (
// currentUser is ignored because on the first page load
// 403 error is displayed for invalid credential.
if (error.response.status === 403 && key === "currentUser") {
if (localStorage.getItem("care_access_token")) {
localStorage.removeItem("care_access_token");
if (localStorage.getItem(LocalStorageKeys.accessToken)) {
localStorage.removeItem(LocalStorageKeys.accessToken);
}
}

Expand Down Expand Up @@ -322,9 +323,9 @@ export const fireRequestForFiles = (
};
// Content-Type: application/pdf
// Content-Disposition: inline; filename="filename.pdf"
if (!request.noAuth && localStorage.getItem("care_access_token")) {
if (!request.noAuth && localStorage.getItem(LocalStorageKeys.accessToken)) {
config.headers["Authorization"] =
"Bearer " + localStorage.getItem("care_access_token");
"Bearer " + localStorage.getItem(LocalStorageKeys.accessToken);
}
const axiosApiCall: any = axios.create(config);

Expand All @@ -349,8 +350,8 @@ export const fireRequestForFiles = (
// currentUser is ignored because on the first page load
// 403 error is displayed for invalid credential.
if (error.response.status === 403 && key === "currentUser") {
if (localStorage.getItem("care_access_token")) {
localStorage.removeItem("care_access_token");
if (localStorage.getItem(LocalStorageKeys.accessToken)) {
localStorage.removeItem(LocalStorageKeys.accessToken);
}
return;
}
Expand Down
11 changes: 10 additions & 1 deletion src/Router/AppRouter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,10 @@ import {
DesktopSidebar,
MobileSidebar,
} from "../Components/Common/Sidebar/Sidebar";
import { BLACKLISTED_PATHS } from "../Common/constants";
import { BLACKLISTED_PATHS, LocalStorageKeys } from "../Common/constants";
import { UpdateFacilityMiddleware } from "../Components/Facility/UpdateFacilityMiddleware";
import useConfig from "../Common/hooks/useConfig";
import { handleSignOut } from "../Utils/utils";

const routes = {
"/hub": () => <HubDashboard />,
Expand Down Expand Up @@ -385,6 +386,14 @@ export default function AppRouter() {
const path = usePath();
const [sidebarOpen, setSidebarOpen] = useState(false);

useEffect(() => {
addEventListener("storage", (event: any) => {
if (event.key === LocalStorageKeys.accessToken && !event.newValue) {
handleSignOut(true);
}
});
}, []);

useEffect(() => {
setSidebarOpen(false);
let flag = false;
Expand Down
9 changes: 4 additions & 5 deletions src/Utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import moment from "moment";
import { navigate } from "raviger";
import { LocalStorageKeys } from "../Common/constants";

interface ApacheParams {
age: number;
Expand Down Expand Up @@ -81,11 +82,9 @@ export const relativeDate = (date: string | Date) => {
export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

export const handleSignOut = (forceReload: boolean) => {
localStorage.removeItem("care_access_token");
localStorage.removeItem("care_refresh_token");
localStorage.removeItem("shift-filters");
localStorage.removeItem("external-filters");
localStorage.removeItem("lsg-ward-data");
Object.values(LocalStorageKeys).forEach((key) =>
localStorage.removeItem(key)
);
navigate("/");
if (forceReload) window.location.reload();
};
Expand Down

0 comments on commit 6761e6b

Please sign in to comment.