Apply wrapped unionize
[arvados-workbench2.git] / src / store / auth / auth-action.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { ofType, unionize, UnionOf } from '~/common/unionize';
6 import { Dispatch } from "redux";
7 import { User } from "~/models/user";
8 import { RootState } from "../store";
9 import { ServiceRepository } from "~/services/services";
10 import { AxiosInstance } from "axios";
11
12 export const authActions = unionize({
13     SAVE_API_TOKEN: ofType<string>(),
14     LOGIN: {},
15     LOGOUT: {},
16     INIT: ofType<{ user: User, token: string }>(),
17     USER_DETAILS_REQUEST: {},
18     USER_DETAILS_SUCCESS: ofType<User>()
19 });
20
21 function setAuthorizationHeader(services: ServiceRepository, token: string) {
22     services.apiClient.defaults.headers.common = {
23         Authorization: `OAuth2 ${token}`
24     };
25     services.webdavClient.defaults.headers = {
26         Authorization: `OAuth2 ${token}`
27     };
28 }
29
30 function removeAuthorizationHeader(client: AxiosInstance) {
31     delete client.defaults.headers.common.Authorization;
32 }
33
34 export const initAuth = () =>
35     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
36         const user = services.authService.getUser();
37         const token = services.authService.getApiToken();
38         if (token) {
39             setAuthorizationHeader(services, token);
40         }
41         if (token && user) {
42             dispatch(authActions.INIT({ user, token }));
43         }
44     };
45
46 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
47     services.authService.saveApiToken(token);
48     setAuthorizationHeader(services, token);
49     dispatch(authActions.SAVE_API_TOKEN(token));
50 };
51
52 export const login = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
53     services.authService.login();
54     dispatch(authActions.LOGIN());
55 };
56
57 export const logout = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
58     services.authService.removeApiToken();
59     services.authService.removeUser();
60     removeAuthorizationHeader(services.apiClient);
61     services.authService.logout();
62     dispatch(authActions.LOGOUT());
63 };
64
65 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
66     dispatch(authActions.USER_DETAILS_REQUEST());
67     return services.authService.getUserDetails().then(user => {
68         services.authService.saveUser(user);
69         dispatch(authActions.USER_DETAILS_SUCCESS(user));
70         return user;
71     });
72 };
73
74 export type AuthAction = UnionOf<typeof authActions>;