15803: Add missing auth middleware file
[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             if (state.auth.user) {
18                 services.authService.saveUser(state.auth.user);
19             } else {
20                 services.authService.removeUser();
21             }
22             if (state.auth.apiToken) {
23                 services.authService.saveApiToken(state.auth.apiToken);
24                 setAuthorizationHeader(services, state.auth.apiToken);
25             } else {
26                 services.authService.removeApiToken();
27                 removeAuthorizationHeader(services);
28             }
29
30             store.dispatch<any>(initSessions(services.authService, state.auth.remoteHostsConfig[state.auth.localCluster], user));
31             if (!user.isActive) {
32                 services.userService.activate(user.uuid).then((user: User) => {
33                     store.getState().dispatch(authActions.INIT({ user, token }));
34                 });
35             }
36         },
37         CONFIG: ({ config }) => {
38             document.title = `Arvados Workbench (${config.uuidPrefix})`;
39             next(action);
40         },
41         default: () => next(action)
42     });
43 };