Merge branch 'master' into 14566-admin-modal
[arvados.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 { reset, stopSubmit, startSubmit, FormErrors } from 'redux-form';
8 import { AxiosInstance } from "axios";
9 import { RootState } from "../store";
10 import { snackbarActions } from '~/store/snackbar/snackbar-actions';
11 import { dialogActions } from '~/store/dialog/dialog-actions';
12 import { setBreadcrumbs } from '~/store/breadcrumbs/breadcrumbs-actions';
13 import { ServiceRepository } from "~/services/services";
14 import { getAuthorizedKeysServiceError, AuthorizedKeysServiceError } from '~/services/authorized-keys-service/authorized-keys-service';
15 import { KeyType, SshKeyResource } from '~/models/ssh-key';
16 import { User } from "~/models/user";
17 import * as Routes from '~/routes/routes';
18
19 export const authActions = unionize({
20     SAVE_API_TOKEN: ofType<string>(),
21     LOGIN: {},
22     LOGOUT: {},
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 });
30
31 export const SSH_KEY_CREATE_FORM_NAME = 'sshKeyCreateFormName';
32 export const SSH_KEY_PUBLIC_KEY_DIALOG = 'sshKeyPublicKeyDialog';
33 export const SSH_KEY_REMOVE_DIALOG = 'sshKeyRemoveDialog';
34 export const SSH_KEY_ATTRIBUTES_DIALOG = 'sshKeyAttributesDialog';
35
36 export interface SshKeyCreateFormDialogData {
37     publicKey: string;
38     name: string;
39 }
40
41 function setAuthorizationHeader(services: ServiceRepository, token: string) {
42     services.apiClient.defaults.headers.common = {
43         Authorization: `OAuth2 ${token}`
44     };
45     services.webdavClient.defaults.headers = {
46         Authorization: `OAuth2 ${token}`
47     };
48 }
49
50 function removeAuthorizationHeader(client: AxiosInstance) {
51     delete client.defaults.headers.common.Authorization;
52 }
53
54 export const initAuth = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
55     const user = services.authService.getUser();
56     const token = services.authService.getApiToken();
57     if (token) {
58         setAuthorizationHeader(services, token);
59     }
60     if (token && user) {
61         dispatch(authActions.INIT({ user, token }));
62     }
63 };
64
65 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
66     services.authService.saveApiToken(token);
67     setAuthorizationHeader(services, token);
68     dispatch(authActions.SAVE_API_TOKEN(token));
69 };
70
71 export const login = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
72     services.authService.login();
73     dispatch(authActions.LOGIN());
74 };
75
76 export const logout = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
77     services.authService.removeApiToken();
78     services.authService.removeUser();
79     removeAuthorizationHeader(services.apiClient);
80     services.authService.logout();
81     dispatch(authActions.LOGOUT());
82 };
83
84 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
85     dispatch(authActions.USER_DETAILS_REQUEST());
86     return services.authService.getUserDetails().then(user => {
87         services.authService.saveUser(user);
88         dispatch(authActions.USER_DETAILS_SUCCESS(user));
89         return user;
90     });
91 };
92
93 export const openSshKeyCreateDialog = () => dialogActions.OPEN_DIALOG({ id: SSH_KEY_CREATE_FORM_NAME, data: {} });
94
95 export const openPublicKeyDialog = (name: string, publicKey: string) =>
96     dialogActions.OPEN_DIALOG({ id: SSH_KEY_PUBLIC_KEY_DIALOG, data: { name, publicKey } });
97
98 export const openSshKeyAttributesDialog = (uuid: string) =>
99     (dispatch: Dispatch, getState: () => RootState) => {
100         const sshKey = getState().auth.sshKeys.find(it => it.uuid === uuid);
101         dispatch(dialogActions.OPEN_DIALOG({ id: SSH_KEY_ATTRIBUTES_DIALOG, data: { sshKey } }));
102     };
103
104 export const openSshKeyRemoveDialog = (uuid: string) =>
105     (dispatch: Dispatch, getState: () => RootState) => {
106         dispatch(dialogActions.OPEN_DIALOG({
107             id: SSH_KEY_REMOVE_DIALOG,
108             data: {
109                 title: 'Remove public key',
110                 text: 'Are you sure you want to remove this public key?',
111                 confirmButtonLabel: 'Remove',
112                 uuid
113             }
114         }));
115     };
116
117 export const removeSshKey = (uuid: string) =>
118     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
119         dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removing ...' }));
120         await services.authorizedKeysService.delete(uuid);
121         dispatch(authActions.REMOVE_SSH_KEY(uuid));
122         dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Public Key has been successfully removed.', hideDuration: 2000 }));
123     };
124
125 export const createSshKey = (data: SshKeyCreateFormDialogData) =>
126     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
127         const userUuid = getState().auth.user!.uuid;
128         const { name, publicKey } = data;
129         dispatch(startSubmit(SSH_KEY_CREATE_FORM_NAME));
130         try {
131             const newSshKey = await services.authorizedKeysService.create({
132                 name,
133                 publicKey,
134                 keyType: KeyType.SSH,
135                 authorizedUserUuid: userUuid
136             });
137             dispatch(authActions.ADD_SSH_KEY(newSshKey));
138             dispatch(dialogActions.CLOSE_DIALOG({ id: SSH_KEY_CREATE_FORM_NAME }));
139             dispatch(reset(SSH_KEY_CREATE_FORM_NAME));
140             dispatch(snackbarActions.OPEN_SNACKBAR({
141                 message: "Public key has been successfully created.",
142                 hideDuration: 2000
143             }));
144         } catch (e) {
145             const error = getAuthorizedKeysServiceError(e);
146             if (error === AuthorizedKeysServiceError.UNIQUE_PUBLIC_KEY) {
147                 dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key already exists.' } as FormErrors));
148             } else if (error === AuthorizedKeysServiceError.INVALID_PUBLIC_KEY) {
149                 dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key is invalid' } as FormErrors));
150             }
151         }
152     };
153
154 export const loadSshKeysPanel = () =>
155     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
156         try {
157             const userUuid = getState().auth.user!.uuid;
158             const { router } = getState();
159             const pathname = router.location ? router.location.pathname : '';
160             dispatch(setBreadcrumbs([{ label: 'SSH Keys' }]));
161             const response = await services.authorizedKeysService.list();
162             const userSshKeys = response.items.find(it => it.ownerUuid === userUuid);
163             return Routes.matchSshKeysAdminRoute(pathname) ? dispatch(authActions.SET_SSH_KEYS(response.items)) : dispatch(authActions.SET_SSH_KEYS([userSshKeys!]));
164         } catch (e) {
165             return;
166         }
167     };
168
169 export type AuthAction = UnionOf<typeof authActions>;