Add login/logout tests
[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, UserDetailsResponse } from "./auth-action";
6 import { User } from "../../models/user";
7 import { authService } from "../../services/services";
8 import { removeServerApiAuthorizationHeader, setServerApiAuthorizationHeader } from "../../common/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             return {user, apiToken: token};
26         },
27         LOGIN: () => {
28             authService.login();
29             return state;
30         },
31         LOGOUT: () => {
32             authService.removeApiToken();
33             authService.removeUser();
34             removeServerApiAuthorizationHeader();
35             authService.logout();
36             return {...state, apiToken: undefined};
37         },
38         USER_DETAILS_SUCCESS: (ud: UserDetailsResponse) => {
39             const user = {
40                 email: ud.email,
41                 firstName: ud.first_name,
42                 lastName: ud.last_name
43             };
44             authService.saveUser(user);
45             return {...state, user};
46         },
47         default: () => state
48     });
49 };
50
51 export default authReducer;