Merge branch 'master'
[arvados-workbench2.git] / src / store / auth / auth-reducer.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import actions, { AuthAction } from "./auth-action";
6 import { User } from "../../models/user";
7 import { authService } from "../../services/services";
8 import { removeServerApiAuthorizationHeader, setServerApiAuthorizationHeader } from "../../common/api/server-api";
9
10 export interface AuthState {
11     user?: User;
12     apiToken?: string;
13 }
14
15 const authReducer = (state: AuthState = {}, action: AuthAction) => {
16     return actions.match(action, {
17         SAVE_API_TOKEN: (token: string) => {
18             authService.saveApiToken(token);
19             setServerApiAuthorizationHeader(token);
20             return {...state, apiToken: token};
21         },
22         INIT: () => {
23             const user = authService.getUser();
24             const token = authService.getApiToken();
25             if (token) {
26                 setServerApiAuthorizationHeader(token);
27             }
28             return {user, apiToken: token};
29         },
30         LOGIN: () => {
31             authService.login();
32             return state;
33         },
34         LOGOUT: () => {
35             authService.removeApiToken();
36             authService.removeUser();
37             removeServerApiAuthorizationHeader();
38             authService.logout();
39             return {...state, apiToken: undefined};
40         },
41         USER_DETAILS_SUCCESS: (user: User) => {
42             authService.saveUser(user);
43             return {...state, user};
44         },
45         default: () => state
46     });
47 };
48
49 export default authReducer;