Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OH2-433 | Implement token refresh #695

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 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 @@ -16,6 +16,7 @@
"@mui/x-date-pickers": "^7.11.0",
"@redux-devtools/extension": "^3.3.0",
"@reduxjs/toolkit": "^2.2.6",
"async-mutex": "^0.5.0",
"browser-image-compression": "^2.0.2",
"chart.js": "^3.9.1",
"classnames": "^2.2.6",
Expand Down
1 change: 1 addition & 0 deletions src/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export const AUTH_KEY = "auth";
export const PERMISSION_KEY = "permission";
export const MOBILE_BREAKPOINT = 768;
export const TOKEN_EXPIRATION_TIMEOUT = 60000;
export const REFRESH_TOKEN_EXPIRATION_TIMEOUT = 0;

export const PATHS = {
home: "/",
Expand Down
12 changes: 8 additions & 4 deletions src/libraries/apiUtils/applyTokenMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,20 @@ import produce from "immer";
import { set } from "lodash";
import { AUTH_KEY } from "../../consts";
import { Middleware, RequestArgs } from "../../generated";
import { refreshTokenHasExpired } from "../authUtils/tokenHasExpired";
import { SessionStorage } from "../storage/storage";
import { redirect } from "react-router";
import { tokenHasExpired } from "../authUtils/tokenHasExpired";

export const applyTokenMiddleware: Middleware = {
pre(request: RequestArgs): RequestArgs {
const userCredentials = SessionStorage.read(AUTH_KEY);
if (userCredentials.token && tokenHasExpired(userCredentials.token)) {
if (
userCredentials?.refreshToken &&
refreshTokenHasExpired(userCredentials.refreshToken)
) {
SessionStorage.clear();
return redirect("/login");
}
if (!userCredentials) {
window.location.reload();
}
return produce(request, (draft) => {
if (userCredentials.token) {
Expand Down
47 changes: 47 additions & 0 deletions src/libraries/apiUtils/wrapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Mutex } from "async-mutex";
import { AUTH_KEY } from "consts";
import { LoginApi } from "generated";
import { saveAuthenticationDataToSession } from "libraries/authUtils/saveAuthenticationDataToSession";
import {
refreshTokenHasExpired,
tokenHasExpired,
} from "libraries/authUtils/tokenHasExpired";
import { SessionStorage } from "libraries/storage/storage";
import { Observable, from, throwError } from "rxjs";
import { catchError, delay, switchMap, tap } from "rxjs/operators";
import { customConfiguration } from "./configuration";

const mutex = new Mutex();

const loginApi = new LoginApi(customConfiguration(false));

export function wrapper<T>(callback: () => Observable<T>): Observable<T> {
return callback().pipe(
catchError((error) => {
if (error.status === 401) {
const refreshToken = SessionStorage.read(AUTH_KEY)?.refreshToken;
if (refreshToken && !refreshTokenHasExpired(refreshToken)) {
return from(
mutex.runExclusive(async () => {
const token = SessionStorage.read(AUTH_KEY)?.token;
if (token && !tokenHasExpired(token)) {
return callback().toPromise();
}
return loginApi
.refreshToken({
tokenRefreshRequest: { refreshToken },
})
.pipe(
tap(saveAuthenticationDataToSession),
delay(500),
switchMap(() => callback())
)
.toPromise();
})
);
}
}
return throwError(error);
})
);
}
11 changes: 10 additions & 1 deletion src/libraries/authUtils/tokenHasExpired.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import jwtDecode from "jwt-decode";
import { TOKEN_EXPIRATION_TIMEOUT } from "../../consts";
import {
REFRESH_TOKEN_EXPIRATION_TIMEOUT,
TOKEN_EXPIRATION_TIMEOUT,
} from "../../consts";

export interface JwtTokenModel {
exp: number;
Expand All @@ -12,3 +15,9 @@ export const tokenHasExpired = (token: any): boolean => {
const expirationTime = exp * 1000 - TOKEN_EXPIRATION_TIMEOUT;
return Date.now() >= expirationTime;
};

export const refreshTokenHasExpired = (token: any): boolean => {
const { exp } = jwtDecode<JwtTokenModel>(token);
const expirationTime = exp * 1000 - REFRESH_TOKEN_EXPIRATION_TIMEOUT;
return Date.now() >= expirationTime;
};
4 changes: 2 additions & 2 deletions src/routes/MainRouter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import { useAppDispatch, useAppSelector } from "libraries/hooks/redux";
import React, { useEffect } from "react";
import { Navigate, Route, Routes } from "react-router";
import { BrowserRouter } from "react-router-dom";
import { Private } from "../components/Private";
import Dashboard from "../components/accessories/dashboard/Dashboard";
import PermissionDenied from "../components/activities/PermissionDenied/PermissionDenied";
import ForgotActivity from "../components/activities/forgotActivity/ForgotActivity";
import LaboratoryActivity from "../components/activities/laboratoryActivity/LaboratoryActivity";
import LoginActivity from "../components/activities/loginActivity/LoginActivity";
import { RedirectAfterLogin } from "../components/activities/loginActivity/RedirectAfterLogin";
import NotFound from "../components/activities/notFound/NotFound";
import PermissionDenied from "../components/activities/PermissionDenied/PermissionDenied";
import VisitsActivity from "../components/activities/visitsActivity/VisitsActivity";
import { Private } from "../components/Private";
import { PATHS } from "../consts";
import { withPermission } from "../libraries/permissionUtils/withPermission";
import { getUserSettings } from "../state/main";
Expand Down
29 changes: 13 additions & 16 deletions src/state/admissions/thunk.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import { wrapper } from "libraries/apiUtils/wrapper";
import { AdmissionDTO, AdmissionsApi } from "../../generated";
import { customConfiguration } from "../../libraries/apiUtils/configuration";

Expand All @@ -7,17 +8,15 @@ const api = new AdmissionsApi(customConfiguration());
export const createAdmission = createAsyncThunk(
"admissions/CREATE_ADMISSION",
async (admissionDTO: AdmissionDTO, thunkApi) =>
api
.newAdmissions({ admissionDTO })
wrapper(() => api.newAdmissions({ admissionDTO }))
.toPromise()
.catch((error) => thunkApi.rejectWithValue(error.response))
);

export const updateAdmission = createAsyncThunk(
"admissions/UPDATE_ADMISSION",
async (admissionDTO: AdmissionDTO, thunkApi) =>
api
.updateAdmissions({ admissionDTO })
wrapper(() => api.updateAdmissions({ admissionDTO }))
.toPromise()
.catch((error) => thunkApi.rejectWithValue(error.response))
);
Expand All @@ -28,8 +27,7 @@ export const dischargePatient = createAsyncThunk(
payload: { patientCode: number; admissionDTO: AdmissionDTO },
thunkApi
) =>
api
.dischargePatient(payload)
wrapper(() => api.dischargePatient(payload))
.toPromise()
.catch((error) => thunkApi.rejectWithValue(error.response))
);
Expand All @@ -40,12 +38,13 @@ export const getDischarges = createAsyncThunk(
payload: { dischargerange: string[]; page?: number; size?: number },
thunkApi
) =>
api
.getDischarges({
wrapper(() =>
api.getDischarges({
...payload,
page: payload.page ?? 0,
size: payload.size ?? 80,
})
)
.toPromise()
.catch((error) => thunkApi.rejectWithValue(error.response))
);
Expand All @@ -56,21 +55,21 @@ export const getAdmissions = createAsyncThunk(
payload: { admissionrange: string[]; page?: number; size?: number },
thunkApi
) =>
api
.getAdmissions({
wrapper(() =>
api.getAdmissions({
...payload,
page: payload.page ?? 0,
size: payload.size ?? 80,
})
)
.toPromise()
.catch((error) => thunkApi.rejectWithValue(error.response))
);

export const getPatientAdmissions = createAsyncThunk(
"admissions/GET_PATIENT_ADMISSIONS",
async (payload: { patientCode: number }, thunkApi) =>
api
.getAdmissions1(payload)
wrapper(() => api.getAdmissions1(payload))
.toPromise()
.catch((error) => thunkApi.rejectWithValue(error.response))
);
Expand All @@ -85,17 +84,15 @@ export const getAdmittedPatients = createAsyncThunk(
},
thunkApi
) =>
api
.getAdmittedPatients(payload)
wrapper(() => api.getAdmittedPatients(payload))
.toPromise()
.catch((error) => thunkApi.rejectWithValue(error.response))
);

export const getCurrentAdmission = createAsyncThunk(
"admissions/getCurrentAdmission",
async (patientCode: number | undefined, thunkApi) =>
api
.getCurrentAdmission({ patientCode: patientCode ?? -1 })
wrapper(() => api.getCurrentAdmission({ patientCode: patientCode ?? -1 }))
.toPromise()
.catch((error) => thunkApi.rejectWithValue(error.response))
);
Loading