Skip to content

Commit

Permalink
fix: Fix token refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
SteveGT96 committed Nov 19, 2024
1 parent 37029d8 commit ffdc8ab
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 16 deletions.
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
49 changes: 33 additions & 16 deletions src/libraries/apiUtils/wrapper.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,49 @@
import { Mutex } from "async-mutex";
import { AUTH_KEY } from "consts";
import { LoginApi } from "generated";
import { saveAuthenticationDataToSession } from "libraries/authUtils/saveAuthenticationDataToSession";
import { refreshTokenHasExpired } from "libraries/authUtils/tokenHasExpired";
import {
refreshTokenHasExpired,
tokenHasExpired,
} from "libraries/authUtils/tokenHasExpired";
import { SessionStorage } from "libraries/storage/storage";
import { Observable, throwError } from "rxjs";
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) => {
const refreshToken = SessionStorage.read(AUTH_KEY)?.refreshToken;
if (
error.status === 401 &&
refreshToken &&
!refreshTokenHasExpired(refreshToken)
) {
return loginApi
.refreshToken({
tokenRefreshRequest: { refreshToken },
})
.pipe(
tap(saveAuthenticationDataToSession),
delay(500),
switchMap(() => callback())
if (error.status === 401) {
const refreshToken = SessionStorage.read(AUTH_KEY)?.refreshToken;
if (
error.status === 401 &&
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);
})
Expand Down

0 comments on commit ffdc8ab

Please sign in to comment.