Merge branch 'master' into 15803-unsetup
[arvados-workbench2.git] / src / store / auth / auth-middleware.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Middleware } from "redux";
6 import { authActions, } from "./auth-action";
7 import { ServiceRepository, setAuthorizationHeader, removeAuthorizationHeader } from "~/services/services";
8 import { initSessions } from "~/store/auth/auth-action-session";
9 import { User } from "~/models/user";
10 import { RootState } from '~/store/store';
11 import { progressIndicatorActions } from "~/store/progress-indicator/progress-indicator-actions";
12 import { WORKBENCH_LOADING_SCREEN } from '~/store/workbench/workbench-actions';
13
14 export const authMiddleware = (services: ServiceRepository): Middleware => store => next => action => {
15     authActions.match(action, {
16         INIT: ({ user, token }) => {
17             next(action);
18             const state: RootState = store.getState();
19
20             if (state.auth.apiToken) {
21                 services.authService.saveApiToken(state.auth.apiToken);
22                 setAuthorizationHeader(services, state.auth.apiToken);
23             } else {
24                 services.authService.removeApiToken();
25                 removeAuthorizationHeader(services);
26             }
27
28             store.dispatch<any>(initSessions(services.authService, state.auth.remoteHostsConfig[state.auth.localCluster], user));
29             if (!user.isActive) {
30                 store.dispatch(progressIndicatorActions.START_WORKING(WORKBENCH_LOADING_SCREEN));
31                 services.userService.activate(user.uuid).then((user: User) => {
32                     store.dispatch(authActions.INIT({ user, token }));
33                     store.dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
34                 }).catch(() => {
35                     store.dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
36                 });
37             }
38         },
39         CONFIG: ({ config }) => {
40             document.title = `Arvados Workbench (${config.uuidPrefix})`;
41             next(action);
42         },
43         LOGOUT: ({ deleteLinkData }) => {
44             next(action);
45             if (deleteLinkData) {
46                 services.linkAccountService.removeAccountToLink();
47             }
48             services.authService.removeApiToken();
49             services.authService.removeUser();
50             removeAuthorizationHeader(services);
51             services.authService.logout();
52         },
53         default: () => next(action)
54     });
55 };