e394d62dc3d227b0b885bcf0bbf541fe3956b669
[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, UserResource } from "~/models/user";
12 import { Session } from "~/models/session";
13 import { getClusterConfigURL, Config, ClusterConfigJSON, buildConfig } from '~/common/config';
14 import { initSessions } from "~/store/auth/auth-action-session";
15 import { cancelLinking } from '~/store/link-account-panel/link-account-panel-actions';
16 import { matchTokenRoute, matchFedTokenRoute } from '~/routes/routes';
17 import Axios from "axios";
18 import { AxiosError } from "axios";
19
20 export const authActions = unionize({
21     SAVE_API_TOKEN: ofType<string>(),
22     SAVE_USER: ofType<UserResource>(),
23     LOGIN: {},
24     LOGOUT: {},
25     CONFIG: ofType<{ config: Config }>(),
26     INIT: ofType<{ user: User, token: string }>(),
27     USER_DETAILS_REQUEST: {},
28     USER_DETAILS_SUCCESS: ofType<User>(),
29     SET_SSH_KEYS: ofType<SshKeyResource[]>(),
30     ADD_SSH_KEY: ofType<SshKeyResource>(),
31     REMOVE_SSH_KEY: ofType<string>(),
32     SET_HOME_CLUSTER: ofType<string>(),
33     SET_SESSIONS: ofType<Session[]>(),
34     ADD_SESSION: ofType<Session>(),
35     REMOVE_SESSION: ofType<string>(),
36     UPDATE_SESSION: ofType<Session>(),
37     REMOTE_CLUSTER_CONFIG: ofType<{ config: Config }>(),
38 });
39
40 export function setAuthorizationHeader(services: ServiceRepository, token: string) {
41     services.apiClient.defaults.headers.common = {
42         Authorization: `OAuth2 ${token}`
43     };
44     services.webdavClient.defaults.headers = {
45         Authorization: `OAuth2 ${token}`
46     };
47 }
48
49 function removeAuthorizationHeader(client: AxiosInstance) {
50     delete client.defaults.headers.common.Authorization;
51 }
52
53 export const initAuth = (config: Config) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
54     // Cancel any link account ops in progress unless the user has
55     // just logged in or there has been a successful link operation
56     const data = services.linkAccountService.getLinkOpStatus();
57     if (!matchTokenRoute(location.pathname) && (!matchFedTokenRoute(location.pathname)) && data === undefined) {
58         dispatch<any>(cancelLinking()).then(() => {
59             dispatch<any>(init(config));
60         });
61     }
62     else {
63         dispatch<any>(init(config));
64     }
65 };
66
67 const init = (config: Config) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
68     const user = services.authService.getUser();
69     const token = services.authService.getApiToken();
70     let homeCluster = services.authService.getHomeCluster();
71     if (token) {
72         setAuthorizationHeader(services, token);
73     }
74     if (homeCluster && !config.remoteHosts[homeCluster]) {
75         homeCluster = undefined;
76     }
77     dispatch(authActions.CONFIG({ config }));
78     dispatch(authActions.SET_HOME_CLUSTER(config.loginCluster || homeCluster || config.uuidPrefix));
79     if (token && user) {
80         dispatch(authActions.INIT({ user, token }));
81         dispatch<any>(initSessions(services.authService, config, user));
82         dispatch<any>(getUserDetails()).then((user: User) => {
83             dispatch(authActions.INIT({ user, token }));
84         }).catch((err: AxiosError) => {
85             if (err.response) {
86                 // Bad token
87                 if (err.response.status === 401) {
88                     dispatch<any>(logout());
89                 }
90             }
91         });
92     }
93     Object.keys(config.remoteHosts).map((k) => {
94         if (k !== config.uuidPrefix) {
95             Axios.get<ClusterConfigJSON>(getClusterConfigURL(config.remoteHosts[k]))
96                 .then(response => {
97                     dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config: buildConfig(response.data) }));
98                 });
99         }
100     });
101 };
102
103 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
104     services.authService.saveApiToken(token);
105     setAuthorizationHeader(services, token);
106     dispatch(authActions.SAVE_API_TOKEN(token));
107 };
108
109 export const saveUser = (user: UserResource) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
110     services.authService.saveUser(user);
111     dispatch(authActions.SAVE_USER(user));
112 };
113
114 export const login = (uuidPrefix: string, homeCluster: string, loginCluster: string,
115     remoteHosts: { [key: string]: string }) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
116         services.authService.login(uuidPrefix, homeCluster, loginCluster, remoteHosts);
117         dispatch(authActions.LOGIN());
118     };
119
120 export const logout = (deleteLinkData: boolean = false) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
121     if (deleteLinkData) {
122         services.linkAccountService.removeAccountToLink();
123     }
124     services.authService.removeApiToken();
125     services.authService.removeUser();
126     removeAuthorizationHeader(services.apiClient);
127     services.authService.logout();
128     dispatch(authActions.LOGOUT());
129 };
130
131 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
132     dispatch(authActions.USER_DETAILS_REQUEST());
133     return services.authService.getUserDetails().then(user => {
134         services.authService.saveUser(user);
135         dispatch(authActions.USER_DETAILS_SUCCESS(user));
136         return user;
137     });
138 };
139
140 export type AuthAction = UnionOf<typeof authActions>;