15803: use getUserUuid instead of getting from local store
[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
12 export const authMiddleware = (services: ServiceRepository): Middleware => store => next => action => {
13     authActions.match(action, {
14         INIT: ({ user, token }) => {
15             next(action);
16             const state: RootState = store.getState();
17
18             if (state.auth.apiToken) {
19                 services.authService.saveApiToken(state.auth.apiToken);
20                 setAuthorizationHeader(services, state.auth.apiToken);
21             } else {
22                 services.authService.removeApiToken();
23                 removeAuthorizationHeader(services);
24             }
25
26             store.dispatch<any>(initSessions(services.authService, state.auth.remoteHostsConfig[state.auth.localCluster], user));
27             if (!user.isActive) {
28                 services.userService.activate(user.uuid).then((user: User) => {
29                     store.getState().dispatch(authActions.INIT({ user, token }));
30                 });
31             }
32         },
33         CONFIG: ({ config }) => {
34             document.title = `Arvados Workbench (${config.uuidPrefix})`;
35             next(action);
36         },
37         LOGOUT: ({ deleteLinkData }) => {
38             next(action);
39             if (deleteLinkData) {
40                 services.linkAccountService.removeAccountToLink();
41             }
42             services.authService.removeApiToken();
43             services.authService.removeUser();
44             removeAuthorizationHeader(services);
45             services.authService.logout();
46         },
47         default: () => next(action)
48     });
49 };