Merge branch '14500_admin_api_tokens'
authorJanicki Artur <artur.janicki@contractors.roche.com>
Fri, 7 Dec 2018 09:51:48 +0000 (10:51 +0100)
committerJanicki Artur <artur.janicki@contractors.roche.com>
Fri, 7 Dec 2018 09:51:48 +0000 (10:51 +0100)
refs #14500

Arvados-DCO-1.1-Signed-off-by: Janicki Artur <artur.janicki@contractors.roche.com>

49 files changed:
src/components/autocomplete/autocomplete.tsx
src/components/text-field/text-field.tsx
src/index.tsx
src/models/api-client-authorization.ts [new file with mode: 0644]
src/models/resource.ts
src/models/user.ts
src/routes/route-change-handlers.ts
src/routes/routes.ts
src/services/api-client-authorization-service/api-client-authorization-service.ts [new file with mode: 0644]
src/services/auth-service/auth-service.ts
src/services/common-service/common-resource-service.ts
src/services/common-service/common-service.ts [new file with mode: 0644]
src/services/favorite-service/favorite-service.ts
src/services/groups-service/groups-service.ts
src/services/permission-service/permission-service.ts
src/services/project-service/project-service.ts
src/services/services.ts
src/store/advanced-tab/advanced-tab.ts
src/store/api-client-authorizations/api-client-authorizations-actions.ts [new file with mode: 0644]
src/store/api-client-authorizations/api-client-authorizations-reducer.ts [new file with mode: 0644]
src/store/auth/auth-action.ts
src/store/auth/auth-reducer.test.ts
src/store/context-menu/context-menu-actions.ts
src/store/data-explorer/data-explorer-middleware-service.ts
src/store/my-account/my-account-panel-actions.ts [new file with mode: 0644]
src/store/navigation/navigation-action.ts
src/store/project-panel/project-panel-middleware-service.ts
src/store/search-results-panel/search-results-middleware-service.ts
src/store/shared-with-me-panel/shared-with-me-middleware-service.ts
src/store/store.ts
src/store/virtual-machines/virtual-machines-actions.ts
src/store/virtual-machines/virtual-machines-reducer.ts
src/store/workbench/workbench-actions.ts
src/store/workflow-panel/workflow-middleware-service.ts
src/validators/validators.tsx
src/views-components/api-client-authorizations-dialog/attributes-dialog.tsx [new file with mode: 0644]
src/views-components/api-client-authorizations-dialog/help-dialog.tsx [new file with mode: 0644]
src/views-components/api-client-authorizations-dialog/remove-dialog.tsx [new file with mode: 0644]
src/views-components/context-menu/action-sets/api-client-authorization-action-set.ts [new file with mode: 0644]
src/views-components/context-menu/context-menu.tsx
src/views-components/main-app-bar/account-menu.tsx
src/views-components/main-content-bar/main-content-bar.tsx
src/views/api-client-authorization-panel/api-client-authorization-panel-root.tsx [new file with mode: 0644]
src/views/api-client-authorization-panel/api-client-authorization-panel.tsx [new file with mode: 0644]
src/views/compute-node-panel/compute-node-panel-root.tsx
src/views/my-account-panel/my-account-panel-root.tsx [new file with mode: 0644]
src/views/my-account-panel/my-account-panel.tsx [new file with mode: 0644]
src/views/virtual-machine-panel/virtual-machine-panel.tsx
src/views/workbench/workbench.tsx

index 7da4ba4a30845a85713439624c8f70fcb052c99a..c5811bb6ea716b44692752c68d7f630d61208e7f 100644 (file)
@@ -3,7 +3,7 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import * as React from 'react';
-import { Input as MuiInput, Chip as MuiChip, Popper as MuiPopper, Paper, FormControl, InputLabel, StyleRulesCallback, withStyles, RootRef, ListItemText, ListItem, List, FormHelperText } from '@material-ui/core';
+import { Input as MuiInput, Chip as MuiChip, Popper as MuiPopper, Paper as MuiPaper, FormControl, InputLabel, StyleRulesCallback, withStyles, RootRef, ListItemText, ListItem, List, FormHelperText } from '@material-ui/core';
 import { PopperProps } from '@material-ui/core/Popper';
 import { WithStyles } from '@material-ui/core/styles';
 import { noop } from 'lodash';
@@ -27,11 +27,13 @@ export interface AutocompleteProps<Item, Suggestion> {
 
 export interface AutocompleteState {
     suggestionsOpen: boolean;
+    selectedSuggestionIndex: number;
 }
 export class Autocomplete<Value, Suggestion> extends React.Component<AutocompleteProps<Value, Suggestion>, AutocompleteState> {
 
     state = {
         suggestionsOpen: false,
+        selectedSuggestionIndex: 0,
     };
 
     containerRef = React.createRef<HTMLDivElement>();
@@ -64,10 +66,11 @@ export class Autocomplete<Value, Suggestion> extends React.Component<Autocomplet
             onBlur={this.handleBlur}
             onChange={this.props.onChange}
             onKeyPress={this.handleKeyPress}
+            onKeyDown={this.handleNavigationKeyPress}
         />;
     }
 
-    renderHelperText(){
+    renderHelperText() {
         return <FormHelperText>{this.props.helperText}</FormHelperText>;
     }
 
@@ -75,13 +78,18 @@ export class Autocomplete<Value, Suggestion> extends React.Component<Autocomplet
         const { suggestions = [] } = this.props;
         return (
             <Popper
-                open={this.state.suggestionsOpen && suggestions.length > 0}
-                anchorEl={this.inputRef.current}>
+                open={this.isSuggestionBoxOpen()}
+                anchorEl={this.inputRef.current}
+                key={suggestions.length}>
                 <Paper onMouseDown={this.preventBlur}>
                     <List dense style={{ width: this.getSuggestionsWidth() }}>
                         {suggestions.map(
                             (suggestion, index) =>
-                                <ListItem button key={index} onClick={this.handleSelect(suggestion)}>
+                                <ListItem
+                                    button
+                                    key={index}
+                                    onClick={this.handleSelect(suggestion)}
+                                    selected={index === this.state.selectedSuggestionIndex}>
                                     {this.renderSuggestion(suggestion)}
                                 </ListItem>
                         )}
@@ -91,6 +99,11 @@ export class Autocomplete<Value, Suggestion> extends React.Component<Autocomplet
         );
     }
 
+    isSuggestionBoxOpen() {
+        const { suggestions = [] } = this.props;
+        return this.state.suggestionsOpen && suggestions.length > 0;
+    }
+
     handleFocus = (event: React.FocusEvent<HTMLInputElement>) => {
         const { onFocus = noop } = this.props;
         this.setState({ suggestionsOpen: true });
@@ -105,13 +118,35 @@ export class Autocomplete<Value, Suggestion> extends React.Component<Autocomplet
         });
     }
 
