15736: When validating sessions, save the config
[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 { Config } 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 { AxiosError } from "axios";
18
19 export const authActions = unionize({
20     SAVE_API_TOKEN: ofType<string>(),
21     SAVE_USER: ofType<UserResource>(),
22     LOGIN: {},
23     LOGOUT: {},
24     CONFIG: ofType<{ config: Config }>(),
25     INIT: ofType<{ user: User, token: string }>(),
26     USER_DETAILS_REQUEST: {},
27     USER_DETAILS_SUCCESS: ofType<User>(),
28     SET_SSH_KEYS: ofType<SshKeyResource[]>(),
29     ADD_SSH_KEY: ofType<SshKeyResource>(),
30     REMOVE_SSH_KEY: ofType<string>(),
31     SET_HOME_CLUSTER: ofType<string>(),
32     SET_SESSIONS: ofType<Session[]>(),
33     ADD_SESSION: ofType<Session>(),
34     REMOVE_SESSION: ofType<string>(),
35     UPDATE_SESSION: ofType<Session>(),
36     REMOTE_CLUSTER_CONFIG: ofType<{ config: Config }>(),
37 });
38
39 export function setAuthorizationHeader(services: ServiceRepository, token: string) {
40     services.apiClient.defaults.headers.common = {
41         Authorization: `OAuth2 ${token}`
42     };
43     services.webdavClient.defaults.headers = {
44         Authorization: `OAuth2 ${token}`
45     };
46 }
47
48 function removeAuthorizationHeader(client: AxiosInstance) {
49     delete client.defaults.headers.common.Authorization;
50 }
51
52 export const initAuth = (config: Config) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
53     // Cancel any link account ops in progress unless the user has
54     // just logged in or there has been a successful link operation
55     const data = services.linkAccountService.getLinkOpStatus();
56     if (!matchTokenRoute(location.pathname) && (!matchFedTokenRoute(location.pathname)) && data === undefined) {
57         dispatch<any>(cancelLinking()).then(() => {
58             dispatch<any>(init(config));
59         });
60     }
61     else {
62         dispatch<any>(init(config));
63     }
64 };
65
66 const init = (config: Config) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
67     const user = services.authService.getUser();
68     const token = services.authService.getApiToken();
69     let homeCluster = services.authService.getHomeCluster();
70     if (token) {
71         setAuthorizationHeader(services, token);
72     }
73     if (homeCluster && !config.remoteHosts[homeCluster]) {
74         homeCluster = undefined;
75     }
76     dispatch(authActions.CONFIG({ config }));
77     dispatch(authActions.SET_HOME_CLUSTER(config.loginCluster || homeCluster || config.uuidPrefix));
78     document.title = `Arvados Workbench (${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 };
94
95 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
96     services.authService.saveApiToken(token);
97     setAuthorizationHeader(services, token);
98     dispatch(authActions.SAVE_API_TOKEN(token));
99 };
100
101 export const saveUser = (user: UserResource) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
102     services.authService.saveUser(user);
103     dispatch(authActions.SAVE_USER(user));
104 };
105
106 export const login = (uuidPrefix: string, homeCluster: string, loginCluster: string,
107     remoteHosts: { [key: string]: string }) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
108         services.authService.login(uuidPrefix, homeCluster, loginCluster, remoteHosts);
109         dispatch(authActions.LOGIN());
110     };
111
112 export const logout = (deleteLinkData: boolean = false) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
113     if (deleteLinkData) {
114         services.linkAccountService.removeAccountToLink();
115     }
116     services.authService.removeApiToken();
117     services.authService.removeUser();
118     removeAuthorizationHeader(services.apiClient);
119     services.authService.logout();
120     dispatch(authActions.LOGOUT());
121 };
122
123 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
124     dispatch(authActions.USER_DETAILS_REQUEST());
125     return services.authService.getUserDetails().then(user => {
126         services.authService.saveUser(user);
127         dispatch(authActions.USER_DETAILS_SUCCESS(user));
128         return user;
129     });
130 };
131
132 export type AuthAction = UnionOf<typeof authActions>;