The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Convert enterprise auth session middleware to TypeScript (#77399)
Andrei Chernykh5340d25eea11
diff --git a/enterprise/frontend/src/metabase-enterprise/application_permissions/reducer.ts b/enterprise/frontend/src/metabase-enterprise/application_permissions/reducer.tsindex 99e959d3f55..b6c95faf6c8 100644--- a/enterprise/frontend/src/metabase-enterprise/application_permissions/reducer.ts+++ b/enterprise/frontend/src/metabase-enterprise/application_permissions/reducer.ts@@ -80,6 +80,8 @@ const SAVE_APPLICATION_PERMISSIONS =export const saveApplicationPermissions = createThunkAction(SAVE_APPLICATION_PERMISSIONS,() => async (dispatch, getState) => {+ // getState() is typed as the base State, which doesn't include the+ // enterprise plugin slice this reducer registers at runtime.const { applicationPermissions, applicationPermissionsRevision } = (getState() as ApplicationPermissionsState).plugins.applicationPermissionsPlugin;diff --git a/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.js b/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.jsdeleted file mode 100644index 8528a0a06cb..00000000000--- a/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.js+++ /dev/null@@ -1,72 +0,0 @@-import Cookies from "js-cookie";--import { logout, refreshSession } from "metabase/redux/auth";-import { replace } from "metabase/router";-import { isSameOrSiteUrlOrigin } from "metabase/utils/dom";--export const SESSION_KEY = "metabase.TIMEOUT";-export const COOKIE_POOLING_TIMEOUT = 3000;-const getIsLoggedIn = () => typeof Cookies.get(SESSION_KEY) !== "undefined";--const getRedirectUrl = () => {- const params = new URLSearchParams(window.location.search);- const redirectUrlParam = params.get("redirect");-- return redirectUrlParam != null && isSameOrSiteUrlOrigin(redirectUrlParam)- ? redirectUrlParam- : null;-};--const preventImmedidateRedirect = () => {- // defer to login page to redirect if sent directly. `getIsLoggedIn` returns if a session cookie- // is present, but does not validate. in the case of an invalid token at the start of an OAuth- // flow, the user can get stuck with a "Account linking requires an authenticated session" error- // without an obvious way to remedy. by defering the the login page we can ensure cookie validation- // and give the user a chance to re-auth if needed.- return window.location.pathname.startsWith("/auth/login");-};--export const createSessionMiddleware = (- resetActions = [],- setInterval = global.setInterval,-) => {- let intervalId;-- const sessionMiddlware = (store) => (next) => (action) => {- if (intervalId == null || resetActions.includes(action.type)) {- clearInterval(intervalId);-- let wasLoggedIn = getIsLoggedIn();-- // get the redirect url before refreshing the session because after the refresh the url will be reset- const redirectUrl = getRedirectUrl();-- if (wasLoggedIn && !!redirectUrl && !preventImmedidateRedirect()) {- store.dispatch(replace(redirectUrl));- }-- intervalId = setInterval(async () => {- const isLoggedIn = getIsLoggedIn();-- if (isLoggedIn !== wasLoggedIn) {- wasLoggedIn = isLoggedIn;-- if (isLoggedIn) {- await store.dispatch(refreshSession())?.unwrap();-- if (redirectUrl !== null) {- store.dispatch(replace(redirectUrl));- }- } else {- const url = location.pathname + location.search + location.hash;- store.dispatch(logout(url));- }- }- }, COOKIE_POOLING_TIMEOUT);- }-- next(action);- };-- return sessionMiddlware;-};diff --git a/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.ts b/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.tsnew file mode 100644index 00000000000..603b219e94c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.ts@@ -0,0 +1,85 @@+import type { Action, Middleware, ThunkDispatch } from "@reduxjs/toolkit";+import { isAction } from "@reduxjs/toolkit";+import Cookies from "js-cookie";++import { logout, refreshSession } from "metabase/redux/auth";+import type { State } from "metabase/redux/store";+import { replace } from "metabase/router";+import { isSameOrSiteUrlOrigin } from "metabase/utils/dom";++export const SESSION_KEY = "metabase.TIMEOUT";+export const COOKIE_POOLING_TIMEOUT = 3000;+const getIsLoggedIn = () => typeof Cookies.get(SESSION_KEY) !== "undefined";++const getRedirectUrl = () => {+ const params = new URLSearchParams(window.location.search);+ const redirectUrlParam = params.get("redirect");++ return redirectUrlParam != null && isSameOrSiteUrlOrigin(redirectUrlParam)+ ? redirectUrlParam+ : null;+};++const preventImmedidateRedirect = () => {+ // defer to login page to redirect if sent directly. `getIsLoggedIn` returns if a session cookie+ // is present, but does not validate. in the case of an invalid token at the start of an OAuth+ // flow, the user can get stuck with a "Account linking requires an authenticated session" error+ // without an obvious way to remedy. by defering the the login page we can ensure cookie validation+ // and give the user a chance to re-auth if needed.+ return window.location.pathname.startsWith("/auth/login");+};++type SessionMiddleware = Middleware<+ Record<string, never>,+ State,+ ThunkDispatch<State, unknown, Action>+>;++export const createSessionMiddleware = (+ resetActions: string[] = [],+ setInterval = global.setInterval,+): SessionMiddleware => {+ let intervalId: ReturnType<typeof setInterval> | undefined;++ const sessionMiddleware: SessionMiddleware =+ (store) => (next) => (action) => {+ if (+ intervalId == null ||+ (isAction(action) && resetActions.includes(action.type))+ ) {+ clearInterval(intervalId);++ let wasLoggedIn = getIsLoggedIn();++ // get the redirect url before refreshing the session because after the refresh the url will be reset+ const redirectUrl = getRedirectUrl();++ if (wasLoggedIn && !!redirectUrl && !preventImmedidateRedirect()) {+ store.dispatch(replace(redirectUrl));+ }++ intervalId = setInterval(async () => {+ const isLoggedIn = getIsLoggedIn();++ if (isLoggedIn !== wasLoggedIn) {+ wasLoggedIn = isLoggedIn;++ if (isLoggedIn) {+ await store.dispatch(refreshSession())?.unwrap();++ if (redirectUrl !== null) {+ store.dispatch(replace(redirectUrl));+ }+ } else {+ const url = location.pathname + location.search + location.hash;+ store.dispatch(logout(url));+ }+ }+ }, COOKIE_POOLING_TIMEOUT);+ }++ next(action);+ };++ return sessionMiddleware;+};diff --git a/frontend/src/metabase/plugins/oss/core.ts b/frontend/src/metabase/plugins/oss/core.tsindex f0d5c2d2a2f..8a42eac7da6 100644--- a/frontend/src/metabase/plugins/oss/core.ts+++ b/frontend/src/metabase/plugins/oss/core.ts@@ -1,4 +1,4 @@-import type { Middleware } from "@reduxjs/toolkit";+import type { Action, Middleware, ThunkDispatch } from "@reduxjs/toolkit";import type { ComponentType, ReactNode } from "react";import { t } from "ttag";@@ -67,7 +67,12 @@ export const PLUGIN_HOMEPAGE_SETTING: {CustomUrlOption: { label: string; Control: ComponentType } | null;} = getDefaultHomepageSetting();-const getDefaultReduxMiddlewares = (): Middleware[] => [];+// dispatch is typed as thunk-capable so EE middlewares can dispatch async thunks+const getDefaultReduxMiddlewares = (): Middleware<+ Record<string, never>,+ State,+ ThunkDispatch<State, unknown, Action>+>[] => [];export const PLUGIN_REDUX_MIDDLEWARES = getDefaultReduxMiddlewares();