-    handleKeyPress = ({ key }: React.KeyboardEvent<HTMLInputElement>) => {
-        const { onCreate = noop } = this.props;
-        if (key === 'Enter' && this.props.value.length > 0) {
-            onCreate();
+    handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
+        const { onCreate = noop, onSelect = noop, suggestions = [] } = this.props;
+        const { selectedSuggestionIndex } = this.state;
+        if (event.key === 'Enter') {
+            if (this.isSuggestionBoxOpen() && selectedSuggestionIndex < suggestions.length) {
+                // prevent form submissions when selecting a suggestion
+                event.preventDefault(); 
+                onSelect(suggestions[selectedSuggestionIndex]);
+            } else if (this.props.value.length > 0) {
+                onCreate();
+            }
+        }
+    }
+
+    handleNavigationKeyPress = ({ key }: React.KeyboardEvent<HTMLInputElement>) => {
+        if (key === 'ArrowUp') {
+            this.updateSelectedSuggestionIndex(-1);
+        } else if (key === 'ArrowDown') {
+            this.updateSelectedSuggestionIndex(1);
         }
     }
 
+    updateSelectedSuggestionIndex(value: -1 | 1) {
+        const { suggestions = [] } = this.props;
+        this.setState(({ selectedSuggestionIndex }) => ({
+            selectedSuggestionIndex: (selectedSuggestionIndex + value) % suggestions.length
+        }));
+    }
+
     renderChips() {
         const { items, onDelete } = this.props;
         return items.map(
@@ -199,3 +234,10 @@ const inputStyles: StyleRulesCallback<InputClasses> = () => ({
 });
 
 const Input = withStyles(inputStyles)(MuiInput);
+
+const Paper = withStyles({
+    root: {
+        maxHeight: '80vh',
+        overflowY: 'auto',
+    }
+})(MuiPaper);
index d57c4a8c41c4a7a11f0c9152c5f1172c9ed0b022..627e004d8b5bc607f6b92c673df92cbdb226fd57 100644 (file)
@@ -19,13 +19,13 @@ const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
 type TextFieldProps = WrappedFieldProps & WithStyles<CssRules>;
 
 export const TextField = withStyles(styles)((props: TextFieldProps & { 
-    label?: string, autoFocus?: boolean, required?: boolean, select?: boolean, children: React.ReactNode
+    label?: string, autoFocus?: boolean, required?: boolean, select?: boolean, disabled?: boolean, children: React.ReactNode
 }) =>
     <MaterialTextField
         helperText={props.meta.touched && props.meta.error}
         className={props.classes.textField}
         label={props.label}
-        disabled={props.meta.submitting}
+        disabled={props.disabled || props.meta.submitting}
         error={props.meta.touched && !!props.meta.error}
         autoComplete='off'
         autoFocus={props.autoFocus}
index fbd6c9a88e1bb8ac18d66bd3ff4c681f38ab89ee..c33ef7c1e4a18630a04f9c76627e24131fc1f56b 100644 (file)
@@ -54,6 +54,7 @@ import { keepServiceActionSet } from '~/views-components/context-menu/action-set
 import { loadVocabulary } from '~/store/vocabulary/vocabulary-actions';
 import { virtualMachineActionSet } from '~/views-components/context-menu/action-sets/virtual-machine-action-set';
 import { computeNodeActionSet } from '~/views-components/context-menu/action-sets/compute-node-action-set';
+import { apiClientAuthorizationActionSet } from '~/views-components/context-menu/action-sets/api-client-authorization-action-set';
 
 console.log(`Starting arvados [${getBuildInfo()}]`);
 
@@ -75,6 +76,7 @@ addMenuActionSet(ContextMenuKind.SSH_KEY, sshKeyActionSet);
 addMenuActionSet(ContextMenuKind.VIRTUAL_MACHINE, virtualMachineActionSet);
 addMenuActionSet(ContextMenuKind.KEEP_SERVICE, keepServiceActionSet);
 addMenuActionSet(ContextMenuKind.NODE, computeNodeActionSet);
+addMenuActionSet(ContextMenuKind.API_CLIENT_AUTHORIZATION, apiClientAuthorizationActionSet);
 
 fetchConfig()
     .then(({ config, apiHost }) => {
diff --git a/src/models/api-client-authorization.ts b/src/models/api-client-authorization.ts
new file mode 100644 (file)
index 0000000..aff50be
--- /dev/null
@@ -0,0 +1,19 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+export interface ApiClientAuthorization {
+    uuid: string;
+    apiToken: string;
+    apiClientId: number;
+    userId: number;
+    createdByIpAddress: string;
+    lastUsedByIpAddress: string;
+    lastUsedAt: string;
+    expiresAt: string;
+    createdAt: string;
+    updatedAt: string;
+    ownerUuid: string;
+    defaultOwnerUuid: string;
+    scopes: string[];
+}
\ No newline at end of file
index 4d2d92e0155b183763b1445865420ffe84a558bf..eddcd5a05db44d536d736dce47e28ec27e8df0c1 100644 (file)
@@ -21,6 +21,7 @@ export interface TrashableResource extends Resource {
 }
 
 export enum ResourceKind {
+    API_CLIENT_AUTHORIZATION = "arvados#apiClientAuthorization",
     COLLECTION = "arvados#collection",
     CONTAINER = "arvados#container",
     CONTAINER_REQUEST = "arvados#containerRequest",
@@ -39,6 +40,7 @@ export enum ResourceKind {
 }
 
 export enum ResourceObjectType {
+    API_CLIENT_AUTHORIZATION = 'gj3su',
     COLLECTION = '4zz18',
     CONTAINER = 'dz642',
     CONTAINER_REQUEST = 'xvhdp',
@@ -93,6 +95,8 @@ export const extractUuidKind = (uuid: string = '') => {
             return ResourceKind.KEEP_SERVICE;
         case ResourceObjectType.NODE:
             return ResourceKind.NODE;
+        case ResourceObjectType.API_CLIENT_AUTHORIZATION:
+            return ResourceKind.API_CLIENT_AUTHORIZATION;
         default:
             return undefined;
     }
index 9f9c534763ca86ee40190c2361c89b4e81da2f95..60d598d57bd637c0728476f6b6b5f18a77909270 100644 (file)
@@ -4,12 +4,24 @@
 
 import { Resource, ResourceKind } from '~/models/resource';
 
+export type UserPrefs = {
+    profile?: {
+        organization?: string,
+        organization_email?: string,
+        lab?: string,
+        website_url?: string,
+        role?: string
+    }
+};
+
 export interface User {
     email: string;
     firstName: string;
     lastName: string;
     uuid: string;
     ownerUuid: string;
+    identityUrl: string;
+    prefs: UserPrefs;
     isAdmin: boolean;
 }
 
index f2304acaa77d2b8d0b69789cafa93626446b47e2..a733e42f7e902a7aa912ff9482de9e000627b0b3 100644 (file)
@@ -31,6 +31,8 @@ const handleLocationChange = (store: RootStore) => ({ pathname }: Location) => {
     const sshKeysMatch = Routes.matchSshKeysRoute(pathname);
     const keepServicesMatch = Routes.matchKeepServicesRoute(pathname);
     const computeNodesMatch = Routes.matchComputeNodesRoute(pathname);
+    const apiClientAuthorizationsMatch = Routes.matchApiClientAuthorizationsRoute(pathname);
+    const myAccountMatch = Routes.matchMyAccountRoute(pathname);
 
     if (projectMatch) {
         store.dispatch(WorkbenchActions.loadProject(projectMatch.params.id));
@@ -64,5 +66,9 @@ const handleLocationChange = (store: RootStore) => ({ pathname }: Location) => {
         store.dispatch(WorkbenchActions.loadKeepServices);
     } else if (computeNodesMatch) {
         store.dispatch(WorkbenchActions.loadComputeNodes);
+    } else if (apiClientAuthorizationsMatch) {
+        store.dispatch(WorkbenchActions.loadApiClientAuthorizations);
+    } else if (myAccountMatch) {
+        store.dispatch(WorkbenchActions.loadMyAccount);
     }
 };
index 8f8fa06bd0379232d6da87ea6a47dad5673b811d..7f15a8de74bb52c47e67a5f1e608a1e3ab0df9cf 100644 (file)
@@ -23,8 +23,10 @@ export const Routes = {
     WORKFLOWS: '/workflows',
     SEARCH_RESULTS: '/search-results',
     SSH_KEYS: `/ssh-keys`,
+    MY_ACCOUNT: '/my-account',
     KEEP_SERVICES: `/keep-services`,
-    COMPUTE_NODES: `/nodes`
+    COMPUTE_NODES: `/nodes`,
+    API_CLIENT_AUTHORIZATIONS: `/api_client_authorizations`
 };
 
 export const getResourceUrl = (uuid: string) => {
@@ -91,8 +93,14 @@ export const matchRepositoriesRoute = (route: string) =>
 export const matchSshKeysRoute = (route: string) =>
     matchPath(route, { path: Routes.SSH_KEYS });
 
+export const matchMyAccountRoute = (route: string) =>
+    matchPath(route, { path: Routes.MY_ACCOUNT });
+
 export const matchKeepServicesRoute = (route: string) =>
     matchPath(route, { path: Routes.KEEP_SERVICES });
 
 export const matchComputeNodesRoute = (route: string) =>
-    matchPath(route, { path: Routes.COMPUTE_NODES });
\ No newline at end of file
+    matchPath(route, { path: Routes.COMPUTE_NODES });
+
+export const matchApiClientAuthorizationsRoute = (route: string) =>
+    matchPath(route, { path: Routes.API_CLIENT_AUTHORIZATIONS });
\ No newline at end of file
diff --git a/src/services/api-client-authorization-service/api-client-authorization-service.ts b/src/services/api-client-authorization-service/api-client-authorization-service.ts
new file mode 100644 (file)
index 0000000..3bf4ae8
--- /dev/null
@@ -0,0 +1,14 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { AxiosInstance } from "axios";
+import { ApiActions } from '~/services/api/api-actions';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
+import { CommonService } from '~/services/common-service/common-service';
+
+export class ApiClientAuthorizationService extends CommonService<ApiClientAuthorization> {
+    constructor(serverApi: AxiosInstance, actions: ApiActions) {
+        super(serverApi, "api_client_authorizations", actions);
+    }
+} 
\ No newline at end of file
index 98c0321598090b11002375823fba7ffa1a374aee..22c9dcd6ae3e36e495f25a9e152f9a489506efdc 100644 (file)
@@ -2,7 +2,7 @@
 //
 // SPDX-License-Identifier: AGPL-3.0
 
-import { User } from "~/models/user";
+import { User, UserPrefs } from "~/models/user";
 import { AxiosInstance } from "axios";
 import { ApiActions } from "~/services/api/api-actions";
 import * as uuid from "uuid/v4";
@@ -14,6 +14,8 @@ export const USER_LAST_NAME_KEY = 'userLastName';
 export const USER_UUID_KEY = 'userUuid';
 export const USER_OWNER_UUID_KEY = 'userOwnerUuid';
 export const USER_IS_ADMIN = 'isAdmin';
+export const USER_IDENTITY_URL = 'identityUrl';
+export const USER_PREFS = 'prefs';
 
 export interface UserDetailsResponse {
     email: string;
@@ -22,6 +24,8 @@ export interface UserDetailsResponse {
     uuid: string;
     owner_uuid: string;
     is_admin: boolean;
+    identity_url: string;
+    prefs: UserPrefs;
 }
 
 export class AuthService {
@@ -61,10 +65,12 @@ export class AuthService {
         const lastName = localStorage.getItem(USER_LAST_NAME_KEY);
         const uuid = this.getUuid();
         const ownerUuid = this.getOwnerUuid();
-        const isAdmin = this.getIsAdmin();   
+        const isAdmin = this.getIsAdmin();
+        const identityUrl = localStorage.getItem(USER_IDENTITY_URL);
+        const prefs = JSON.parse(localStorage.getItem(USER_PREFS) || '{"profile": {}}');
 
-        return email && firstName && lastName && uuid && ownerUuid
-            ? { email, firstName, lastName, uuid, ownerUuid, isAdmin }
+        return email && firstName && lastName && uuid && ownerUuid && identityUrl && prefs
+            ? { email, firstName, lastName, uuid, ownerUuid, isAdmin, identityUrl, prefs }
             : undefined;
     }
 
@@ -75,6 +81,8 @@ export class AuthService {
         localStorage.setItem(USER_UUID_KEY, user.uuid);
         localStorage.setItem(USER_OWNER_UUID_KEY, user.ownerUuid);
         localStorage.setItem(USER_IS_ADMIN, JSON.stringify(user.isAdmin));
+        localStorage.setItem(USER_IDENTITY_URL, user.identityUrl);
+        localStorage.setItem(USER_PREFS, JSON.stringify(user.prefs));
     }
 
     public removeUser() {
@@ -84,6 +92,8 @@ export class AuthService {
         localStorage.removeItem(USER_UUID_KEY);
         localStorage.removeItem(USER_OWNER_UUID_KEY);
         localStorage.removeItem(USER_IS_ADMIN);
+        localStorage.removeItem(USER_IDENTITY_URL);
+        localStorage.removeItem(USER_PREFS);
     }
 
     public login() {
@@ -103,13 +113,16 @@ export class AuthService {
             .get<UserDetailsResponse>('/users/current')
             .then(resp => {
                 this.actions.progressFn(reqId, false);
+                const prefs = resp.data.prefs.profile ? resp.data.prefs : { profile: {}};
                 return {
                     email: resp.data.email,
                     firstName: resp.data.first_name,
                     lastName: resp.data.last_name,
                     uuid: resp.data.uuid,
                     ownerUuid: resp.data.owner_uuid,
-                    isAdmin: resp.data.is_admin
+                    isAdmin: resp.data.is_admin,
+                    identityUrl: resp.data.identity_url,
+                    prefs
                 };
             })
             .catch(e => {
index 6114c560526e7b598c033b0a9c6ae4435bd10047..471c32fa21020e8b9eb1db9ae248ad3c6aa30f8f 100644 (file)
@@ -3,33 +3,10 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import * as _ from "lodash";
-import { AxiosInstance, AxiosPromise } from "axios";
+import { AxiosInstance } from "axios";
 import { Resource } from "src/models/resource";
-import * as uuid from "uuid/v4";
 import { ApiActions } from "~/services/api/api-actions";
-
-export interface ListArguments {
-    limit?: number;
-    offset?: number;
-    filters?: string;
-    order?: string;
-    select?: string[];
-    distinct?: boolean;
-    count?: string;
-}
-
-export interface ListResults<T> {
-    kind: string;
-    offset: number;
-    limit: number;
-    items: T[];
-    itemsAvailable: number;
-}
-
-export interface Errors {
-    errors: string[];
-    errorToken: string;
-}
+import { CommonService } from "~/services/common-service/common-service";
 
 export enum CommonResourceServiceError {
     UNIQUE_VIOLATION = 'UniqueViolation',
@@ -40,105 +17,12 @@ export enum CommonResourceServiceError {
     NONE = 'None'
 }
 
-export class CommonResourceService<T extends Resource> {
-
-    static mapResponseKeys = (response: { data: any }) =>
-        CommonResourceService.mapKeys(_.camelCase)(response.data)
-
-    static mapKeys = (mapFn: (key: string) => string) =>
-        (value: any): any => {
-            switch (true) {
-                case _.isPlainObject(value):
-                    return Object
-                        .keys(value)
-                        .map(key => [key, mapFn(key)])
-                        .reduce((newValue, [key, newKey]) => ({
-                            ...newValue,
-                            [newKey]: CommonResourceService.mapKeys(mapFn)(value[key])
-                        }), {});
-                case _.isArray(value):
-                    return value.map(CommonResourceService.mapKeys(mapFn));
-                default:
-                    return value;
-            }
-        }
-
-    static defaultResponse<R>(promise: AxiosPromise<R>, actions: ApiActions, mapKeys = true): Promise<R> {
-        const reqId = uuid();
-        actions.progressFn(reqId, true);
-        return promise
-            .then(data => {
-                actions.progressFn(reqId, false);
-                return data;
-            })
-            .then((response: { data: any }) => {
-                return mapKeys ? CommonResourceService.mapResponseKeys(response) : response.data;
-            })
-            .catch(({ response }) => {
-                actions.progressFn(reqId, false);
-                const errors = CommonResourceService.mapResponseKeys(response) as Errors;
-                actions.errorFn(reqId, errors);
-                throw errors;
-            });
-    }
-
-    protected serverApi: AxiosInstance;
-    protected resourceType: string;
-    protected actions: ApiActions;
+export class CommonResourceService<T extends Resource> extends CommonService<T> {
 
     constructor(serverApi: AxiosInstance, resourceType: string, actions: ApiActions) {
-        this.serverApi = serverApi;
-        this.resourceType = '/' + resourceType + '/';
-        this.actions = actions;
-    }
-
-    create(data?: Partial<T>) {
-        return CommonResourceService.defaultResponse(
-            this.serverApi
-                .post<T>(this.resourceType, data && CommonResourceService.mapKeys(_.snakeCase)(data)),
-            this.actions
-        );
-    }
-
-    delete(uuid: string): Promise<T> {
-        return CommonResourceService.defaultResponse(
-            this.serverApi
-                .delete(this.resourceType + uuid),
-            this.actions
-        );
-    }
-
-    get(uuid: string) {
-        return CommonResourceService.defaultResponse(
-            this.serverApi
-                .get<T>(this.resourceType + uuid),
-            this.actions
-        );
-    }
-
-    list(args: ListArguments = {}): Promise<ListResults<T>> {
-        const { filters, order, ...other } = args;
-        const params = {
-            ...other,
-            filters: filters ? `[${filters}]` : undefined,
-            order: order ? order : undefined
-        };
-        return CommonResourceService.defaultResponse(
-            this.serverApi
-                .get(this.resourceType, {
-                    params: CommonResourceService.mapKeys(_.snakeCase)(params)
-                }),
-            this.actions
-        );
-    }
-
-    update(uuid: string, data: Partial<T>) {
-        return CommonResourceService.defaultResponse(
-            this.serverApi
-                .put<T>(this.resourceType + uuid, data && CommonResourceService.mapKeys(_.snakeCase)(data)),
-            this.actions
-        );
+        super(serverApi, resourceType, actions);
     }
+    
 }
 
 export const getCommonResourceServiceError = (errorResponse: any) => {
diff --git a/src/services/common-service/common-service.ts b/src/services/common-service/common-service.ts
new file mode 100644 (file)
index 0000000..b301a72
--- /dev/null
@@ -0,0 +1,131 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import * as _ from "lodash";
+import { AxiosInstance, AxiosPromise } from "axios";
+import * as uuid from "uuid/v4";
+import { ApiActions } from "~/services/api/api-actions";
+
+interface Errors {
+    errors: string[];
+    errorToken: string;
+}
+
+export interface ListArguments {
+    limit?: number;
+    offset?: number;
+    filters?: string;
+    order?: string;
+    select?: string[];
+    distinct?: boolean;
+    count?: string;
+}
+
+export interface ListResults<T> {
+    kind: string;
+    offset: number;
+    limit: number;
+    items: T[];
+    itemsAvailable: number;
+}
+
+export class CommonService<T> {
+    protected serverApi: AxiosInstance;
+    protected resourceType: string;
+    protected actions: ApiActions;
+
+    constructor(serverApi: AxiosInstance, resourceType: string, actions: ApiActions) {
+        this.serverApi = serverApi;
+        this.resourceType = '/' + resourceType + '/';
+        this.actions = actions;
+    }
+
+    static mapResponseKeys = (response: { data: any }) =>
+        CommonService.mapKeys(_.camelCase)(response.data)
+
+    static mapKeys = (mapFn: (key: string) => string) =>
+        (value: any): any => {
+            switch (true) {
+                case _.isPlainObject(value):
+                    return Object
+                        .keys(value)
+                        .map(key => [key, mapFn(key)])
+                        .reduce((newValue, [key, newKey]) => ({
+                            ...newValue,
+                            [newKey]: CommonService.mapKeys(mapFn)(value[key])
+                        }), {});
+                case _.isArray(value):
+                    return value.map(CommonService.mapKeys(mapFn));
+                default:
+                    return value;
+            }
+        }
+
+    static defaultResponse<R>(promise: AxiosPromise<R>, actions: ApiActions, mapKeys = true): Promise<R> {
+        const reqId = uuid();
+        actions.progressFn(reqId, true);
+        return promise
+            .then(data => {
+                actions.progressFn(reqId, false);
+                return data;
+            })
+            .then((response: { data: any }) => {
+                return mapKeys ? CommonService.mapResponseKeys(response) : response.data;
+            })
+            .catch(({ response }) => {
+                actions.progressFn(reqId, false);
+                const errors = CommonService.mapResponseKeys(response) as Errors;
+                actions.errorFn(reqId, errors);
+                throw errors;
+            });
+    }
+
+    create(data?: Partial<T>) {
+        return CommonService.defaultResponse(
+            this.serverApi
+                .post<T>(this.resourceType, data && CommonService.mapKeys(_.snakeCase)(data)),
+            this.actions
+        );
+    }
+
+    delete(uuid: string): Promise<T> {
+        return CommonService.defaultResponse(
+            this.serverApi
+                .delete(this.resourceType + uuid),
+            this.actions
+        );
+    }
+
+    get(uuid: string) {
+        return CommonService.defaultResponse(
+            this.serverApi
+                .get<T>(this.resourceType + uuid),
+            this.actions
+        );
+    }
+
+    list(args: ListArguments = {}): Promise<ListResults<T>> {
+        const { filters, order, ...other } = args;
+        const params = {
+            ...other,
+            filters: filters ? `[${filters}]` : undefined,
+            order: order ? order : undefined
+        };
+        return CommonService.defaultResponse(
+            this.serverApi
+                .get(this.resourceType, {
+                    params: CommonService.mapKeys(_.snakeCase)(params)
+                }),
+            this.actions
+        );
+    }
+
+    update(uuid: string, data: Partial<T>) {
+        return CommonService.defaultResponse(
+            this.serverApi
+                .put<T>(this.resourceType + uuid, data && CommonService.mapKeys(_.snakeCase)(data)),
+            this.actions
+        );
+    }
+}
\ No newline at end of file
index 92b0713dbcc6ee2ce8b0eb0939d4cb928710676b..c41b2b992e10aafd33f07353f17087834ecf8a68 100644 (file)
@@ -6,7 +6,7 @@ import { LinkService } from "../link-service/link-service";
 import { GroupsService, GroupContentsResource } from "../groups-service/groups-service";
 import { LinkClass } from "~/models/link";
 import { FilterBuilder, joinFilters } from "~/services/api/filter-builder";
-import { ListResults } from "~/services/common-service/common-resource-service";
+import { ListResults } from '~/services/common-service/common-service';
 
 export interface FavoriteListArguments {
     limit?: number;
index d1e2eff2791c101ef7fd21b2b52ff6e6fb0ed438..d8b33f601f94c553e79e8be078f0dc2c9c4ee62f 100644 (file)
@@ -3,7 +3,8 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import * as _ from "lodash";
-import { CommonResourceService, ListResults, ListArguments } from '~/services/common-service/common-resource-service';
+import { CommonResourceService } from '~/services/common-service/common-resource-service';
+import { ListResults, ListArguments } from '~/services/common-service/common-service';
 import { AxiosInstance } from "axios";
 import { CollectionResource } from "~/models/collection";
 import { ProjectResource } from "~/models/project";
index 4bb0fe0934eecde90c1d2621745b43477b0dd6db..763844e0663552448cfd0f75ebe0a2ed987e2e04 100644 (file)
@@ -4,8 +4,9 @@
 
 import { LinkService } from "~/services/link-service/link-service";
 import { PermissionResource } from "~/models/permission";
-import { ListArguments, ListResults, CommonResourceService } from '~/services/common-service/common-resource-service';
+import { CommonResourceService } from '~/services/common-service/common-resource-service';
 import { LinkClass } from '../../models/link';
+import { ListArguments, ListResults } from '~/services/common-service/common-service';
 
 export class PermissionService extends LinkService<PermissionResource> {
 
index d60034711ed8402e654c3fa43494c963952a0a4a..5c686aae67fd5db06251071bacbc591b5c5f0f51 100644 (file)
@@ -5,7 +5,7 @@
 import { GroupsService } from "../groups-service/groups-service";
 import { ProjectResource } from "~/models/project";
 import { GroupClass } from "~/models/group";
-import { ListArguments } from "~/services/common-service/common-resource-service";
+import { ListArguments } from "~/services/common-service/common-service";
 import { FilterBuilder, joinFilters } from "~/services/api/filter-builder";
 import { TrashableResourceService } from '~/services/common-service/trashable-resource-service';
 import { snakeCase } from 'lodash';
index d524405fe62000a889d980520e00ef0b9e771e79..59fe2d4704ee194e6a5f0cf684c09b3629342ada 100644 (file)
@@ -3,6 +3,7 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import Axios from "axios";
+import { ApiClientAuthorizationService } from '~/services/api-client-authorization-service/api-client-authorization-service';
 import { AuthService } from "./auth-service/auth-service";
 import { GroupsService } from "./groups-service/groups-service";
 import { ProjectService } from "./project-service/project-service";
@@ -39,6 +40,7 @@ export const createServices = (config: Config, actions: ApiActions) => {
     const webdavClient = new WebDAV();
     webdavClient.defaults.baseURL = config.keepWebServiceUrl;
 
+    const apiClientAuthorizationService = new ApiClientAuthorizationService(apiClient, actions);
     const authorizedKeysService = new AuthorizedKeysService(apiClient, actions);
     const containerRequestService = new ContainerRequestService(apiClient, actions);
     const containerService = new ContainerService(apiClient, actions);
@@ -66,6 +68,7 @@ export const createServices = (config: Config, actions: ApiActions) => {
     return {
         ancestorsService,
         apiClient,
+        apiClientAuthorizationService,
         authService,
         authorizedKeysService,
         collectionFilesService,
index 6b20f8b328a2ac555552031d5732834a6912fdc8..a77ffcca8ca7c1b325937f0d6f7f5be98edd478c 100644 (file)
@@ -14,14 +14,15 @@ import { CollectionResource } from '~/models/collection';
 import { ProjectResource } from '~/models/project';
 import { ServiceRepository } from '~/services/services';
 import { FilterBuilder } from '~/services/api/filter-builder';
+import { ListResults } from '~/services/common-service/common-service';
 import { RepositoryResource } from '~/models/repositories';
 import { SshKeyResource } from '~/models/ssh-key';
 import { VirtualMachinesResource } from '~/models/virtual-machines';
 import { UserResource } from '~/models/user';
-import { ListResults } from '~/services/common-service/common-resource-service';
 import { LinkResource } from '~/models/link';
 import { KeepServiceResource } from '~/models/keep-services';
 import { NodeResource } from '~/models/node';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
 
 export const ADVANCED_TAB_DIALOG = 'advancedTabDialog';
 
@@ -74,7 +75,8 @@ enum ResourcePrefix {
     AUTORIZED_KEYS = 'authorized_keys',
     VIRTUAL_MACHINES = 'virtual_machines',
     KEEP_SERVICES = 'keep_services',
-    COMPUTE_NODES = 'nodes'
+    COMPUTE_NODES = 'nodes',
+    API_CLIENT_AUTHORIZATIONS = 'api_client_authorizations'
 }
 
 enum KeepServiceData {
@@ -87,9 +89,14 @@ enum ComputeNodeData {
     PROPERTIES = 'properties'
 }
 
-type AdvanceResourceKind = CollectionData | ProcessData | ProjectData | RepositoryData | SshKeyData | VirtualMachineData | KeepServiceData | ComputeNodeData;
+enum ApiClientAuthorizationsData {
+    API_CLIENT_AUTHORIZATION = 'api_client_authorization',
+    DEFAULT_OWNER_UUID = 'default_owner_uuid'
+}
+
+type AdvanceResourceKind = CollectionData | ProcessData | ProjectData | RepositoryData | SshKeyData | VirtualMachineData | KeepServiceData | ComputeNodeData | ApiClientAuthorizationsData;
 type AdvanceResourcePrefix = GroupContentsResourcePrefix | ResourcePrefix;
-type AdvanceResponseData = ContainerRequestResource | ProjectResource | CollectionResource | RepositoryResource | SshKeyResource | VirtualMachinesResource | KeepServiceResource | NodeResource | undefined;
+type AdvanceResponseData = ContainerRequestResource | ProjectResource | CollectionResource | RepositoryResource | SshKeyResource | VirtualMachinesResource | KeepServiceResource | NodeResource | ApiClientAuthorization | undefined;
 
 export const openAdvancedTabDialog = (uuid: string) =>
     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
@@ -215,6 +222,21 @@ export const openAdvancedTabDialog = (uuid: string) =>
                 });
                 dispatch<any>(initAdvancedTabDialog(advanceDataComputeNode));
                 break;
+            case ResourceKind.API_CLIENT_AUTHORIZATION:
+                const dataApiClientAuthorization = getState().apiClientAuthorizations.find(item => item.uuid === uuid);
+                const advanceDataApiClientAuthorization = advancedTabData({
+                    uuid,
+                    metadata: '',
+                    user: '',
+                    apiResponseKind: apiClientAuthorizationApiResponse,
+                    data: dataApiClientAuthorization,
+                    resourceKind: ApiClientAuthorizationsData.API_CLIENT_AUTHORIZATION,
+                    resourcePrefix: ResourcePrefix.API_CLIENT_AUTHORIZATIONS,
+                    resourceKindProperty: ApiClientAuthorizationsData.DEFAULT_OWNER_UUID,
+                    property: dataApiClientAuthorization!.defaultOwnerUuid
+                });
+                dispatch<any>(initAdvancedTabDialog(advanceDataApiClientAuthorization));
+                break;
             default:
                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: "Could not open advanced tab for this resource.", hideDuration: 2000, kind: SnackbarKind.ERROR }));
         }
@@ -487,5 +509,27 @@ const computeNodeApiResponse = (apiResponse: NodeResource) => {
 "properties": "${JSON.stringify(properties, null, 4)}",
 "info": "${JSON.stringify(info, null, 4)}"`;
 
+    return response;
+};
+
+const apiClientAuthorizationApiResponse = (apiResponse: ApiClientAuthorization) => {
+    const {
+        uuid, ownerUuid, apiToken, apiClientId, userId, createdByIpAddress, lastUsedByIpAddress, 
+        lastUsedAt, expiresAt, defaultOwnerUuid, scopes, updatedAt, createdAt
+    } = apiResponse;
+    const response = `"uuid": "${uuid}",
+"owner_uuid": "${ownerUuid}",
+"api_token": "${stringify(apiToken)}",
+"api_client_id": "${stringify(apiClientId)}",
+"user_id": "${stringify(userId)}",
+"created_by_ip_address": "${stringify(createdByIpAddress)}",
+"last_used_by_ip_address": "${stringify(lastUsedByIpAddress)}",
+"last_used_at": "${stringify(lastUsedAt)}",
+"expires_at": "${stringify(expiresAt)}",
+"created_at": "${stringify(createdAt)}",
+"updated_at": "${stringify(updatedAt)}",
+"default_owner_uuid": "${stringify(defaultOwnerUuid)}",
+"scopes": "${JSON.stringify(scopes, null, 4)}"`;
+
     return response;
 };
\ No newline at end of file
diff --git a/src/store/api-client-authorizations/api-client-authorizations-actions.ts b/src/store/api-client-authorizations/api-client-authorizations-actions.ts
new file mode 100644 (file)
index 0000000..8ed8a38
--- /dev/null
@@ -0,0 +1,82 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { Dispatch } from "redux";
+import { unionize, ofType, UnionOf } from "~/common/unionize";
+import { RootState } from '~/store/store';
+import { setBreadcrumbs } from '~/store/breadcrumbs/breadcrumbs-actions';
+import { ServiceRepository } from "~/services/services";
+import { dialogActions } from '~/store/dialog/dialog-actions';
+import { snackbarActions } from '~/store/snackbar/snackbar-actions';
+import { navigateToRootProject } from '~/store/navigation/navigation-action';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
+
+export const apiClientAuthorizationsActions = unionize({
+    SET_API_CLIENT_AUTHORIZATIONS: ofType<ApiClientAuthorization[]>(),
+    REMOVE_API_CLIENT_AUTHORIZATION: ofType<string>()
+});
+
+export type ApiClientAuthorizationsActions = UnionOf<typeof apiClientAuthorizationsActions>;
+
+export const API_CLIENT_AUTHORIZATION_REMOVE_DIALOG = 'apiClientAuthorizationRemoveDialog';
+export const API_CLIENT_AUTHORIZATION_ATTRIBUTES_DIALOG = 'apiClientAuthorizationAttributesDialog';
+export const API_CLIENT_AUTHORIZATION_HELP_DIALOG = 'apiClientAuthorizationHelpDialog';
+
+export const loadApiClientAuthorizationsPanel = () =>
+    async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
+        const user = getState().auth.user;
+        if (user && user.isAdmin) {
+            try {
+                dispatch(setBreadcrumbs([{ label: 'Api client authorizations' }]));
+                const response = await services.apiClientAuthorizationService.list();
+                dispatch(apiClientAuthorizationsActions.SET_API_CLIENT_AUTHORIZATIONS(response.items));
+            } catch (e) {
+                dispatch(snackbarActions.OPEN_SNACKBAR({ message: "You don't have permissions to view this page", hideDuration: 2000 }));
+                return;
+            }
+        } else {
+            dispatch(navigateToRootProject);
+            dispatch(snackbarActions.OPEN_SNACKBAR({ message: "You don't have permissions to view this page", hideDuration: 2000 }));
+        }
+    };
+
+export const openApiClientAuthorizationAttributesDialog = (uuid: string) =>
+    (dispatch: Dispatch, getState: () => RootState) => {
+        const apiClientAuthorization = getState().apiClientAuthorizations.find(node => node.uuid === uuid);
+        dispatch(dialogActions.OPEN_DIALOG({ id: API_CLIENT_AUTHORIZATION_ATTRIBUTES_DIALOG, data: { apiClientAuthorization } }));
+    };
+
+export const openApiClientAuthorizationRemoveDialog = (uuid: string) =>
+    (dispatch: Dispatch, getState: () => RootState) => {
+        dispatch(dialogActions.OPEN_DIALOG({
+            id: API_CLIENT_AUTHORIZATION_REMOVE_DIALOG,
+            data: {
+                title: 'Remove api client authorization',
+                text: 'Are you sure you want to remove this api client authorization?',
+                confirmButtonLabel: 'Remove',
+                uuid
+            }
+        }));
+    };
+
+export const removeApiClientAuthorization = (uuid: string) =>
+    async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+        dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removing ...' }));
+        try {
+            await services.apiClientAuthorizationService.delete(uuid);
+            dispatch(apiClientAuthorizationsActions.REMOVE_API_CLIENT_AUTHORIZATION(uuid));
+            dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Api client authorization has been successfully removed.', hideDuration: 2000 }));
+        } catch (e) {
+            return;
+        }
+    };
+
+export const openApiClientAuthorizationsHelpDialog = () =>
+    (dispatch: Dispatch, getState: () => RootState) => {
+        const apiHost = getState().properties.apiHost;
+        const user = getState().auth.user;
+        const email = user ? user.email : '';
+        const apiToken = getState().auth.apiToken;
+        dispatch(dialogActions.OPEN_DIALOG({ id: API_CLIENT_AUTHORIZATION_HELP_DIALOG, data: { apiHost, apiToken, email } }));
+    };
\ No newline at end of file
diff --git a/src/store/api-client-authorizations/api-client-authorizations-reducer.ts b/src/store/api-client-authorizations/api-client-authorizations-reducer.ts
new file mode 100644 (file)
index 0000000..7084dea
--- /dev/null
@@ -0,0 +1,22 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { 
+    apiClientAuthorizationsActions, 
+    ApiClientAuthorizationsActions 
+} from '~/store/api-client-authorizations/api-client-authorizations-actions';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
+
+export type ApiClientAuthorizationsState = ApiClientAuthorization[];
+
+const initialState: ApiClientAuthorizationsState = [];
+
+export const apiClientAuthorizationsReducer = 
+    (state: ApiClientAuthorizationsState = initialState, action: ApiClientAuthorizationsActions): ApiClientAuthorizationsState =>
+        apiClientAuthorizationsActions.match(action, {
+            SET_API_CLIENT_AUTHORIZATIONS: apiClientAuthorizations => apiClientAuthorizations,
+            REMOVE_API_CLIENT_AUTHORIZATION: (uuid: string) => 
+                state.filter((apiClientAuthorization) => apiClientAuthorization.uuid !== uuid),
+            default: () => state
+        });
\ No newline at end of file
index 4ed348751faa6a516eb07bcf3cb2c18688534e01..1e2620e48c790838e87d76ee0ab45317170e3a5f 100644 (file)
@@ -161,5 +161,4 @@ export const loadSshKeysPanel = () =>
         }
     };
 
-
 export type AuthAction = UnionOf<typeof authActions>;
index a4017db3be7af4b83a69543fdc85d825516ec149..b9f768f1cb0a42a9653d119cc577e516b21407ba 100644 (file)
@@ -30,6 +30,8 @@ describe('auth-reducer', () => {
             lastName: "Doe",
             uuid: "uuid",
             ownerUuid: "ownerUuid",
+            identityUrl: "identityUrl",
+            prefs: {},
             isAdmin: false
         };
         const state = reducer(initialState, authActions.INIT({ user, token: "token" }));
@@ -60,6 +62,8 @@ describe('auth-reducer', () => {
             lastName: "Doe",
             uuid: "uuid",
             ownerUuid: "ownerUuid",
+            identityUrl: "identityUrl",
+            prefs: {},
             isAdmin: false
         };
 
index 65ddcff2c7f1b360baa0e4ea98587cdb9bbbc179..b7d6cb260c7b7be319648e48c787ee231aba7052 100644 (file)
@@ -18,6 +18,7 @@ import { SshKeyResource } from '~/models/ssh-key';
 import { VirtualMachinesResource } from '~/models/virtual-machines';
 import { KeepServiceResource } from '~/models/keep-services';
 import { NodeResource } from '~/models/node';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
 
 export const contextMenuActions = unionize({
     OPEN_CONTEXT_MENU: ofType<{ position: ContextMenuPosition, resource: ContextMenuResource }>(),
@@ -121,6 +122,18 @@ export const openComputeNodeContextMenu = (event: React.MouseEvent<HTMLElement>,
         }));
     };
 
+export const openApiClientAuthorizationContextMenu = 
+    (event: React.MouseEvent<HTMLElement>, apiClientAuthorization: ApiClientAuthorization) =>
+        (dispatch: Dispatch) => {
+            dispatch<any>(openContextMenu(event, {
+                name: '',
+                uuid: apiClientAuthorization.uuid,
+                ownerUuid: apiClientAuthorization.ownerUuid,
+                kind: ResourceKind.API_CLIENT_AUTHORIZATION,
+                menuKind: ContextMenuKind.API_CLIENT_AUTHORIZATION
+            }));
+        };
+
 export const openRootProjectContextMenu = (event: React.MouseEvent<HTMLElement>, projectUuid: string) =>
     (dispatch: Dispatch, getState: () => RootState) => {
         const res = getResource<UserResource>(projectUuid)(getState().resources);
index 80ab514cb41440b9a3356f62ed6379a4ec08896c..82ba5b4b8e517e9ad6541f228e53213e9ab3f81b 100644 (file)
@@ -6,7 +6,7 @@ import { Dispatch, MiddlewareAPI } from "redux";
 import { RootState } from "../store";
 import { DataColumns } from "~/components/data-table/data-table";
 import { DataExplorer } from './data-explorer-reducer';
-import { ListResults } from '~/services/common-service/common-resource-service';
+import { ListResults } from '~/services/common-service/common-service';
 import { createTree } from "~/models/tree";
 import { DataTableFilters } from "~/components/data-table-filters/data-table-filters-tree";
 
diff --git a/src/store/my-account/my-account-panel-actions.ts b/src/store/my-account/my-account-panel-actions.ts
new file mode 100644 (file)
index 0000000..34bb269
--- /dev/null
@@ -0,0 +1,31 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { Dispatch } from "redux";
+import { RootState } from "~/store/store";
+import { initialize } from "redux-form";
+import { ServiceRepository } from "~/services/services";
+import { setBreadcrumbs } from "~/store/breadcrumbs/breadcrumbs-actions";
+import { authActions } from "~/store/auth/auth-action";
+import { snackbarActions, SnackbarKind } from "~/store/snackbar/snackbar-actions";
+
+export const MY_ACCOUNT_FORM = 'myAccountForm';
+
+export const loadMyAccountPanel = () =>
+    (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
+        dispatch(setBreadcrumbs([{ label: 'User profile'}]));
+    };
+
+export const saveEditedUser = (resource: any) =>
+    async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
+        try {
+            await services.userService.update(resource.uuid, resource);
+            services.authService.saveUser(resource);
+            dispatch(authActions.USER_DETAILS_SUCCESS(resource));
+            dispatch(initialize(MY_ACCOUNT_FORM, resource));
+            dispatch(snackbarActions.OPEN_SNACKBAR({ message: "Profile has been updated.", hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
+        } catch(e) {
+            return;
+        }
+    };
index 50cfd88d326e8fe97a4610b6b27b6ab842a8a092..067a9ac487f0869e038c00b67cd75c8f1f9d2985 100644 (file)
@@ -68,6 +68,10 @@ export const navigateToRepositories = push(Routes.REPOSITORIES);
 
 export const navigateToSshKeys= push(Routes.SSH_KEYS);
 
+export const navigateToMyAccount = push(Routes.MY_ACCOUNT);
+
 export const navigateToKeepServices = push(Routes.KEEP_SERVICES);
 
-export const navigateToComputeNodes = push(Routes.COMPUTE_NODES);
\ No newline at end of file
+export const navigateToComputeNodes = push(Routes.COMPUTE_NODES);
+
+export const navigateToApiClientAuthorizations = push(Routes.API_CLIENT_AUTHORIZATIONS);
\ No newline at end of file
index 36672e99ac19003ede9f9ade9240d870de496d14..f2cc8a9229d8fbe3798a732e32172f76c18fa555 100644 (file)
@@ -25,7 +25,7 @@ import { getProperty } from "~/store/properties/properties";
 import { snackbarActions, SnackbarKind } from '../snackbar/snackbar-actions';
 import { progressIndicatorActions } from '~/store/progress-indicator/progress-indicator-actions.ts';
 import { DataExplorer, getDataExplorer } from '../data-explorer/data-explorer-reducer';
-import { ListResults } from '~/services/common-service/common-resource-service';
+import { ListResults } from '~/services/common-service/common-service';
 import { loadContainers } from '../processes/processes-actions';
 import { ResourceKind } from '~/models/resource';
 import { getResource } from "~/store/resources/resources";
index 1bd294f112ed636afa68fd0e7a547a4931df793b..d8b4d7e76f7e6c6616f6b69b1d7779fd9cbd2238 100644 (file)
@@ -13,7 +13,7 @@ import { SortDirection } from '~/components/data-table/data-column';
 import { SearchResultsPanelColumnNames } from '~/views/search-results-panel/search-results-panel-view';
 import { OrderDirection, OrderBuilder } from '~/services/api/order-builder';
 import { GroupContentsResource, GroupContentsResourcePrefix } from "~/services/groups-service/groups-service";
-import { ListResults } from '~/services/common-service/common-resource-service';
+import { ListResults } from '~/services/common-service/common-service';
 import { searchResultsPanelActions } from '~/store/search-results-panel/search-results-panel-actions';
 import { getFilters } from '~/store/search-bar/search-bar-actions';
 import { getSortColumn } from "~/store/data-explorer/data-explorer-reducer";
index c139b429da435b734cfac187543b923d2e0818b2..9e76d46da7a30ef8f0b782b8bf701fbb1e47487e 100644 (file)
@@ -12,7 +12,7 @@ import { updateResources } from '~/store/resources/resources-actions';
 import { loadMissingProcessesInformation, getFilters } from '~/store/project-panel/project-panel-middleware-service';
 import { snackbarActions } from '~/store/snackbar/snackbar-actions';
 import { sharedWithMePanelActions } from './shared-with-me-panel-actions';
-import { ListResults } from '~/services/common-service/common-resource-service';
+import { ListResults } from '~/services/common-service/common-service';
 import { GroupContentsResource, GroupContentsResourcePrefix } from '~/services/groups-service/groups-service';
 import { SortDirection } from '~/components/data-table/data-column';
 import { OrderBuilder, OrderDirection } from '~/services/api/order-builder';
index 321a19b6f25182072d405e29e8b308457b4162df..eef047508274ba2bf6cba1f3be5e6534540b6111 100644 (file)
@@ -47,6 +47,7 @@ import { virtualMachinesReducer } from "~/store/virtual-machines/virtual-machine
 import { repositoriesReducer } from '~/store/repositories/repositories-reducer';
 import { keepServicesReducer } from '~/store/keep-services/keep-services-reducer';
 import { computeNodesReducer } from '~/store/compute-nodes/compute-nodes-reducer';
+import { apiClientAuthorizationsReducer } from '~/store/api-client-authorizations/api-client-authorizations-reducer';
 
 const composeEnhancers =
     (process.env.NODE_ENV === 'development' &&
@@ -119,5 +120,6 @@ const createRootReducer = (services: ServiceRepository) => combineReducers({
     virtualMachines: virtualMachinesReducer,
     repositories: repositoriesReducer,
     keepServices: keepServicesReducer,
-    computeNodes: computeNodesReducer
+    computeNodes: computeNodesReducer,
+    apiClientAuthorizations: apiClientAuthorizationsReducer
 });
index c95277b3a4c412149d4d2f3606a21f0bf3fc699f..0aaa9050d7276cd4eef159b53166d5a34032182b 100644 (file)
@@ -11,7 +11,7 @@ import { formatDate } from "~/common/formatters";
 import { unionize, ofType, UnionOf } from "~/common/unionize";
 import { VirtualMachineLogins } from '~/models/virtual-machines';
 import { FilterBuilder } from "~/services/api/filter-builder";
-import { ListResults } from "~/services/common-service/common-resource-service";
+import { ListResults } from "~/services/common-service/common-service";
 import { dialogActions } from '~/store/dialog/dialog-actions';
 import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
 
index 475ad7523896eeb2f63bd96efe92bfa3ce44ea8a..3ee90d57d60a7fbe9280ca89d0027a47a0619917 100644 (file)
@@ -3,7 +3,7 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import { virtualMachinesActions, VirtualMachineActions } from '~/store/virtual-machines/virtual-machines-actions';
-import { ListResults } from '~/services/common-service/common-resource-service';
+import { ListResults } from '~/services/common-service/common-service';
 import { VirtualMachineLogins } from '~/models/virtual-machines';
 
 interface VirtualMachines {
index e3f96a9c07de620385640dd43445ca566c276f8b..fdc91f43d51fd9bfa8aaea918c258391ed06fe3b 100644 (file)
@@ -40,6 +40,7 @@ import { loadSharedWithMePanel } from '~/store/shared-with-me-panel/shared-with-
 import { CopyFormDialogData } from '~/store/copy-dialog/copy-dialog';
 import { loadWorkflowPanel, workflowPanelActions } from '~/store/workflow-panel/workflow-panel-actions';
 import { loadSshKeysPanel } from '~/store/auth/auth-action';
+import { loadMyAccountPanel } from '~/store/my-account/my-account-panel-actions';
 import { workflowPanelColumns } from '~/views/workflow-panel/workflow-panel-view';
 import { progressIndicatorActions } from '~/store/progress-indicator/progress-indicator-actions';
 import { getProgressIndicator } from '~/store/progress-indicator/progress-indicator-reducer';
@@ -58,6 +59,7 @@ import { loadVirtualMachinesPanel } from '~/store/virtual-machines/virtual-machi
 import { loadRepositoriesPanel } from '~/store/repositories/repositories-actions';
 import { loadKeepServicesPanel } from '~/store/keep-services/keep-services-actions';
 import { loadComputeNodesPanel } from '~/store/compute-nodes/compute-nodes-actions';
+import { loadApiClientAuthorizationsPanel } from '~/store/api-client-authorizations/api-client-authorizations-actions';
 
 export const WORKBENCH_LOADING_SCREEN = 'workbenchLoadingScreen';
 
@@ -412,6 +414,11 @@ export const loadSshKeys = handleFirstTimeLoad(
         await dispatch(loadSshKeysPanel());
     });
 
+export const loadMyAccount = handleFirstTimeLoad(
+    (dispatch: Dispatch<any>) => {
+        dispatch(loadMyAccountPanel());
+    });
+
 export const loadKeepServices = handleFirstTimeLoad(
     async (dispatch: Dispatch<any>) => {
         await dispatch(loadKeepServicesPanel());
@@ -422,6 +429,11 @@ export const loadComputeNodes = handleFirstTimeLoad(
         await dispatch(loadComputeNodesPanel());
     });
 
+export const loadApiClientAuthorizations = handleFirstTimeLoad(
+    async (dispatch: Dispatch<any>) => {
+        await dispatch(loadApiClientAuthorizationsPanel());
+    });
+
 const finishLoadingProject = (project: GroupContentsResource | string) =>
     async (dispatch: Dispatch<any>) => {
         const uuid = typeof project === 'string' ? project : project.uuid;
index fefcb325e24dc8fe406c2b92545309e5e33db11d..2cd910bda106dc11b2976e24088120a0ec9913d3 100644 (file)
@@ -14,7 +14,7 @@ import { SortDirection } from '~/components/data-table/data-column';
 import { WorkflowPanelColumnNames } from '~/views/workflow-panel/workflow-panel-view';
 import { OrderDirection, OrderBuilder } from '~/services/api/order-builder';
 import { WorkflowResource } from '~/models/workflow';
-import { ListResults } from '~/services/common-service/common-resource-service';
+import { ListResults } from '~/services/common-service/common-service';
 import { workflowPanelActions } from './workflow-panel-actions';
 import { getSortColumn } from "~/store/data-explorer/data-explorer-reducer";
 
index c601df17416d8711be048d51144684703fa4fe8c..a3f5df2e22d24df4f0c5eb7892298994451432c4 100644 (file)
@@ -26,3 +26,5 @@ export const REPOSITORY_NAME_VALIDATION = [require, maxLength(255)];
 
 export const SSH_KEY_PUBLIC_VALIDATION = [require, isRsaKey, maxLength(1024)];
 export const SSH_KEY_NAME_VALIDATION = [require, maxLength(255)];
+
+export const MY_ACCOUNT_VALIDATION = [require];
diff --git a/src/views-components/api-client-authorizations-dialog/attributes-dialog.tsx b/src/views-components/api-client-authorizations-dialog/attributes-dialog.tsx
new file mode 100644 (file)
index 0000000..e7defd6
--- /dev/null
@@ -0,0 +1,78 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import * as React from "react";
+import { compose } from 'redux';
+import {
+    withStyles, Dialog, DialogTitle, DialogContent, DialogActions,
+    Button, StyleRulesCallback, WithStyles, Grid
+} from '@material-ui/core';
+import { WithDialogProps, withDialog } from "~/store/dialog/with-dialog";
+import { API_CLIENT_AUTHORIZATION_ATTRIBUTES_DIALOG } from '~/store/api-client-authorizations/api-client-authorizations-actions';
+import { ArvadosTheme } from '~/common/custom-theme';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
+import { formatDate } from '~/common/formatters';
+
+type CssRules = 'root';
+
+const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
+    root: {
+        fontSize: '0.875rem',
+        '& div:nth-child(odd)': {
+            textAlign: 'right',
+            color: theme.palette.grey["500"]
+        }
+    }
+});
+
+interface AttributesKeepServiceDialogDataProps {
+    apiClientAuthorization: ApiClientAuthorization;
+}
+
+export const AttributesApiClientAuthorizationDialog = compose(
+    withDialog(API_CLIENT_AUTHORIZATION_ATTRIBUTES_DIALOG),
+    withStyles(styles))(
+        ({ open, closeDialog, data, classes }: WithDialogProps<AttributesKeepServiceDialogDataProps> & WithStyles<CssRules>) =>
+            <Dialog open={open} onClose={closeDialog} fullWidth maxWidth='sm'>
+                <DialogTitle>Attributes</DialogTitle>
+                <DialogContent>
+                    {data.apiClientAuthorization && <Grid container direction="row" spacing={16} className={classes.root}>
+                        <Grid item xs={5}>UUID</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.uuid}</Grid>
+                        <Grid item xs={5}>Owner uuid</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.ownerUuid}</Grid>
+                        <Grid item xs={5}>API Client ID</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.apiClientId}</Grid>
+                        <Grid item xs={5}>API Token</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.apiToken}</Grid>
+                        <Grid item xs={5}>Created by IP address</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.createdByIpAddress || '(none)'}</Grid>
+                        <Grid item xs={5}>Default owner</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.defaultOwnerUuid || '(none)'}</Grid>
+                        <Grid item xs={5}>Expires at</Grid>
+                        <Grid item xs={7}>{formatDate(data.apiClientAuthorization.expiresAt) || '(none)'}</Grid>
+                        <Grid item xs={5}>Last used at</Grid>
+                        <Grid item xs={7}>{formatDate(data.apiClientAuthorization.lastUsedAt) || '(none)'}</Grid>
+                        <Grid item xs={5}>Last used by IP address</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.lastUsedByIpAddress || '(none)'}</Grid>
+                        <Grid item xs={5}>Scopes</Grid>
+                        <Grid item xs={7}>{JSON.stringify(data.apiClientAuthorization.scopes || '(none)')}</Grid>
+                        <Grid item xs={5}>User ID</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.userId || '(none)'}</Grid>
+                        <Grid item xs={5}>Created at</Grid>
+                        <Grid item xs={7}>{formatDate(data.apiClientAuthorization.createdAt) || '(none)'}</Grid>
+                        <Grid item xs={5}>Updated at</Grid>
+                        <Grid item xs={7}>{formatDate(data.apiClientAuthorization.updatedAt) || '(none)'}</Grid>
+                    </Grid>}
+                </DialogContent>
+                <DialogActions>
+                    <Button
+                        variant='flat'
+                        color='primary'
+                        onClick={closeDialog}>
+                        Close
+                    </Button>
+                </DialogActions>
+            </Dialog>
+    );
\ No newline at end of file
diff --git a/src/views-components/api-client-authorizations-dialog/help-dialog.tsx b/src/views-components/api-client-authorizations-dialog/help-dialog.tsx
new file mode 100644 (file)
index 0000000..d2802fa
--- /dev/null
@@ -0,0 +1,66 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import * as React from "react";
+import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Typography } from "@material-ui/core";
+import { WithDialogProps } from "~/store/dialog/with-dialog";
+import { withDialog } from '~/store/dialog/with-dialog';
+import { DefaultCodeSnippet } from '~/components/default-code-snippet/default-code-snippet';
+import { StyleRulesCallback, WithStyles, withStyles } from '@material-ui/core/styles';
+import { ArvadosTheme } from '~/common/custom-theme';
+import { compose } from "redux";
+import { API_CLIENT_AUTHORIZATION_HELP_DIALOG } from '~/store/api-client-authorizations/api-client-authorizations-actions';
+
+type CssRules = 'codeSnippet';
+
+const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
+    codeSnippet: {
+        borderRadius: theme.spacing.unit * 0.5,
+        border: `1px solid ${theme.palette.grey["400"]}`,
+        '& pre': {
+            fontSize: '0.815rem'
+        }
+    }
+});
+
+interface HelpApiClientAuthorizationDataProps {
+    apiHost: string;
+    apiToken: string;
+    email: string;
+}
+
+export const HelpApiClientAuthorizationDialog = compose(
+    withDialog(API_CLIENT_AUTHORIZATION_HELP_DIALOG),
+    withStyles(styles))(
+        (props: WithDialogProps<HelpApiClientAuthorizationDataProps> & WithStyles<CssRules>) =>
+            <Dialog open={props.open}
+                onClose={props.closeDialog}
+                fullWidth
+                maxWidth='md'>
+                <DialogTitle>HELP:</DialogTitle>
+                <DialogContent>
+                    <DefaultCodeSnippet
+                        className={props.classes.codeSnippet}
+                        lines={[snippetText(props.data)]} />
+                        {/* // lines={snippetText2(props.data)} /> */}
+                </DialogContent>
+                <DialogActions>
+                    <Button
+                        variant='flat'
+                        color='primary'
+                        onClick={props.closeDialog}>
+                        Close
+                </Button>
+                </DialogActions>
+            </Dialog>
+    );
+
+const snippetText = (data: HelpApiClientAuthorizationDataProps) => `### Pasting the following lines at a shell prompt will allow Arvados SDKs
+### to authenticate to your account, ${data.email}
+
+read ARVADOS_API_TOKEN <<EOF
+${data.apiToken}
+EOF
+export ARVADOS_API_TOKEN ARVADOS_API_HOST=${data.apiHost}
+unset ARVADOS_API_HOST_INSECURE`;
diff --git a/src/views-components/api-client-authorizations-dialog/remove-dialog.tsx b/src/views-components/api-client-authorizations-dialog/remove-dialog.tsx
new file mode 100644 (file)
index 0000000..47b6adc
--- /dev/null
@@ -0,0 +1,20 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+import { Dispatch, compose } from 'redux';
+import { connect } from "react-redux";
+import { ConfirmationDialog } from "~/components/confirmation-dialog/confirmation-dialog";
+import { withDialog, WithDialogProps } from "~/store/dialog/with-dialog";
+import { API_CLIENT_AUTHORIZATION_REMOVE_DIALOG, removeApiClientAuthorization } from '~/store/api-client-authorizations/api-client-authorizations-actions';
+
+const mapDispatchToProps = (dispatch: Dispatch, props: WithDialogProps<any>) => ({
+    onConfirm: () => {
+        props.closeDialog();
+        dispatch<any>(removeApiClientAuthorization(props.data.uuid));
+    }
+});
+
+export const RemoveApiClientAuthorizationDialog = compose(
+    withDialog(API_CLIENT_AUTHORIZATION_REMOVE_DIALOG),
+    connect(null, mapDispatchToProps)
+)(ConfirmationDialog);
\ No newline at end of file
diff --git a/src/views-components/context-menu/action-sets/api-client-authorization-action-set.ts b/src/views-components/context-menu/action-sets/api-client-authorization-action-set.ts
new file mode 100644 (file)
index 0000000..b6f089a
--- /dev/null
@@ -0,0 +1,31 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import {
+    openApiClientAuthorizationAttributesDialog,
+    openApiClientAuthorizationRemoveDialog
+} from '~/store/api-client-authorizations/api-client-authorizations-actions';
+import { openAdvancedTabDialog } from '~/store/advanced-tab/advanced-tab';
+import { ContextMenuActionSet } from "~/views-components/context-menu/context-menu-action-set";
+import { AdvancedIcon, RemoveIcon, AttributesIcon } from "~/components/icon/icon";
+
+export const apiClientAuthorizationActionSet: ContextMenuActionSet = [[{
+    name: "Attributes",
+    icon: AttributesIcon,
+    execute: (dispatch, { uuid }) => {
+        dispatch<any>(openApiClientAuthorizationAttributesDialog(uuid));
+    }
+}, {
+    name: "Advanced",
+    icon: AdvancedIcon,
+    execute: (dispatch, { uuid }) => {
+        dispatch<any>(openAdvancedTabDialog(uuid));
+    }
+}, {
+    name: "Remove",
+    icon: RemoveIcon,
+    execute: (dispatch, { uuid }) => {
+        dispatch<any>(openApiClientAuthorizationRemoveDialog(uuid));
+    }
+}]];
index 3fa1ab30d83d5d994e7b94bbe49b356deee74009..35298d0e1a2403d52cec788856fcdfb5ee439087 100644 (file)
@@ -55,6 +55,7 @@ const getMenuActionSet = (resource?: ContextMenuResource): ContextMenuActionSet
 };
 
 export enum ContextMenuKind {
+    API_CLIENT_AUTHORIZATION = "ApiClientAuthorization",
     ROOT_PROJECT = "RootProject",
     PROJECT = "Project",
     RESOURCE = "Resource",
index f4232a129dd3c07b11d64d88f661eab40b79ab9c..415cba37c97b543da6ee41d4cb7dccce6f91a6c6 100644 (file)
@@ -12,7 +12,10 @@ import { logout } from '~/store/auth/auth-action';
 import { RootState } from "~/store/store";
 import { openCurrentTokenDialog } from '~/store/current-token-dialog/current-token-dialog-actions';
 import { openRepositoriesPanel } from "~/store/repositories/repositories-actions";
-import { navigateToSshKeys, navigateToKeepServices, navigateToComputeNodes } from '~/store/navigation/navigation-action';
+import { 
+    navigateToSshKeys, navigateToKeepServices, navigateToComputeNodes,
+    navigateToApiClientAuthorizations, navigateToMyAccount
+} from '~/store/navigation/navigation-action';
 import { openVirtualMachines } from "~/store/virtual-machines/virtual-machines-actions";
 
 interface AccountMenuProps {
@@ -37,9 +40,10 @@ export const AccountMenu = connect(mapStateToProps)(
                 <MenuItem onClick={() => dispatch(openRepositoriesPanel())}>Repositories</MenuItem>
                 <MenuItem onClick={() => dispatch(openCurrentTokenDialog)}>Current token</MenuItem>
                 <MenuItem onClick={() => dispatch(navigateToSshKeys)}>Ssh Keys</MenuItem>
+                { user.isAdmin && <MenuItem onClick={() => dispatch(navigateToApiClientAuthorizations)}>Api Tokens</MenuItem> }
                 { user.isAdmin && <MenuItem onClick={() => dispatch(navigateToKeepServices)}>Keep Services</MenuItem> }
                 { user.isAdmin && <MenuItem onClick={() => dispatch(navigateToComputeNodes)}>Compute Nodes</MenuItem> }
-                <MenuItem>My account</MenuItem>
+                <MenuItem onClick={() => dispatch(navigateToMyAccount)}>My account</MenuItem>
                 <MenuItem onClick={() => dispatch(logout())}>Logout</MenuItem>
             </DropdownMenu>
             : null);
index 78b79a8ed46bf0f70737fa412178d421fa0562fb..a3279e37730fcb4d874eb2f8605e8743e803d1e1 100644 (file)
@@ -20,7 +20,8 @@ const isButtonVisible = ({ router }: RootState) => {
     const pathname = router.location ? router.location.pathname : '';
     return !Routes.matchWorkflowRoute(pathname) && !Routes.matchVirtualMachineRoute(pathname) &&
         !Routes.matchRepositoriesRoute(pathname) && !Routes.matchSshKeysRoute(pathname) &&
-        !Routes.matchKeepServicesRoute(pathname) && !Routes.matchComputeNodesRoute(pathname);
+        !Routes.matchKeepServicesRoute(pathname) && !Routes.matchComputeNodesRoute(pathname) &&
+        !Routes.matchApiClientAuthorizationsRoute(pathname);
 };
 
 export const MainContentBar = connect((state: RootState) => ({
diff --git a/src/views/api-client-authorization-panel/api-client-authorization-panel-root.tsx b/src/views/api-client-authorization-panel/api-client-authorization-panel-root.tsx
new file mode 100644 (file)
index 0000000..52921b3
--- /dev/null
@@ -0,0 +1,104 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import * as React from 'react';
+import { 
+    StyleRulesCallback, WithStyles, withStyles, Card, CardContent, Grid, 
+    Table, TableHead, TableRow, TableCell, TableBody, Tooltip, IconButton
+} from '@material-ui/core';
+import { ArvadosTheme } from '~/common/custom-theme';
+import { MoreOptionsIcon, HelpIcon } from '~/components/icon/icon';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
+import { formatDate } from '~/common/formatters';
+
+type CssRules = 'root' | 'tableRow' | 'helpIconGrid' | 'tableGrid';
+
+const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
+    root: {
+        width: '100%',
+        overflow: 'auto'
+    },
+    helpIconGrid: {
+        textAlign: 'right'
+    },
+    tableGrid: {
+        marginTop: theme.spacing.unit
+    },
+    tableRow: {
+        '& td, th': {
+            whiteSpace: 'nowrap'
+        }
+    }
+});
+
+export interface ApiClientAuthorizationPanelRootActionProps {
+    openRowOptions: (event: React.MouseEvent<HTMLElement>, keepService: ApiClientAuthorization) => void;
+    openHelpDialog: () => void;
+}
+
+export interface ApiClientAuthorizationPanelRootDataProps {
+    apiClientAuthorizations: ApiClientAuthorization[];
+    hasApiClientAuthorizations: boolean;
+}
+
+type ApiClientAuthorizationPanelRootProps = ApiClientAuthorizationPanelRootActionProps 
+    & ApiClientAuthorizationPanelRootDataProps & WithStyles<CssRules>;
+
+export const ApiClientAuthorizationPanelRoot = withStyles(styles)(
+    ({ classes, hasApiClientAuthorizations, apiClientAuthorizations, openRowOptions, openHelpDialog }: ApiClientAuthorizationPanelRootProps) =>
+        <Card className={classes.root}>
+            <CardContent>
+                {hasApiClientAuthorizations && <Grid container direction="row" justify="flex-end">
+                    <Grid item xs={12} className={classes.helpIconGrid}>
+                        <Tooltip title="Api token - help">
+                            <IconButton onClick={openHelpDialog}>
+                                <HelpIcon />
+                            </IconButton>
+                        </Tooltip>
+                    </Grid>
+                    <Grid item xs={12}>
+                        <Table>
+                            <TableHead>
+                                <TableRow className={classes.tableRow}>
+                                    <TableCell>UUID</TableCell>
+                                    <TableCell>API Client ID</TableCell>
+                                    <TableCell>API Token</TableCell>
+                                    <TableCell>Created by IP address</TableCell>
+                                    <TableCell>Default owner</TableCell>
+                                    <TableCell>Expires at</TableCell>
+                                    <TableCell>Last used at</TableCell>
+                                    <TableCell>Last used by IP address</TableCell>
+                                    <TableCell>Scopes</TableCell>
+                                    <TableCell>User ID</TableCell>
+                                    <TableCell />
+                                </TableRow>
+                            </TableHead>
+                            <TableBody>
+                                {apiClientAuthorizations.map((apiClientAuthorizatio, index) =>
+                                    <TableRow key={index} className={classes.tableRow}>
+                                        <TableCell>{apiClientAuthorizatio.uuid}</TableCell>
+                                        <TableCell>{apiClientAuthorizatio.apiClientId}</TableCell>
+                                        <TableCell>{apiClientAuthorizatio.apiToken}</TableCell>
+                                        <TableCell>{apiClientAuthorizatio.createdByIpAddress || '(none)'}</TableCell>
+                                        <TableCell>{apiClientAuthorizatio.defaultOwnerUuid || '(none)'}</TableCell>
+                                        <TableCell>{formatDate(apiClientAuthorizatio.expiresAt) || '(none)'}</TableCell>
+                                        <TableCell>{formatDate(apiClientAuthorizatio.lastUsedAt) || '(none)'}</TableCell>
+                                        <TableCell>{apiClientAuthorizatio.lastUsedByIpAddress || '(none)'}</TableCell>
+                                        <TableCell>{JSON.stringify(apiClientAuthorizatio.scopes)}</TableCell>
+                                        <TableCell>{apiClientAuthorizatio.userId}</TableCell>
+                                        <TableCell>
+                                            <Tooltip title="More options" disableFocusListener>
+                                                <IconButton onClick={event => openRowOptions(event, apiClientAuthorizatio)}>
+                                                    <MoreOptionsIcon />
+                                                </IconButton>
+                                            </Tooltip>
+                                        </TableCell>
+                                    </TableRow>)}
+                            </TableBody>
+                        </Table>
+                    </Grid>
+                </Grid>}
+            </CardContent>
+        </Card>
+);
\ No newline at end of file
diff --git a/src/views/api-client-authorization-panel/api-client-authorization-panel.tsx b/src/views/api-client-authorization-panel/api-client-authorization-panel.tsx
new file mode 100644 (file)
index 0000000..75b79ab
--- /dev/null
@@ -0,0 +1,32 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { RootState } from '~/store/store';
+import { Dispatch } from 'redux';
+import { connect } from 'react-redux';
+import {
+    ApiClientAuthorizationPanelRoot,
+    ApiClientAuthorizationPanelRootDataProps,
+    ApiClientAuthorizationPanelRootActionProps
+} from '~/views/api-client-authorization-panel/api-client-authorization-panel-root';
+import { openApiClientAuthorizationContextMenu } from '~/store/context-menu/context-menu-actions';
+import { openApiClientAuthorizationsHelpDialog } from '~/store/api-client-authorizations/api-client-authorizations-actions';
+
+const mapStateToProps = (state: RootState): ApiClientAuthorizationPanelRootDataProps => {
+    return {
+        apiClientAuthorizations: state.apiClientAuthorizations,
+        hasApiClientAuthorizations: state.apiClientAuthorizations.length > 0
+    };
+};
+
+const mapDispatchToProps = (dispatch: Dispatch): ApiClientAuthorizationPanelRootActionProps => ({
+    openRowOptions: (event, apiClientAuthorization) => {
+        dispatch<any>(openApiClientAuthorizationContextMenu(event, apiClientAuthorization));
+    },
+    openHelpDialog: () => {
+        dispatch<any>(openApiClientAuthorizationsHelpDialog());
+    }
+});
+
+export const ApiClientAuthorizationPanel = connect(mapStateToProps, mapDispatchToProps)(ApiClientAuthorizationPanelRoot);
\ No newline at end of file
index be3627b8782748354f00baea1708c6d81b78450c..2d325b514a8bb20897d3f4ca5959b4b5496af14e 100644 (file)
@@ -20,7 +20,7 @@ const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
         overflow: 'auto'
     },
     tableRow: {
-        '& td, th': {
+        '& th': {
             whiteSpace: 'nowrap'
         }
     }
@@ -60,7 +60,7 @@ export const ComputeNodePanelRoot = withStyles(styles)(
                             <TableBody>
                                 {computeNodes.map((computeNode, index) =>
                                     <TableRow key={index} className={classes.tableRow}>
-                                        <TableCell>{computeNode.uuid}</TableCell>
+                                        <TableCell>{JSON.stringify(computeNode.info, null, 4)}</TableCell>
                                         <TableCell>{computeNode.uuid}</TableCell>
                                         <TableCell>{computeNode.domain}</TableCell>
                                         <TableCell>{formatDate(computeNode.firstPingAt) || '(none)'}</TableCell>
diff --git a/src/views/my-account-panel/my-account-panel-root.tsx b/src/views/my-account-panel/my-account-panel-root.tsx
new file mode 100644 (file)
index 0000000..e6a2763
--- /dev/null
@@ -0,0 +1,161 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import * as React from 'react';
+import { Field, InjectedFormProps } from "redux-form";
+import { TextField } from "~/components/text-field/text-field";
+import { NativeSelectField } from "~/components/select-field/select-field";
+import {
+    StyleRulesCallback,
+    WithStyles,
+    withStyles,
+    Card,
+    CardContent,
+    Button,
+    Typography,
+    Grid,
+    InputLabel
+} from '@material-ui/core';
+import { ArvadosTheme } from '~/common/custom-theme';
+import { User } from "~/models/user";
+import { MY_ACCOUNT_VALIDATION} from "~/validators/validators";
+
+type CssRules = 'root' | 'gridItem' | 'label' | 'title' | 'actions';
+
+const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
+    root: {
+        width: '100%',
+        overflow: 'auto'
+    },
+    gridItem: {
+        height: 45,
+        marginBottom: 20
+    },
+    label: {
+        fontSize: '0.675rem'
+    },
+    title: {
+        marginBottom: theme.spacing.unit * 3,
+        color: theme.palette.grey["600"]
+    },
+    actions: {
+        display: 'flex',
+        justifyContent: 'flex-end'
+    }
+});
+
+export interface MyAccountPanelRootActionProps {}
+
+export interface MyAccountPanelRootDataProps {
+    isPristine: boolean;
+    isValid: boolean;
+    initialValues?: User;
+}
+
+const RoleTypes = [
+    {key: 'Bio-informatician', value: 'Bio-informatician'},
+    {key: 'Data Scientist', value: 'Data Scientist'},
+    {key: 'Analyst', value: 'Analyst'},
+    {key: 'Researcher', value: 'Researcher'},
+    {key: 'Software Developer', value: 'Software Developer'},
+    {key: 'System Administrator', value: 'System Administrator'},
+    {key: 'Other', value: 'Other'}
+];
+
+type MyAccountPanelRootProps = InjectedFormProps<MyAccountPanelRootActionProps> & MyAccountPanelRootDataProps & WithStyles<CssRules>;
+
+export const MyAccountPanelRoot = withStyles(styles)(
+    ({ classes, isValid, handleSubmit, reset, isPristine, invalid, submitting }: MyAccountPanelRootProps) => {
+        return <Card className={classes.root}>
+            <CardContent>
+                <Typography variant="title" className={classes.title}>User profile</Typography>
+                <form onSubmit={handleSubmit}>
+                    <Grid container direction="row" spacing={24}>
+                        <Grid item xs={6}>
+                            <Grid item className={classes.gridItem}>
+                                <Field
+                                    label="E-mail"
+                                    name="email"
+                                    component={TextField}
+                                    disabled
+                                />
+                            </Grid>
+                            <Grid item className={classes.gridItem}>
+                                <Field
+                                    label="First name"
+                                    name="firstName"
+                                    component={TextField}
+                                    disabled
+                                />
+                            </Grid>
+                            <Grid item className={classes.gridItem}>
+                                <Field
+                                    label="Identity URL"
+                                    name="identityUrl"
+                                    component={TextField}
+                                    disabled
+                                />
+                            </Grid>
+                            <Grid item className={classes.gridItem}>
+                                <Field
+                                    label="Organization"
+                                    name="prefs.profile.organization"
+                                    component={TextField}
+                                    validate={MY_ACCOUNT_VALIDATION}
+                                    required
+                                />
+                            </Grid>
+                            <Grid item className={classes.gridItem}>
+                                <Field
+                                    label="Website"
+                                    name="prefs.profile.website_url"
+                                    component={TextField}
+                                />
+                            </Grid>
+                            <Grid item className={classes.gridItem}>
+                                <InputLabel className={classes.label} htmlFor="prefs.profile.role">Organization</InputLabel>
+                                <Field
+                                    id="prefs.profile.role"
+                                    name="prefs.profile.role"
+                                    component={NativeSelectField}
+                                    items={RoleTypes}
+                                />
+                            </Grid>
+                        </Grid>
+                        <Grid item xs={6}>
+                            <Grid item className={classes.gridItem} />
+                            <Grid item className={classes.gridItem}>
+                                <Field
+                                    label="Last name"
+                                    name="lastName"
+                                    component={TextField}
+                                    disabled
+                                />
+                            </Grid>
+                            <Grid item className={classes.gridItem} />
+                            <Grid item className={classes.gridItem}>
+                                <Field
+                                    label="E-mail at Organization"
+                                    name="prefs.profile.organization_email"
+                                    component={TextField}
+                                    validate={MY_ACCOUNT_VALIDATION}
+                                    required
+                                />
+                            </Grid>
+                        </Grid>
+                        <Grid item xs={12} className={classes.actions}>
+                            <Button color="primary" onClick={reset} disabled={isPristine}>Discard changes</Button>
+                            <Button
+                                color="primary"
+                                variant="contained"
+                                type="submit"
+                                disabled={isPristine || invalid || submitting}>
+                                    Save changes
+                            </Button>
+                        </Grid>
+                    </Grid>
+                </form>
+            </CardContent>
+        </Card>;}
+);
\ No newline at end of file
diff --git a/src/views/my-account-panel/my-account-panel.tsx b/src/views/my-account-panel/my-account-panel.tsx
new file mode 100644 (file)
index 0000000..5c2c531
--- /dev/null
@@ -0,0 +1,26 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { RootState } from '~/store/store';
+import { compose } from 'redux';
+import { reduxForm, isPristine, isValid } from 'redux-form';
+import { connect } from 'react-redux';
+import { saveEditedUser } from '~/store/my-account/my-account-panel-actions';
+import { MyAccountPanelRoot, MyAccountPanelRootDataProps } from '~/views/my-account-panel/my-account-panel-root';
+import { MY_ACCOUNT_FORM } from "~/store/my-account/my-account-panel-actions";
+
+const mapStateToProps = (state: RootState): MyAccountPanelRootDataProps => ({
+    isPristine: isPristine(MY_ACCOUNT_FORM)(state),
+    isValid: isValid(MY_ACCOUNT_FORM)(state),
+    initialValues: state.auth.user
+});
+
+export const MyAccountPanel = compose(
+    connect(mapStateToProps),
+    reduxForm({
+    form: MY_ACCOUNT_FORM,
+    onSubmit: (data, dispatch) => {
+        dispatch(saveEditedUser(data));
+    }
+}))(MyAccountPanelRoot);
\ No newline at end of file
index 5dbd3f0965aa6336d2893fd7faf48ecba75e43e7..d5d345551c41a680a26c6b62247f2109980567ce 100644 (file)
@@ -12,7 +12,7 @@ import { Link } from 'react-router-dom';
 import { compose, Dispatch } from 'redux';
 import { saveRequestedDate, loadVirtualMachinesData } from '~/store/virtual-machines/virtual-machines-actions';
 import { RootState } from '~/store/store';
-import { ListResults } from '~/services/common-service/common-resource-service';
+import { ListResults } from '~/services/common-service/common-service';
 import { HelpIcon, MoreOptionsIcon } from '~/components/icon/icon';
 import { VirtualMachineLogins, VirtualMachinesResource } from '~/models/virtual-machines';
 import { Routes } from '~/routes/routes';
index 92c2438b49f92c3d16bcf741713d76e6972d8643..3cd040f78c6aeec4819c92dd5db500a1495ab9e0 100644 (file)
@@ -45,6 +45,7 @@ import SplitterLayout from 'react-splitter-layout';
 import { WorkflowPanel } from '~/views/workflow-panel/workflow-panel';
 import { SearchResultsPanel } from '~/views/search-results-panel/search-results-panel';
 import { SshKeyPanel } from '~/views/ssh-key-panel/ssh-key-panel';
+import { MyAccountPanel } from '~/views/my-account-panel/my-account-panel';
 import { SharingDialog } from '~/views-components/sharing-dialog/sharing-dialog';
 import { AdvancedTabDialog } from '~/views-components/advanced-tab-dialog/advanced-tab-dialog';
 import { ProcessInputDialog } from '~/views-components/process-input-dialog/process-input-dialog';
@@ -53,20 +54,24 @@ import { ProjectPropertiesDialog } from '~/views-components/project-properties-d
 import { RepositoriesPanel } from '~/views/repositories-panel/repositories-panel';
 import { KeepServicePanel } from '~/views/keep-service-panel/keep-service-panel';
 import { ComputeNodePanel } from '~/views/compute-node-panel/compute-node-panel';
+import { ApiClientAuthorizationPanel } from '~/views/api-client-authorization-panel/api-client-authorization-panel';
 import { RepositoriesSampleGitDialog } from '~/views-components/repositories-sample-git-dialog/repositories-sample-git-dialog';
 import { RepositoryAttributesDialog } from '~/views-components/repository-attributes-dialog/repository-attributes-dialog';
 import { CreateRepositoryDialog } from '~/views-components/dialog-forms/create-repository-dialog';
 import { RemoveRepositoryDialog } from '~/views-components/repository-remove-dialog/repository-remove-dialog';
 import { CreateSshKeyDialog } from '~/views-components/dialog-forms/create-ssh-key-dialog';
 import { PublicKeyDialog } from '~/views-components/ssh-keys-dialog/public-key-dialog';
+import { RemoveApiClientAuthorizationDialog } from '~/views-components/api-client-authorizations-dialog/remove-dialog';
 import { RemoveComputeNodeDialog } from '~/views-components/compute-nodes-dialog/remove-dialog';
 import { RemoveKeepServiceDialog } from '~/views-components/keep-services-dialog/remove-dialog';
 import { RemoveSshKeyDialog } from '~/views-components/ssh-keys-dialog/remove-dialog';
 import { RemoveVirtualMachineDialog } from '~/views-components/virtual-machines-dialog/remove-dialog';
+import { AttributesApiClientAuthorizationDialog } from '~/views-components/api-client-authorizations-dialog/attributes-dialog';
 import { AttributesComputeNodeDialog } from '~/views-components/compute-nodes-dialog/attributes-dialog';
 import { AttributesKeepServiceDialog } from '~/views-components/keep-services-dialog/attributes-dialog';
 import { AttributesSshKeyDialog } from '~/views-components/ssh-keys-dialog/attributes-dialog';
 import { VirtualMachineAttributesDialog } from '~/views-components/virtual-machines-dialog/attributes-dialog';
+import { HelpApiClientAuthorizationDialog } from '~/views-components/api-client-authorizations-dialog/help-dialog';
 
 type CssRules = 'root' | 'container' | 'splitter' | 'asidePanel' | 'contentWrapper' | 'content';
 
@@ -141,6 +146,8 @@ export const WorkbenchPanel =
                                 <Route path={Routes.SSH_KEYS} component={SshKeyPanel} />
                                 <Route path={Routes.KEEP_SERVICES} component={KeepServicePanel} />
                                 <Route path={Routes.COMPUTE_NODES} component={ComputeNodePanel} />
+                                <Route path={Routes.API_CLIENT_AUTHORIZATIONS} component={ApiClientAuthorizationPanel} />
+                                <Route path={Routes.MY_ACCOUNT} component={MyAccountPanel} />
                             </Switch>
                         </Grid>
                     </Grid>
@@ -150,6 +157,7 @@ export const WorkbenchPanel =
                 <DetailsPanel />
             </Grid>
             <AdvancedTabDialog />
+            <AttributesApiClientAuthorizationDialog />
             <AttributesComputeNodeDialog />
             <AttributesKeepServiceDialog />
             <AttributesSshKeyDialog />
@@ -164,6 +172,7 @@ export const WorkbenchPanel =
             <CurrentTokenDialog />
             <FileRemoveDialog />
             <FilesUploadCollectionDialog />
+            <HelpApiClientAuthorizationDialog />
             <MoveCollectionDialog />
             <MoveProcessDialog />
             <MoveProjectDialog />
@@ -173,6 +182,7 @@ export const WorkbenchPanel =
             <ProcessCommandDialog />
             <ProcessInputDialog />
             <ProjectPropertiesDialog />
+            <RemoveApiClientAuthorizationDialog />
             <RemoveComputeNodeDialog />
             <RemoveKeepServiceDialog />
             <RemoveProcessDialog />