refs #13986 Merge branch 'origin/13986-projects-list-and-default-routing'
[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, default as unionize, UnionOf } from "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     tag: 'type',
21     value: 'payload'
22 });
23
24 function setAuthorizationHeader(services: ServiceRepository, token: string) {
25     services.apiClient.defaults.headers.common = {
26         Authorization: `OAuth2 ${token}`
27     };
28     services.webdavClient.defaults.headers = {
29         Authorization: `OAuth2 ${token}`
30     };
31 }
32
33 function removeAuthorizationHeader(client: AxiosInstance) {
34     delete client.defaults.headers.common.Authorization;
35 }
36
37 export const initAuth = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
38     const user = services.authService.getUser();
39     const token = services.authService.getApiToken();
40     if (token) {
41         setAuthorizationHeader(services, token);
42     }
43     if (token && user) {
44         dispatch(authActions.INIT({ user, token }));
45     }
46 };
47
48 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
49     services.authService.saveApiToken(token);
50     setAuthorizationHeader(services, token);
51     dispatch(authActions.SAVE_API_TOKEN(token));
52 };
53
54 export const login = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
55     services.authService.login();
56     dispatch(authActions.LOGIN());
57 };
58
59 export const logout = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
60     services.authService.removeApiToken();
61     services.authService.removeUser();
62     removeAuthorizationHeader(services.apiClient);
63     services.authService.logout();
64     dispatch(authActions.LOGOUT());
65 };
66
67 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
68     dispatch(authActions.USER_DETAILS_REQUEST());
69     return services.authService.getUserDetails().then(user => {
70         services.authService.saveUser(user);
71         dispatch(authActions.USER_DETAILS_SUCCESS(user));
72         return user;
73     });
74 };
75
76 export type AuthAction = UnionOf<typeof authActions>;