conflicts
[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, startSubmit } 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
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<SshKeyResource[]>(),
26     ADD_SSH_KEY: ofType<SshKeyResource>(),
27     REMOVE_SSH_KEY: ofType<string>()
28 });
29
30 export const SSH_KEY_CREATE_FORM_NAME = 'sshKeyCreateFormName';
31 export const SSH_KEY_PUBLIC_KEY_DIALOG = 'sshKeyPublicKeyDialog';
32 export const SSH_KEY_REMOVE_DIALOG = 'sshKeyRemoveDialog';
33 export const SSH_KEY_ATTRIBUTES_DIALOG = 'sshKeyAttributesDialog';
34
35 export interface SshKeyCreateFormDialogData {
36     publicKey: string;
37     name: string;
38 }
39
40 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 = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
54     const user = services.authService.getUser();
55     const token = services.authService.getApiToken();
56     if (token) {
57         setAuthorizationHeader(services, token);
58     }
59     if (token && user) {
60         dispatch(authActions.INIT({ user, token }));
61     }
62 };
63
64 export const saveApiToken = (token: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
65     services.authService.saveApiToken(token);
66     setAuthorizationHeader(services, token);
67     dispatch(authActions.SAVE_API_TOKEN(token));
68 };
69
70 export const login = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
71     services.authService.login();
72     dispatch(authActions.LOGIN());
73 };
74
75 export const logout = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
76     services.authService.removeApiToken();
77     services.authService.removeUser();
78     removeAuthorizationHeader(services.apiClient);
79     services.authService.logout();
80     dispatch(authActions.LOGOUT());
81 };
82
83 export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<User> => {
84     dispatch(authActions.USER_DETAILS_REQUEST());
85     return services.authService.getUserDetails().then(user => {
86         services.authService.saveUser(user);
87         dispatch(authActions.USER_DETAILS_SUCCESS(user));
88         return user;
89     });
90 };
91
92 export const openSshKeyCreateDialog = () => dialogActions.OPEN_DIALOG({ id: SSH_KEY_CREATE_FORM_NAME, data: {} });
93
94 export const openPublicKeyDialog = (name: string, publicKey: string) =>
95     dialogActions.OPEN_DIALOG({ id: SSH_KEY_PUBLIC_KEY_DIALOG, data: { name, publicKey } });
96
97 export const openSshKeyAttributesDialog = (uuid: string) =>
98     (dispatch: Dispatch, getState: () => RootState) => {
99         const sshKey = getState().auth.sshKeys.find(it => it.uuid === uuid);
100         dispatch(dialogActions.OPEN_DIALOG({ id: SSH_KEY_ATTRIBUTES_DIALOG, data: { sshKey } }));
101     };
102
103 export const openSshKeyRemoveDialog = (uuid: string) =>
104     (dispatch: Dispatch, getState: () => RootState) => {
105         dispatch(dialogActions.OPEN_DIALOG({
106             id: SSH_KEY_REMOVE_DIALOG,
107             data: {
108                 title: 'Remove public key',
109                 text: 'Are you sure you want to remove this public key?',
110                 confirmButtonLabel: 'Remove',
111                 uuid
112             }
113         }));
114     };
115
116 export const removeSshKey = (uuid: string) =>
117     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
118         dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removing ...' }));
119         await services.authorizedKeysService.delete(uuid);
120         dispatch(authActions.REMOVE_SSH_KEY(uuid));
121         dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Public Key has been successfully removed.', hideDuration: 2000 }));
122     };
123
124 export const createSshKey = (data: SshKeyCreateFormDialogData) =>
125     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
126         const userUuid = getState().auth.user!.uuid;
127         const { name, publicKey } = data;
128         dispatch(startSubmit(SSH_KEY_CREATE_FORM_NAME));
129         try {
130             const newSshKey = await services.authorizedKeysService.create({
131                 name,
132                 publicKey,
133                 keyType: KeyType.SSH,
134                 authorizedUserUuid: userUuid
135             });
136             dispatch(authActions.ADD_SSH_KEY(newSshKey));
137             dispatch(dialogActions.CLOSE_DIALOG({ id: SSH_KEY_CREATE_FORM_NAME }));
138             dispatch(reset(SSH_KEY_CREATE_FORM_NAME));
139             dispatch(snackbarActions.OPEN_SNACKBAR({
140                 message: "Public key has been successfully created.",
141                 hideDuration: 2000
142             }));
143         } catch (e) {
144             const error = getAuthorizedKeysServiceError(e);
145             if (error === AuthorizedKeysServiceError.UNIQUE_PUBLIC_KEY) {
146                 dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key already exists.' }));
147             } else if (error === AuthorizedKeysServiceError.INVALID_PUBLIC_KEY) {
148                 dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key is invalid' }));
149             }
150         }
151     };
152
153 export const loadSshKeysPanel = () =>
154     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
155         try {
156             dispatch(setBreadcrumbs([{ label: 'SSH Keys'}]));
157             const response = await services.authorizedKeysService.list();
158             dispatch(authActions.SET_SSH_KEYS(response.items));
159         } catch (e) {
160             return;
161         }
162     };
163
164
165 export type AuthAction = UnionOf<typeof authActions>;