Add ssh keys panel
[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 { reset, stopSubmit } from 'redux-form';
8 import { User } from "~/models/user";
9 import { RootState } from "../store";
10 import { ServiceRepository } from "~/services/services";
11 import { getCommonResourceServiceError, CommonResourceServiceError } from '~/services/common-service/common-resource-service';
12 import { AxiosInstance } from "axios";
13 import { snackbarActions } from '~/store/snackbar/snackbar-actions';
14 import { dialogActions } from '~/store/dialog/dialog-actions';
15 import { SshKeyCreateFormDialogData, SshKey, KeyType } from '~/models/ssh-key';
16 import { setBreadcrumbs } from '../breadcrumbs/breadcrumbs-actions';
17
18 export const authActions = unionize({
19     SAVE_API_TOKEN: ofType<string>(),
20     LOGIN: {},
21     LOGOUT: {},
22     INIT: ofType<{ user: User, token: string }>(),
23     USER_DETAILS_REQUEST: {},
24     USER_DETAILS_SUCCESS: ofType<User>(),
25     SET_SSH_KEYS: ofType<SshKey[]>(),
26     ADD_SSH_KEY: ofType<SshKey>()
27 });
28
29 export const SSH_KEY_CREATE_FORM_NAME = 'sshKeyCreateFormName';
30
31 function setAuthorizationHeader(services: ServiceRepository, token: string) {
32     services.apiClient.defaults.headers.common = {
33         Authorization: `OAuth2 ${token}`
34     };
35     services.webdavClient.defaults.headers = {
36         Authorization: `OAuth2 ${token}`
37     };
38 }
39
40 function removeAuthorizationHeader(client: AxiosInstance) {
41     delete client.defaults.headers.common.Authorization;
42 }
43
44 export const initAuth = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
45     const user = services.authService.getUser();
46     const token = services.authService.getApiToken();
47     if (token) {
48         setAuthorizationHeader(services, token);
49     }
50     if (token && user) {
51         dispatch(authActions.INIT({ user, token }));
52     }
53 };
54
55 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
56     services.authService.saveApiToken(token);
57     setAuthorizationHeader(services, token);
58     dispatch(authActions.SAVE_API_TOKEN(token));
59 };
60
61 export const login = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
62     services.authService.login();
63     dispatch(authActions.LOGIN());
64 };
65
66 export const logout = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
67     services.authService.removeApiToken();
68     services.authService.removeUser();
69     removeAuthorizationHeader(services.apiClient);
70     services.authService.logout();
71     dispatch(authActions.LOGOUT());
72 };
73
74 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
75     dispatch(authActions.USER_DETAILS_REQUEST());
76     return services.authService.getUserDetails().then(user => {
77         services.authService.saveUser(user);
78         dispatch(authActions.USER_DETAILS_SUCCESS(user));
79         return user;
80     });
81 };
82
83 export const openSshKeyCreateDialog = () => dialogActions.OPEN_DIALOG({ id: SSH_KEY_CREATE_FORM_NAME, data: {} });
84
85 export const createSshKey = (data: SshKeyCreateFormDialogData) =>
86     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
87         try {
88             const userUuid = getState().auth.user!.uuid;
89             const { name, publicKey } = data;
90             const newSshKey = await services.authorizedKeysService.create({
91                 name, 
92                 publicKey,
93                 keyType: KeyType.SSH,
94                 authorizedUserUuid: userUuid
95             });
96             dispatch(dialogActions.CLOSE_DIALOG({ id: SSH_KEY_CREATE_FORM_NAME }));
97             dispatch(reset(SSH_KEY_CREATE_FORM_NAME));
98             dispatch(authActions.ADD_SSH_KEY(newSshKey));
99             dispatch(snackbarActions.OPEN_SNACKBAR({
100                 message: "Public key has been successfully created.",
101                 hideDuration: 2000
102             }));
103         } catch (e) {
104             const error = getCommonResourceServiceError(e);
105             if (error === CommonResourceServiceError.UNIQUE_PUBLIC_KEY) {
106                 dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key already exists.' }));
107             } else if (error === CommonResourceServiceError.INVALID_PUBLIC_KEY) {
108                 dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key is invalid' }));
109             }
110         }
111     };
112
113 export const loadSshKeysPanel = () =>
114     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
115         try {
116             dispatch(setBreadcrumbs([{ label: 'SSH Keys'}]));
117             const response = await services.authorizedKeysService.list();
118             dispatch(authActions.SET_SSH_KEYS(response.items));
119         } catch (e) {
120             return;
121         }
122     };
123
124
125 export type AuthAction = UnionOf<typeof authActions>;