refs #13545 Merge branch '13545-projects-service'
[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/server-api";
9 import { UserDetailsResponse } from "../../services/auth-service/auth-service";
10
11 export interface AuthState {
12     user?: User;
13     apiToken?: string;
14 };
15
16 const authReducer = (state: AuthState = {}, action: AuthAction) => {
17     return actions.match(action, {
18         SAVE_API_TOKEN: (token: string) => {
19             authService.saveApiToken(token);
20             setServerApiAuthorizationHeader(token);
21             return {...state, apiToken: token};
22         },
23         INIT: () => {
24             const user = authService.getUser();
25             const token = authService.getApiToken();
26             if (token) {
27                 setServerApiAuthorizationHeader(token);
28             }
29             return {user, apiToken: token};
30         },
31         LOGIN: () => {
32             authService.login();
33             return state;
34         },
35         LOGOUT: () => {
36             authService.removeApiToken();
37             authService.removeUser();
38             removeServerApiAuthorizationHeader();
39             authService.logout();
40             return {...state, apiToken: undefined};
41         },
42         USER_DETAILS_SUCCESS: (ud: UserDetailsResponse) => {
43             const user = {
44                 email: ud.email,
45                 firstName: ud.first_name,
46                 lastName: ud.last_name
47             };
48             authService.saveUser(user);
49             return {...state, user};
50         },
51         default: () => state
52     });
53 };
54
55 export default authReducer;