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