15803: If user is inactive, attempt to self-activate.
[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             if (!user.isActive) {
85                 services.userService.activate(user.uuid).then((user: User) => {
86                     dispatch(authActions.INIT({ user, token }));
87                 });
88             }
89         }).catch((err: AxiosError) => {
90             if (err.response) {
91                 // Bad token
92                 if (err.response.status === 401) {
93                     dispatch<any>(logout());
94                 }
95             }
96         });
97     }
98 };
99
100 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
101     services.authService.saveApiToken(token);
102     setAuthorizationHeader(services, token);
103     dispatch(authActions.SAVE_API_TOKEN(token));
104 };
105
106 export const saveUser = (user: UserResource) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
107     services.authService.saveUser(user);
108     dispatch(authActions.SAVE_USER(user));
109 };
110
111 export const login = (uuidPrefix: string, homeCluster: string, loginCluster: string,
112     remoteHosts: { [key: string]: string }) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
113         services.authService.login(uuidPrefix, homeCluster, loginCluster, remoteHosts);
114         dispatch(authActions.LOGIN());
115     };
116
117 export const logout = (deleteLinkData: boolean = false) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
118     if (deleteLinkData) {
119         services.linkAccountService.removeAccountToLink();
120     }
121     services.authService.removeApiToken();
122     services.authService.removeUser();
123     removeAuthorizationHeader(services.apiClient);
124     services.authService.logout();
125     dispatch(authActions.LOGOUT());
126 };
127
128 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
129     dispatch(authActions.USER_DETAILS_REQUEST());
130     return services.authService.getUserDetails().then(user => {
131         services.authService.saveUser(user);
132         dispatch(authActions.USER_DETAILS_SUCCESS(user));
133         return user;
134     });
135 };
136
137 export type AuthAction = UnionOf<typeof authActions>;