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

Automatically renew auth token #141

Merged
merged 1 commit into from
Sep 8, 2024
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
8 changes: 1 addition & 7 deletions packages/ilmomasiina-frontend/src/api.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import { ApiError, apiFetch, FetchOptions } from "@tietokilta/ilmomasiina-components";
import { ErrorCode } from "@tietokilta/ilmomasiina-models";
import { loginExpired, renewLogin } from "./modules/auth/actions";
import { loginExpired } from "./modules/auth/actions";
import { AccessToken } from "./modules/auth/types";
import type { DispatchAction } from "./store/types";

interface AdminApiFetchOptions extends FetchOptions {
accessToken?: AccessToken;
}

const RENEW_LOGIN_THRESHOLD = 5 * 60 * 1000;

/** Wrapper for apiFetch that checks for Unauthenticated responses and dispatches a loginExpired
* action if necessary.
*/
Expand All @@ -23,10 +21,6 @@ export default async function adminApiFetch<T = unknown>(
if (!accessToken) {
throw new ApiError(401, { isUnauthenticated: true });
}
// Renew token asynchronously if it's expiring soon
if (Date.now() > accessToken.expiresAt - RENEW_LOGIN_THRESHOLD) {
dispatch(renewLogin(accessToken.token));
}
return await apiFetch<T>(uri, {
...opts,
headers: { ...opts.headers, Authorization: accessToken.token },
Expand Down
17 changes: 15 additions & 2 deletions packages/ilmomasiina-frontend/src/containers/AuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@
import React, { PropsWithChildren } from "react";
import React, { PropsWithChildren, useEffect } from "react";

import { AuthContext } from "@tietokilta/ilmomasiina-components";
import { useTypedSelector } from "../store/reducers";
import { renewLogin } from "../modules/auth/actions";
import { useTypedDispatch, useTypedSelector } from "../store/reducers";

const LOGIN_RENEW_INTERVAL = 60 * 1000;

const AuthProvider = ({ children }: PropsWithChildren<{}>) => {
const auth = useTypedSelector((state) => state.auth);
const dispatch = useTypedDispatch();

useEffect(() => {
// Renew login immediately on page load if necessary.
dispatch(renewLogin());
// Then, check every minute and renew if necessary.
const timer = window.setInterval(() => dispatch(renewLogin()), LOGIN_RENEW_INTERVAL);
return () => window.clearTimeout(timer);
}, [dispatch]);

return <AuthContext.Provider value={auth}>{children}</AuthContext.Provider>;
};

Expand Down
17 changes: 9 additions & 8 deletions packages/ilmomasiina-frontend/src/modules/auth/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { ApiError, apiFetch } from "@tietokilta/ilmomasiina-components";
import { AdminLoginResponse, ErrorCode } from "@tietokilta/ilmomasiina-models";
import i18n from "../../i18n";
import appPaths from "../../paths";
import type { DispatchAction } from "../../store/types";
import type { DispatchAction, GetState } from "../../store/types";
import { LOGIN_SUCCEEDED, RESET } from "./actionTypes";

export const loginSucceeded = (payload: AdminLoginResponse) =>
Expand Down Expand Up @@ -83,17 +83,18 @@ export const loginExpired = () => (dispatch: DispatchAction) => {
dispatch(redirectToLogin());
};

export const renewLogin = (accessToken: string) => async (dispatch: DispatchAction) => {
const RENEW_LOGIN_THRESHOLD = 5 * 60 * 1000;

export const renewLogin = () => async (dispatch: DispatchAction, getState: GetState) => {
const { accessToken } = getState().auth;
if (!accessToken || Date.now() < accessToken.expiresAt - RENEW_LOGIN_THRESHOLD) return;

try {
if (accessToken) {
const sessionResponse = await apiFetch<AdminLoginResponse>("authentication/renew", {
method: "POST",
body: {
accessToken,
},
headers: {
Authorization: accessToken,
},
body: { accessToken },
headers: { Authorization: accessToken.token },
});
if (sessionResponse) {
dispatch(loginSucceeded(sessionResponse));
Expand Down