7ebbbaa633ab8fc794be450f6635edf6d691b45e
[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 { AxiosInstance } from "axios";
8 import { RootState } from "../store";
9 import { ServiceRepository } from "~/services/services";
10 import { SshKeyResource } from '~/models/ssh-key';
11 import { User } from "~/models/user";
12 import { Session } from "~/models/session";
13 import { getDiscoveryURL, Config } from '~/common/config';
14 import { initSessions } from "~/store/auth/auth-action-session";
15 import Axios from "axios";
16 import { AxiosError } from "axios";
17
18 export const authActions = unionize({
19     SAVE_API_TOKEN: ofType<string>(),
20     LOGIN: {},
21     LOGOUT: {},
22     CONFIG: ofType<{ config: Config }>(),
23     INIT: ofType<{ user: User, token: string }>(),
24     USER_DETAILS_REQUEST: {},
25     USER_DETAILS_SUCCESS: ofType<User>(),
26     SET_SSH_KEYS: ofType<SshKeyResource[]>(),
27     ADD_SSH_KEY: ofType<SshKeyResource>(),
28     REMOVE_SSH_KEY: ofType<string>(),
29     SET_HOME_CLUSTER: ofType<string>(),
30     SET_SESSIONS: ofType<Session[]>(),
31     ADD_SESSION: ofType<Session>(),
32     REMOVE_SESSION: ofType<string>(),
33     UPDATE_SESSION: ofType<Session>(),
34     REMOTE_CLUSTER_CONFIG: ofType<{ config: Config }>(),
35 });
36
37 function setAuthorizationHeader(services: ServiceRepository, token: string) {
38     services.apiClient.defaults.headers.common = {
39         Authorization: `OAuth2 ${token}`
40     };
41     services.webdavClient.defaults.headers = {
42         Authorization: `OAuth2 ${token}`
43     };
44 }
45
46 function removeAuthorizationHeader(client: AxiosInstance) {
47     delete client.defaults.headers.common.Authorization;
48 }
49
50 export const initAuth = (config: Config) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
51     const user = services.authService.getUser();
52     const token = services.authService.getApiToken();
53     const homeCluster = services.authService.getHomeCluster();
54     if (token) {
55         setAuthorizationHeader(services, token);
56     }
57     dispatch(authActions.CONFIG({ config }));
58     dispatch(authActions.SET_HOME_CLUSTER(homeCluster || config.uuidPrefix));
59     if (token && user) {
60         dispatch(authActions.INIT({ user, token }));
61         dispatch<any>(initSessions(services.authService, config, user));
62         dispatch<any>(getUserDetails()).then((user: User) => {
63             dispatch(authActions.INIT({ user, token }));
64         }).catch((err: AxiosError) => {
65             console.log("error");
66             console.log(err);
67             if (err.response) {
68                 // Bad token
69                 if (err.response.status === 401) {
70                     logout()(dispatch, getState, services);
71                 }
72             }
73         });
74     }
75     Object.keys(config.remoteHosts).map((k) => {
76         Axios.get<Config>(getDiscoveryURL(config.remoteHosts[k]))
77             .then(response => dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config: response.data })));
78     });
79 };
80
81 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
82     services.authService.saveApiToken(token);
83     setAuthorizationHeader(services, token);
84     dispatch(authActions.SAVE_API_TOKEN(token));
85 };
86
87 export const login = (uuidPrefix: string, homeCluster: string, remoteHosts: { [key: string]: string }) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
88     services.authService.login(uuidPrefix, homeCluster, remoteHosts);
89     dispatch(authActions.LOGIN());
90 };
91
92 export const logout = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
93     services.authService.removeApiToken();
94     services.authService.removeUser();
95     removeAuthorizationHeader(services.apiClient);
96     services.authService.logout();
97     dispatch(authActions.LOGOUT());
98 };
99
100 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
101     dispatch(authActions.USER_DETAILS_REQUEST());
102     return services.authService.getUserDetails().then(user => {
103         services.authService.saveUser(user);
104         dispatch(authActions.USER_DETAILS_SUCCESS(user));
105         return user;
106     });
107 };
108
109 export type AuthAction = UnionOf<typeof authActions>;