From: Pawel Kromplewski Date: Tue, 18 Dec 2018 13:25:31 +0000 (+0100) Subject: Merge branch '14434-display-workflow-name' X-Git-Tag: 1.4.0~71^2~14 X-Git-Url: https://git.arvados.org/arvados-workbench2.git/commitdiff_plain/61cd8fe9d4fe4dfeab443f31bbbc5effa5176765?hp=2c8a2efbe5bac7df0a13a17ed773102d95fd1111 Merge branch '14434-display-workflow-name' refs #14434 Arvados-DCO-1.1-Signed-off-by: Pawel Kromplewski --- diff --git a/README.md b/README.md index e8d77701..425d1787 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,8 @@ Currently this configuration schema is supported: ``` { "API_HOST": "string", - "VOCABULARY_URL": "string" + "VOCABULARY_URL": "string", + "FILE_VIEWERS_CONFIG_URL": "string", } ``` @@ -49,6 +50,13 @@ Currently this configuration schema is supported: Local path, or any URL that allows cross-origin requests. See [Vocabulary JSON file example](public/vocabulary-example.json). +### FILE_VIEWERS_CONFIG_URL +Local path, or any URL that allows cross-origin requests. See: + +[File viewers config file example](public/file-viewers-example.json) + +[File viewers config scheme](src/models/file-viewers-config.ts) + ### Licensing Arvados is Free Software. See COPYING for information about Arvados Free diff --git a/package.json b/package.json index 13326304..46b3ee4f 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "@material-ui/icons": "3.0.1", "@types/debounce": "3.0.0", "@types/js-yaml": "3.11.2", + "@types/jssha": "0.0.29", "@types/lodash": "4.14.116", "@types/react-copy-to-clipboard": "4.2.6", "@types/react-dnd": "3.0.2", @@ -21,6 +22,7 @@ "debounce": "1.2.0", "is-image": "2.0.0", "js-yaml": "3.12.0", + "jssha": "2.3.1", "lodash": "4.17.11", "react": "16.5.2", "react-copy-to-clipboard": "5.0.1", diff --git a/public/file-viewers-example.json b/public/file-viewers-example.json new file mode 100644 index 00000000..27adb70b --- /dev/null +++ b/public/file-viewers-example.json @@ -0,0 +1,25 @@ +[ + { + "name": "File browser", + "extensions": [ + ".txt", + ".zip" + ], + "url": "https://doc.arvados.org", + "filePathParam": "filePath", + "iconUrl": "https://material.io/tools/icons/static/icons/baseline-next_week-24px.svg" + }, + { + "name": "Collection browser", + "extensions": [], + "collections": true, + "url": "https://doc.arvados.org", + "filePathParam": "collectionPath" + }, + { + "name": "Universal browser", + "collections": true, + "url": "https://doc.arvados.org", + "filePathParam": "filePath" + } +] \ No newline at end of file diff --git a/src/common/config.ts b/src/common/config.ts index b7b89bd9..3961d5aa 100644 --- a/src/common/config.ts +++ b/src/common/config.ts @@ -35,7 +35,9 @@ export interface Config { packageVersion: string; parameters: {}; protocol: string; - remoteHosts: string; + remoteHosts: { + [key: string]: string + }; remoteHostsViaDNS: boolean; resources: {}; revision: string; @@ -50,6 +52,7 @@ export interface Config { websocketUrl: string; workbenchUrl: string; vocabularyUrl: string; + fileViewersConfigUrl: string; } export const fetchConfig = () => { @@ -59,10 +62,15 @@ export const fetchConfig = () => { .catch(() => Promise.resolve(getDefaultConfig())) .then(config => Axios .get(getDiscoveryURL(config.API_HOST)) - .then(response => ({ + .then(response => ({ // TODO: After tests delete `|| '/vocabulary-example.json'` - config: {...response.data, vocabularyUrl: config.VOCABULARY_URL || '/vocabulary-example.json' }, - apiHost: config.API_HOST, + // TODO: After tests delete `|| '/file-viewers-example.json'` + config: { + ...response.data, + vocabularyUrl: config.VOCABULARY_URL || '/vocabulary-example.json', + fileViewersConfigUrl: config.FILE_VIEWERS_CONFIG_URL || '/file-viewers-example.json' + }, + apiHost: config.API_HOST, }))); }; @@ -96,7 +104,7 @@ export const mockConfig = (config: Partial): Config => ({ packageVersion: '', parameters: {}, protocol: '', - remoteHosts: '', + remoteHosts: {}, remoteHostsViaDNS: false, resources: {}, revision: '', @@ -111,17 +119,21 @@ export const mockConfig = (config: Partial): Config => ({ websocketUrl: '', workbenchUrl: '', vocabularyUrl: '', + fileViewersConfigUrl: '', ...config }); interface ConfigJSON { API_HOST: string; VOCABULARY_URL: string; + FILE_VIEWERS_CONFIG_URL: string; } const getDefaultConfig = (): ConfigJSON => ({ API_HOST: process.env.REACT_APP_ARVADOS_API_HOST || "", VOCABULARY_URL: "", + FILE_VIEWERS_CONFIG_URL: "", }); -const getDiscoveryURL = (apiHost: string) => `${window.location.protocol}//${apiHost}/discovery/v1/apis/arvados/v1/rest`; +export const DISCOVERY_URL = 'discovery/v1/apis/arvados/v1/rest'; +const getDiscoveryURL = (apiHost: string) => `${window.location.protocol}//${apiHost}/${DISCOVERY_URL}`; diff --git a/src/components/autocomplete/autocomplete.tsx b/src/components/autocomplete/autocomplete.tsx index c5811bb6..4b19b771 100644 --- a/src/components/autocomplete/autocomplete.tsx +++ b/src/components/autocomplete/autocomplete.tsx @@ -15,6 +15,7 @@ export interface AutocompleteProps { suggestions?: Suggestion[]; error?: boolean; helperText?: string; + autofocus?: boolean; onChange: (event: React.ChangeEvent) => void; onBlur?: (event: React.FocusEvent) => void; onFocus?: (event: React.FocusEvent) => void; @@ -29,6 +30,7 @@ export interface AutocompleteState { suggestionsOpen: boolean; selectedSuggestionIndex: number; } + export class Autocomplete extends React.Component, AutocompleteState> { state = { @@ -59,6 +61,7 @@ export class Autocomplete extends React.Component extends React.Component 0) { onCreate(); @@ -149,6 +152,16 @@ export class Autocomplete extends React.Component { {item.name} } )} - {groupIndex < items.length - 1 && } + { + items[groupIndex + 1] && + items[groupIndex + 1].length > 0 && + + } )} ; diff --git a/src/components/data-explorer/data-explorer.tsx b/src/components/data-explorer/data-explorer.tsx index 4175fbc6..b6ca215d 100644 --- a/src/components/data-explorer/data-explorer.tsx +++ b/src/components/data-explorer/data-explorer.tsx @@ -49,6 +49,7 @@ interface DataExplorerDataProps { paperProps?: PaperProps; actions?: React.ReactNode; hideSearchInput?: boolean; + paperKey?: string; } interface DataExplorerActionProps { @@ -79,9 +80,10 @@ export const DataExplorer = withStyles(styles)( columns, onContextMenu, onFiltersChange, onSortToggle, working, extractKey, rowsPerPage, rowsPerPageOptions, onColumnToggle, searchValue, onSearch, items, itemsAvailable, onRowClick, onRowDoubleClick, classes, - dataTableDefaultView, hideColumnSelector, actions, paperProps, hideSearchInput + dataTableDefaultView, hideColumnSelector, actions, paperProps, hideSearchInput, + paperKey } = this.props; - return + return {!hideSearchInput &&
@@ -105,8 +107,7 @@ export const DataExplorer = withStyles(styles)( onSortToggle={onSortToggle} extractKey={extractKey} working={working} - defaultView={dataTableDefaultView} - /> + defaultView={dataTableDefaultView} /> ; export const MoveToIcon: IconType = (props) => ; export const NewProjectIcon: IconType = (props) => ; export const NotificationIcon: IconType = (props) => ; +export const OpenIcon: IconType = (props) => ; export const OutputIcon: IconType = (props) => ; export const PaginationDownIcon: IconType = (props) => ; export const PaginationLeftArrowIcon: IconType = (props) => ; diff --git a/src/components/text-field/text-field.tsx b/src/components/text-field/text-field.tsx index 627e004d..93c4080f 100644 --- a/src/components/text-field/text-field.tsx +++ b/src/components/text-field/text-field.tsx @@ -5,8 +5,15 @@ import * as React from 'react'; import { WrappedFieldProps } from 'redux-form'; import { ArvadosTheme } from '~/common/custom-theme'; -import { TextField as MaterialTextField, StyleRulesCallback, WithStyles, withStyles } from '@material-ui/core'; +import { + TextField as MaterialTextField, + StyleRulesCallback, + WithStyles, + withStyles, + PropTypes +} from '@material-ui/core'; import RichTextEditor from 'react-rte'; +import Margin = PropTypes.Margin; type CssRules = 'textField'; @@ -18,8 +25,8 @@ const styles: StyleRulesCallback = (theme: ArvadosTheme) => ({ type TextFieldProps = WrappedFieldProps & WithStyles; -export const TextField = withStyles(styles)((props: TextFieldProps & { - label?: string, autoFocus?: boolean, required?: boolean, select?: boolean, disabled?: boolean, children: React.ReactNode +export const TextField = withStyles(styles)((props: TextFieldProps & { + label?: string, autoFocus?: boolean, required?: boolean, select?: boolean, disabled?: boolean, children: React.ReactNode, margin?: Margin, placeholder?: string }) => ); @@ -78,4 +87,4 @@ export const DateTextField = withStyles(styles) onChange={props.input.onChange} value={props.input.value} /> - ); \ No newline at end of file + ); diff --git a/src/index.tsx b/src/index.tsx index e73f08c4..1561c3ff 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -56,7 +56,10 @@ import { virtualMachineActionSet } from '~/views-components/context-menu/action- import { userActionSet } from '~/views-components/context-menu/action-sets/user-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'; +import { groupActionSet } from '~/views-components/context-menu/action-sets/group-action-set'; +import { groupMemberActionSet } from '~/views-components/context-menu/action-sets/group-member-action-set'; import { linkActionSet } from '~/views-components/context-menu/action-sets/link-action-set'; +import { loadFileViewersConfig } from '~/store/file-viewers/file-viewers-actions'; console.log(`Starting arvados [${getBuildInfo()}]`); @@ -81,6 +84,8 @@ addMenuActionSet(ContextMenuKind.USER, userActionSet); addMenuActionSet(ContextMenuKind.LINK, linkActionSet); addMenuActionSet(ContextMenuKind.NODE, computeNodeActionSet); addMenuActionSet(ContextMenuKind.API_CLIENT_AUTHORIZATION, apiClientAuthorizationActionSet); +addMenuActionSet(ContextMenuKind.GROUPS, groupActionSet); +addMenuActionSet(ContextMenuKind.GROUP_MEMBER, groupMemberActionSet); fetchConfig() .then(({ config, apiHost }) => { @@ -97,13 +102,14 @@ fetchConfig() const store = configureStore(history, services); store.subscribe(initListener(history, store, services, config)); - store.dispatch(initAuth()); + store.dispatch(initAuth(config)); store.dispatch(setBuildInfo()); store.dispatch(setCurrentTokenDialogApiHost(apiHost)); store.dispatch(setUuidPrefix(config.uuidPrefix)); store.dispatch(loadVocabulary); + store.dispatch(loadFileViewersConfig); - const TokenComponent = (props: any) => ; + const TokenComponent = (props: any) => ; const MainPanelComponent = (props: any) => ; const App = () => diff --git a/src/models/client-authorization.ts b/src/models/client-authorization.ts new file mode 100644 index 00000000..767916ec --- /dev/null +++ b/src/models/client-authorization.ts @@ -0,0 +1,12 @@ +export interface ClientAuthorizationResource { + uuid: string; + apiToken: string; + apiClientId: number; + userId: number; + createdByIpAddress: string; + lastUsedByIpAddress: string; + lastUsedAt: string; + expiresAt: string; + ownerUuid: string; + scopes: string[]; +} diff --git a/src/models/file-viewers-config.ts b/src/models/file-viewers-config.ts new file mode 100644 index 00000000..e95116ba --- /dev/null +++ b/src/models/file-viewers-config.ts @@ -0,0 +1,47 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +export type FileViewerList = FileViewer[]; + +export interface FileViewer { + /** + * Name is used as a label in file's context menu + */ + name: string; + + /** + * Limits files for which viewer is enabled + * If not given, viewer will be enabled for all files + * Viewer is enabled if file name ends with an extension. + * + * Example: `['.zip', '.tar.gz', 'bam']` + */ + extensions?: string[]; + + /** + * Determines whether a viewer is enabled for collections. + */ + collections?: boolean; + + /** + * URL that redirects to a viewer + * Example: `https://bam-viewer.com` + */ + url: string; + + /** + * Name of a search param that will be used to send file's path to a viewer + * Example: + * + * `{ filePathParam: 'filePath' }` + * + * `https://bam-viewer.com?filePath=/path/to/file` + */ + filePathParam: string; + + /** + * Icon that will display next to a label + */ + iconUrl?: string; +} diff --git a/src/models/link.ts b/src/models/link.ts index d931f7f2..785d531c 100644 --- a/src/models/link.ts +++ b/src/models/link.ts @@ -2,9 +2,8 @@ // // SPDX-License-Identifier: AGPL-3.0 -import { Resource } from "./resource"; import { TagProperty } from "~/models/tag"; -import { ResourceKind } from '~/models/resource'; +import { Resource, ResourceKind } from '~/models/resource'; export interface LinkResource extends Resource { headUuid: string; @@ -14,6 +13,7 @@ export interface LinkResource extends Resource { linkClass: string; name: string; properties: TagProperty; + kind: ResourceKind.LINK; } export enum LinkClass { diff --git a/src/models/session.ts b/src/models/session.ts new file mode 100644 index 00000000..9a942967 --- /dev/null +++ b/src/models/session.ts @@ -0,0 +1,21 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +export enum SessionStatus { + INVALIDATED, + BEING_VALIDATED, + VALIDATED +} + +export interface Session { + clusterId: string; + remoteHost: string; + baseUrl: string; + username: string; + email: string; + token: string; + loggedIn: boolean; + status: SessionStatus; + active: boolean; +} diff --git a/src/routes/route-change-handlers.ts b/src/routes/route-change-handlers.ts index 655c806f..bb88f4a1 100644 --- a/src/routes/route-change-handlers.ts +++ b/src/routes/route-change-handlers.ts @@ -8,6 +8,8 @@ import * as Routes from '~/routes/routes'; import * as WorkbenchActions from '~/store/workbench/workbench-actions'; import { navigateToRootProject } from '~/store/navigation/navigation-action'; import { dialogActions } from '~/store/dialog/dialog-actions'; +import { contextMenuActions } from '~/store/context-menu/context-menu-actions'; +import { searchBarActions } from '~/store/search-bar/search-bar-actions'; export const addRouteChangeHandlers = (history: History, store: RootStore) => { const handler = handleLocationChange(store); @@ -32,14 +34,19 @@ const handleLocationChange = (store: RootStore) => ({ pathname }: Location) => { const workflowMatch = Routes.matchWorkflowRoute(pathname); const sshKeysUserMatch = Routes.matchSshKeysUserRoute(pathname); const sshKeysAdminMatch = Routes.matchSshKeysAdminRoute(pathname); + const siteManagerMatch = Routes.matchSiteManagerRoute(pathname); const keepServicesMatch = Routes.matchKeepServicesRoute(pathname); const computeNodesMatch = Routes.matchComputeNodesRoute(pathname); const apiClientAuthorizationsMatch = Routes.matchApiClientAuthorizationsRoute(pathname); const myAccountMatch = Routes.matchMyAccountRoute(pathname); const userMatch = Routes.matchUsersRoute(pathname); + const groupsMatch = Routes.matchGroupsRoute(pathname); + const groupDetailsMatch = Routes.matchGroupDetailsRoute(pathname); const linksMatch = Routes.matchLinksRoute(pathname); store.dispatch(dialogActions.CLOSE_ALL_DIALOGS()); + store.dispatch(contextMenuActions.CLOSE_CONTEXT_MENU()); + store.dispatch(searchBarActions.CLOSE_SEARCH_VIEW()); if (projectMatch) { store.dispatch(WorkbenchActions.loadProject(projectMatch.params.id)); @@ -73,6 +80,8 @@ const handleLocationChange = (store: RootStore) => ({ pathname }: Location) => { store.dispatch(WorkbenchActions.loadSshKeys); } else if (sshKeysAdminMatch) { store.dispatch(WorkbenchActions.loadSshKeys); + } else if (siteManagerMatch) { + store.dispatch(WorkbenchActions.loadSiteManager); } else if (keepServicesMatch) { store.dispatch(WorkbenchActions.loadKeepServices); } else if (computeNodesMatch) { @@ -83,6 +92,10 @@ const handleLocationChange = (store: RootStore) => ({ pathname }: Location) => { store.dispatch(WorkbenchActions.loadMyAccount); } else if (userMatch) { store.dispatch(WorkbenchActions.loadUsers); + } else if (groupsMatch) { + store.dispatch(WorkbenchActions.loadGroupsPanel); + } else if (groupDetailsMatch) { + store.dispatch(WorkbenchActions.loadGroupDetailsPanel(groupDetailsMatch.params.id)); } else if (linksMatch) { store.dispatch(WorkbenchActions.loadLinks); } diff --git a/src/routes/routes.ts b/src/routes/routes.ts index 05f6663f..b1da9496 100644 --- a/src/routes/routes.ts +++ b/src/routes/routes.ts @@ -25,11 +25,14 @@ export const Routes = { SEARCH_RESULTS: '/search-results', SSH_KEYS_ADMIN: `/ssh-keys-admin`, SSH_KEYS_USER: `/ssh-keys-user`, + SITE_MANAGER: `/site-manager`, MY_ACCOUNT: '/my-account', KEEP_SERVICES: `/keep-services`, COMPUTE_NODES: `/nodes`, USERS: '/users', API_CLIENT_AUTHORIZATIONS: `/api_client_authorizations`, + GROUPS: '/groups', + GROUP_DETAILS: `/group/:id(${RESOURCE_UUID_PATTERN})`, LINKS: '/links' }; @@ -51,6 +54,8 @@ export const getProcessUrl = (uuid: string) => `/processes/${uuid}`; export const getProcessLogUrl = (uuid: string) => `/process-logs/${uuid}`; +export const getGroupUrl = (uuid: string) => `/group/${uuid}`; + export interface ResourceRouteParams { id: string; } @@ -103,6 +108,9 @@ export const matchSshKeysUserRoute = (route: string) => export const matchSshKeysAdminRoute = (route: string) => matchPath(route, { path: Routes.SSH_KEYS_ADMIN }); +export const matchSiteManagerRoute = (route: string) => + matchPath(route, { path: Routes.SITE_MANAGER }); + export const matchMyAccountRoute = (route: string) => matchPath(route, { path: Routes.MY_ACCOUNT }); @@ -118,5 +126,11 @@ export const matchComputeNodesRoute = (route: string) => export const matchApiClientAuthorizationsRoute = (route: string) => matchPath(route, { path: Routes.API_CLIENT_AUTHORIZATIONS }); +export const matchGroupsRoute = (route: string) => + matchPath(route, { path: Routes.GROUPS }); + +export const matchGroupDetailsRoute = (route: string) => + matchPath(route, { path: Routes.GROUP_DETAILS }); + export const matchLinksRoute = (route: string) => - matchPath(route, { path: Routes.LINKS }); \ No newline at end of file + matchPath(route, { path: Routes.LINKS }); diff --git a/src/services/api/filter-builder.ts b/src/services/api/filter-builder.ts index 08746c81..4b3db9fa 100644 --- a/src/services/api/filter-builder.ts +++ b/src/services/api/filter-builder.ts @@ -11,8 +11,8 @@ export function joinFilters(filters0?: string, filters1?: string) { export class FilterBuilder { constructor(private filters = "") { } - public addEqual(field: string, value?: string | boolean, resourcePrefix?: string) { - return this.addCondition(field, "=", value, "", "", resourcePrefix ); + public addEqual(field: string, value?: string | boolean | null, resourcePrefix?: string) { + return this.addCondition(field, "=", value, "", "", resourcePrefix); } public addLike(field: string, value?: string, resourcePrefix?: string) { @@ -59,13 +59,13 @@ export class FilterBuilder { return this.filters; } - private addCondition(field: string, cond: string, value?: string | string[] | boolean, prefix: string = "", postfix: string = "", resourcePrefix?: string) { - if (value) { + private addCondition(field: string, cond: string, value?: string | string[] | boolean | null, prefix: string = "", postfix: string = "", resourcePrefix?: string) { + if (value !== undefined) { if (typeof value === "string") { value = `"${prefix}${value}${postfix}"`; } else if (Array.isArray(value)) { value = `["${value.join(`","`)}"]`; - } else { + } else if (value !== null) { value = value ? "true" : "false"; } diff --git a/src/services/auth-service/auth-service.ts b/src/services/auth-service/auth-service.ts index 22c9dcd6..8601e208 100644 --- a/src/services/auth-service/auth-service.ts +++ b/src/services/auth-service/auth-service.ts @@ -2,10 +2,13 @@ // // SPDX-License-Identifier: AGPL-3.0 -import { User, UserPrefs } from "~/models/user"; +import { getUserFullname, User, UserPrefs } from "~/models/user"; import { AxiosInstance } from "axios"; import { ApiActions } from "~/services/api/api-actions"; import * as uuid from "uuid/v4"; +import { Session, SessionStatus } from "~/models/session"; +import { Config } from "~/common/config"; +import { uniqBy } from "lodash"; export const API_TOKEN_KEY = 'apiToken'; export const USER_EMAIL_KEY = 'userEmail'; @@ -137,4 +140,53 @@ export class AuthService { const uuidParts = uuid ? uuid.split('-') : []; return uuidParts.length > 1 ? `${uuidParts[0]}-${uuidParts[1]}` : undefined; } + + public getSessions(): Session[] { + try { + const sessions = JSON.parse(localStorage.getItem("sessions") || ''); + return sessions; + } catch { + return []; + } + } + + public saveSessions(sessions: Session[]) { + localStorage.setItem("sessions", JSON.stringify(sessions)); + } + + public buildSessions(cfg: Config, user?: User) { + const currentSession = { + clusterId: cfg.uuidPrefix, + remoteHost: cfg.rootUrl, + baseUrl: cfg.baseUrl, + username: getUserFullname(user), + email: user ? user.email : '', + token: this.getApiToken(), + loggedIn: true, + active: true, + status: SessionStatus.VALIDATED + } as Session; + const localSessions = this.getSessions(); + const cfgSessions = Object.keys(cfg.remoteHosts).map(clusterId => { + const remoteHost = cfg.remoteHosts[clusterId]; + return { + clusterId, + remoteHost, + baseUrl: '', + username: '', + email: '', + token: '', + loggedIn: false, + active: false, + status: SessionStatus.INVALIDATED + } as Session; + }); + const sessions = [currentSession] + .concat(localSessions) + .concat(cfgSessions); + + const uniqSessions = uniqBy(sessions, 'clusterId'); + + return uniqSessions; + } } diff --git a/src/services/collection-service/collection-service.ts b/src/services/collection-service/collection-service.ts index b0d5cb14..f0f25a2d 100644 --- a/src/services/collection-service/collection-service.ts +++ b/src/services/collection-service/collection-service.ts @@ -56,7 +56,7 @@ export class CollectionService extends TrashableResourceService(this.url) + .then(response => response.data); + } +} diff --git a/src/services/services.ts b/src/services/services.ts index 59fe2d47..78ea714b 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -30,6 +30,7 @@ import { RepositoriesService } from '~/services/repositories-service/repositorie import { AuthorizedKeysService } from '~/services/authorized-keys-service/authorized-keys-service'; import { VocabularyService } from '~/services/vocabulary-service/vocabulary-service'; import { NodeService } from '~/services/node-service/node-service'; +import { FileViewersConfigService } from '~/services/file-viewers-config-service/file-viewers-config-service'; export type ServiceRepository = ReturnType; @@ -64,6 +65,7 @@ export const createServices = (config: Config, actions: ApiActions) => { const tagService = new TagService(linkService); const searchService = new SearchService(); const vocabularyService = new VocabularyService(config.vocabularyUrl); + const fileViewersConfig = new FileViewersConfigService(config.fileViewersConfigUrl); return { ancestorsService, @@ -76,6 +78,7 @@ export const createServices = (config: Config, actions: ApiActions) => { containerRequestService, containerService, favoriteService, + fileViewersConfig, groupsService, keepService, linkService, diff --git a/src/store/auth/auth-action-session.ts b/src/store/auth/auth-action-session.ts new file mode 100644 index 00000000..e5e2e575 --- /dev/null +++ b/src/store/auth/auth-action-session.ts @@ -0,0 +1,215 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import { Dispatch } from "redux"; +import { setBreadcrumbs } from "~/store/breadcrumbs/breadcrumbs-actions"; +import { RootState } from "~/store/store"; +import { ServiceRepository } from "~/services/services"; +import Axios from "axios"; +import { getUserFullname, User } from "~/models/user"; +import { authActions } from "~/store/auth/auth-action"; +import { Config, DISCOVERY_URL } from "~/common/config"; +import { Session, SessionStatus } from "~/models/session"; +import { progressIndicatorActions } from "~/store/progress-indicator/progress-indicator-actions"; +import { AuthService, UserDetailsResponse } from "~/services/auth-service/auth-service"; +import * as jsSHA from "jssha"; + +const getRemoteHostBaseUrl = async (remoteHost: string): Promise => { + let url = remoteHost; + if (url.indexOf('://') < 0) { + url = 'https://' + url; + } + const origin = new URL(url).origin; + let baseUrl: string | null = null; + + try { + const resp = await Axios.get(`${origin}/${DISCOVERY_URL}`); + baseUrl = resp.data.baseUrl; + } catch (err) { + try { + const resp = await Axios.get(`${origin}/status.json`); + baseUrl = resp.data.apiBaseURL; + } catch (err) { + } + } + + if (baseUrl && baseUrl[baseUrl.length - 1] === '/') { + baseUrl = baseUrl.substr(0, baseUrl.length - 1); + } + + return baseUrl; +}; + +const getUserDetails = async (baseUrl: string, token: string): Promise => { + const resp = await Axios.get(`${baseUrl}/users/current`, { + headers: { + Authorization: `OAuth2 ${token}` + } + }); + return resp.data; +}; + +const getTokenUuid = async (baseUrl: string, token: string): Promise => { + if (token.startsWith("v2/")) { + const uuid = token.split("/")[1]; + return Promise.resolve(uuid); + } + + const resp = await Axios.get(`${baseUrl}/api_client_authorizations`, { + headers: { + Authorization: `OAuth2 ${token}` + }, + data: { + filters: JSON.stringify([['api_token', '=', token]]) + } + }); + + return resp.data.items[0].uuid; +}; + +const getSaltedToken = (clusterId: string, tokenUuid: string, token: string) => { + const shaObj = new jsSHA("SHA-1", "TEXT"); + let secret = token; + if (token.startsWith("v2/")) { + secret = token.split("/")[2]; + } + shaObj.setHMACKey(secret, "TEXT"); + shaObj.update(clusterId); + const hmac = shaObj.getHMAC("HEX"); + return `v2/${tokenUuid}/${hmac}`; +}; + +const clusterLogin = async (clusterId: string, baseUrl: string, activeSession: Session): Promise<{user: User, token: string}> => { + const tokenUuid = await getTokenUuid(activeSession.baseUrl, activeSession.token); + const saltedToken = getSaltedToken(clusterId, tokenUuid, activeSession.token); + const user = await getUserDetails(baseUrl, saltedToken); + return { + user: { + firstName: user.first_name, + lastName: user.last_name, + uuid: user.uuid, + ownerUuid: user.owner_uuid, + email: user.email, + isAdmin: user.is_admin, + identityUrl: user.identity_url, + prefs: user.prefs + }, + token: saltedToken + }; +}; + +const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active); + +export const validateCluster = async (remoteHost: string, clusterId: string, activeSession: Session): Promise<{ user: User; token: string, baseUrl: string }> => { + const baseUrl = await getRemoteHostBaseUrl(remoteHost); + if (!baseUrl) { + return Promise.reject(`Could not find base url for ${remoteHost}`); + } + const { user, token } = await clusterLogin(clusterId, baseUrl, activeSession); + return { baseUrl, user, token }; +}; + +export const validateSession = (session: Session, activeSession: Session) => + async (dispatch: Dispatch): Promise => { + dispatch(authActions.UPDATE_SESSION({ ...session, status: SessionStatus.BEING_VALIDATED })); + session.loggedIn = false; + try { + const { baseUrl, user, token } = await validateCluster(session.remoteHost, session.clusterId, activeSession); + session.baseUrl = baseUrl; + session.token = token; + session.email = user.email; + session.username = getUserFullname(user); + session.loggedIn = true; + } catch { + session.loggedIn = false; + } finally { + session.status = SessionStatus.VALIDATED; + dispatch(authActions.UPDATE_SESSION(session)); + } + return session; + }; + +export const validateSessions = () => + async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { + const sessions = getState().auth.sessions; + const activeSession = getActiveSession(sessions); + if (activeSession) { + dispatch(progressIndicatorActions.START_WORKING("sessionsValidation")); + for (const session of sessions) { + if (session.status === SessionStatus.INVALIDATED) { + await dispatch(validateSession(session, activeSession)); + } + } + services.authService.saveSessions(sessions); + dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation")); + } + }; + +export const addSession = (remoteHost: string) => + async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { + const sessions = getState().auth.sessions; + const activeSession = getActiveSession(sessions); + if (activeSession) { + const clusterId = remoteHost.match(/^(\w+)\./)![1]; + if (sessions.find(s => s.clusterId === clusterId)) { + return Promise.reject("Cluster already exists"); + } + try { + const { baseUrl, user, token } = await validateCluster(remoteHost, clusterId, activeSession); + const session = { + loggedIn: true, + status: SessionStatus.VALIDATED, + active: false, + email: user.email, + username: getUserFullname(user), + remoteHost, + baseUrl, + clusterId, + token + }; + + dispatch(authActions.ADD_SESSION(session)); + services.authService.saveSessions(getState().auth.sessions); + + return session; + } catch (e) { + } + } + return Promise.reject("Could not validate cluster"); + }; + +export const toggleSession = (session: Session) => + async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { + let s = { ...session }; + + if (session.loggedIn) { + s.loggedIn = false; + } else { + const sessions = getState().auth.sessions; + const activeSession = getActiveSession(sessions); + if (activeSession) { + s = await dispatch(validateSession(s, activeSession)) as Session; + } + } + + dispatch(authActions.UPDATE_SESSION(s)); + services.authService.saveSessions(getState().auth.sessions); + }; + +export const initSessions = (authService: AuthService, config: Config, user: User) => + (dispatch: Dispatch) => { + const sessions = authService.buildSessions(config, user); + authService.saveSessions(sessions); + dispatch(authActions.SET_SESSIONS(sessions)); + }; + +export const loadSiteManagerPanel = () => + async (dispatch: Dispatch) => { + try { + dispatch(setBreadcrumbs([{ label: 'Site Manager'}])); + dispatch(validateSessions()); + } catch (e) { + return; + } + }; diff --git a/src/store/auth/auth-action-ssh.ts b/src/store/auth/auth-action-ssh.ts new file mode 100644 index 00000000..2c3a2722 --- /dev/null +++ b/src/store/auth/auth-action-ssh.ts @@ -0,0 +1,102 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import { dialogActions } from "~/store/dialog/dialog-actions"; +import { Dispatch } from "redux"; +import { RootState } from "~/store/store"; +import { ServiceRepository } from "~/services/services"; +import { snackbarActions } from "~/store/snackbar/snackbar-actions"; +import { FormErrors, reset, startSubmit, stopSubmit } from "redux-form"; +import { KeyType } from "~/models/ssh-key"; +import { + AuthorizedKeysServiceError, + getAuthorizedKeysServiceError +} from "~/services/authorized-keys-service/authorized-keys-service"; +import { setBreadcrumbs } from "~/store/breadcrumbs/breadcrumbs-actions"; +import { + authActions, +} from "~/store/auth/auth-action"; + +export const SSH_KEY_CREATE_FORM_NAME = 'sshKeyCreateFormName'; +export const SSH_KEY_PUBLIC_KEY_DIALOG = 'sshKeyPublicKeyDialog'; +export const SSH_KEY_REMOVE_DIALOG = 'sshKeyRemoveDialog'; +export const SSH_KEY_ATTRIBUTES_DIALOG = 'sshKeyAttributesDialog'; + +export interface SshKeyCreateFormDialogData { + publicKey: string; + name: string; +} + +export const openSshKeyCreateDialog = () => dialogActions.OPEN_DIALOG({ id: SSH_KEY_CREATE_FORM_NAME, data: {} }); + +export const openPublicKeyDialog = (name: string, publicKey: string) => + dialogActions.OPEN_DIALOG({ id: SSH_KEY_PUBLIC_KEY_DIALOG, data: { name, publicKey } }); + +export const openSshKeyAttributesDialog = (uuid: string) => + (dispatch: Dispatch, getState: () => RootState) => { + const sshKey = getState().auth.sshKeys.find(it => it.uuid === uuid); + dispatch(dialogActions.OPEN_DIALOG({ id: SSH_KEY_ATTRIBUTES_DIALOG, data: { sshKey } })); + }; + +export const openSshKeyRemoveDialog = (uuid: string) => + (dispatch: Dispatch, getState: () => RootState) => { + dispatch(dialogActions.OPEN_DIALOG({ + id: SSH_KEY_REMOVE_DIALOG, + data: { + title: 'Remove public key', + text: 'Are you sure you want to remove this public key?', + confirmButtonLabel: 'Remove', + uuid + } + })); + }; + +export const removeSshKey = (uuid: string) => + async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { + dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removing ...' })); + await services.authorizedKeysService.delete(uuid); + dispatch(authActions.REMOVE_SSH_KEY(uuid)); + dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Public Key has been successfully removed.', hideDuration: 2000 })); + }; + +export const createSshKey = (data: SshKeyCreateFormDialogData) => + async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { + const userUuid = getState().auth.user!.uuid; + const { name, publicKey } = data; + dispatch(startSubmit(SSH_KEY_CREATE_FORM_NAME)); + try { + const newSshKey = await services.authorizedKeysService.create({ + name, + publicKey, + keyType: KeyType.SSH, + authorizedUserUuid: userUuid + }); + dispatch(authActions.ADD_SSH_KEY(newSshKey)); + dispatch(dialogActions.CLOSE_DIALOG({ id: SSH_KEY_CREATE_FORM_NAME })); + dispatch(reset(SSH_KEY_CREATE_FORM_NAME)); + dispatch(snackbarActions.OPEN_SNACKBAR({ + message: "Public key has been successfully created.", + hideDuration: 2000 + })); + } catch (e) { + const error = getAuthorizedKeysServiceError(e); + if (error === AuthorizedKeysServiceError.UNIQUE_PUBLIC_KEY) { + dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key already exists.' } as FormErrors)); + } else if (error === AuthorizedKeysServiceError.INVALID_PUBLIC_KEY) { + dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key is invalid' } as FormErrors)); + } + } + }; + +export const loadSshKeysPanel = () => + async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { + try { + dispatch(setBreadcrumbs([{ label: 'SSH Keys'}])); + const response = await services.authorizedKeysService.list(); + dispatch(authActions.SET_SSH_KEYS(response.items)); + } catch (e) { + return; + } + }; + diff --git a/src/store/auth/auth-actions.test.ts b/src/store/auth/auth-action.test.ts similarity index 77% rename from src/store/auth/auth-actions.test.ts rename to src/store/auth/auth-action.test.ts index ed223795..e5775a49 100644 --- a/src/store/auth/auth-actions.test.ts +++ b/src/store/auth/auth-action.test.ts @@ -18,7 +18,7 @@ import 'jest-localstorage-mock'; import { createServices } from "~/services/services"; import { configureStore, RootStore } from "../store"; import createBrowserHistory from "history/createBrowserHistory"; -import { mockConfig } from '~/common/config'; +import { Config, mockConfig } from '~/common/config'; import { ApiActions } from "~/services/api/api-actions"; describe('auth-actions', () => { @@ -47,11 +47,36 @@ describe('auth-actions', () => { localStorage.setItem(USER_OWNER_UUID_KEY, "ownerUuid"); localStorage.setItem(USER_IS_ADMIN, JSON.stringify("false")); - store.dispatch(initAuth()); + const config: any = { + remoteHosts: { "xc59": "xc59.api.arvados.com" } + }; + + store.dispatch(initAuth(config)); expect(store.getState().auth).toEqual({ apiToken: "token", sshKeys: [], + sessions: [{ + "active": true, + "baseUrl": undefined, + "clusterId": undefined, + "email": "test@test.com", + "loggedIn": true, + "remoteHost": undefined, + "status": 2, + "token": "token", + "username": "John Doe" + }, { + "active": false, + "baseUrl": "", + "clusterId": "xc59", + "email": "", + "loggedIn": false, + "remoteHost": "xc59.api.arvados.com", + "status": 0, + "token": "", + "username": "" + }], user: { email: "test@test.com", firstName: "John", diff --git a/src/store/auth/auth-action.ts b/src/store/auth/auth-action.ts index d72a3ece..6c54a5c9 100644 --- a/src/store/auth/auth-action.ts +++ b/src/store/auth/auth-action.ts @@ -4,17 +4,14 @@ import { ofType, unionize, UnionOf } from '~/common/unionize'; import { Dispatch } from "redux"; -import { reset, stopSubmit, startSubmit, FormErrors } from 'redux-form'; import { AxiosInstance } from "axios"; import { RootState } from "../store"; -import { snackbarActions } from '~/store/snackbar/snackbar-actions'; -import { dialogActions } from '~/store/dialog/dialog-actions'; -import { setBreadcrumbs } from '~/store/breadcrumbs/breadcrumbs-actions'; import { ServiceRepository } from "~/services/services"; -import { getAuthorizedKeysServiceError, AuthorizedKeysServiceError } from '~/services/authorized-keys-service/authorized-keys-service'; -import { KeyType, SshKeyResource } from '~/models/ssh-key'; +import { SshKeyResource } from '~/models/ssh-key'; import { User } from "~/models/user"; -import * as Routes from '~/routes/routes'; +import { Session } from "~/models/session"; +import { Config } from '~/common/config'; +import { initSessions } from "~/store/auth/auth-action-session"; export const authActions = unionize({ SAVE_API_TOKEN: ofType(), @@ -25,19 +22,13 @@ export const authActions = unionize({ USER_DETAILS_SUCCESS: ofType(), SET_SSH_KEYS: ofType(), ADD_SSH_KEY: ofType(), - REMOVE_SSH_KEY: ofType() + REMOVE_SSH_KEY: ofType(), + SET_SESSIONS: ofType(), + ADD_SESSION: ofType(), + REMOVE_SESSION: ofType(), + UPDATE_SESSION: ofType() }); -export const SSH_KEY_CREATE_FORM_NAME = 'sshKeyCreateFormName'; -export const SSH_KEY_PUBLIC_KEY_DIALOG = 'sshKeyPublicKeyDialog'; -export const SSH_KEY_REMOVE_DIALOG = 'sshKeyRemoveDialog'; -export const SSH_KEY_ATTRIBUTES_DIALOG = 'sshKeyAttributesDialog'; - -export interface SshKeyCreateFormDialogData { - publicKey: string; - name: string; -} - function setAuthorizationHeader(services: ServiceRepository, token: string) { services.apiClient.defaults.headers.common = { Authorization: `OAuth2 ${token}` @@ -51,7 +42,7 @@ function removeAuthorizationHeader(client: AxiosInstance) { delete client.defaults.headers.common.Authorization; } -export const initAuth = () => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { +export const initAuth = (config: Config) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { const user = services.authService.getUser(); const token = services.authService.getApiToken(); if (token) { @@ -59,6 +50,7 @@ export const initAuth = () => (dispatch: Dispatch, getState: () => RootState, se } if (token && user) { dispatch(authActions.INIT({ user, token })); + dispatch(initSessions(services.authService, config, user)); } }; @@ -90,80 +82,4 @@ export const getUserDetails = () => (dispatch: Dispatch, getState: () => RootSta }); }; -export const openSshKeyCreateDialog = () => dialogActions.OPEN_DIALOG({ id: SSH_KEY_CREATE_FORM_NAME, data: {} }); - -export const openPublicKeyDialog = (name: string, publicKey: string) => - dialogActions.OPEN_DIALOG({ id: SSH_KEY_PUBLIC_KEY_DIALOG, data: { name, publicKey } }); - -export const openSshKeyAttributesDialog = (uuid: string) => - (dispatch: Dispatch, getState: () => RootState) => { - const sshKey = getState().auth.sshKeys.find(it => it.uuid === uuid); - dispatch(dialogActions.OPEN_DIALOG({ id: SSH_KEY_ATTRIBUTES_DIALOG, data: { sshKey } })); - }; - -export const openSshKeyRemoveDialog = (uuid: string) => - (dispatch: Dispatch, getState: () => RootState) => { - dispatch(dialogActions.OPEN_DIALOG({ - id: SSH_KEY_REMOVE_DIALOG, - data: { - title: 'Remove public key', - text: 'Are you sure you want to remove this public key?', - confirmButtonLabel: 'Remove', - uuid - } - })); - }; - -export const removeSshKey = (uuid: string) => - async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removing ...' })); - await services.authorizedKeysService.delete(uuid); - dispatch(authActions.REMOVE_SSH_KEY(uuid)); - dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Public Key has been successfully removed.', hideDuration: 2000 })); - }; - -export const createSshKey = (data: SshKeyCreateFormDialogData) => - async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - const userUuid = getState().auth.user!.uuid; - const { name, publicKey } = data; - dispatch(startSubmit(SSH_KEY_CREATE_FORM_NAME)); - try { - const newSshKey = await services.authorizedKeysService.create({ - name, - publicKey, - keyType: KeyType.SSH, - authorizedUserUuid: userUuid - }); - dispatch(authActions.ADD_SSH_KEY(newSshKey)); - dispatch(dialogActions.CLOSE_DIALOG({ id: SSH_KEY_CREATE_FORM_NAME })); - dispatch(reset(SSH_KEY_CREATE_FORM_NAME)); - dispatch(snackbarActions.OPEN_SNACKBAR({ - message: "Public key has been successfully created.", - hideDuration: 2000 - })); - } catch (e) { - const error = getAuthorizedKeysServiceError(e); - if (error === AuthorizedKeysServiceError.UNIQUE_PUBLIC_KEY) { - dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key already exists.' } as FormErrors)); - } else if (error === AuthorizedKeysServiceError.INVALID_PUBLIC_KEY) { - dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key is invalid' } as FormErrors)); - } - } - }; - -export const loadSshKeysPanel = () => - async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - try { - const userUuid = getState().auth.user!.uuid; - const { router } = getState(); - const pathname = router.location ? router.location.pathname : ''; - dispatch(setBreadcrumbs([{ label: 'SSH Keys' }])); - const response = await services.authorizedKeysService.list(); - const userSshKeys = response.items.find(it => it.ownerUuid === userUuid); - return Routes.matchSshKeysAdminRoute(pathname) ? dispatch(authActions.SET_SSH_KEYS(response.items)) : dispatch(authActions.SET_SSH_KEYS([userSshKeys!])); - } catch (e) { - return; - } - }; - export type AuthAction = UnionOf; diff --git a/src/store/auth/auth-reducer.test.ts b/src/store/auth/auth-reducer.test.ts index eb7e0c0d..773f9f82 100644 --- a/src/store/auth/auth-reducer.test.ts +++ b/src/store/auth/auth-reducer.test.ts @@ -38,7 +38,8 @@ describe('auth-reducer', () => { expect(state).toEqual({ apiToken: "token", user, - sshKeys: [] + sshKeys: [], + sessions: [] }); }); @@ -49,7 +50,8 @@ describe('auth-reducer', () => { expect(state).toEqual({ apiToken: "token", user: undefined, - sshKeys: [] + sshKeys: [], + sessions: [] }); }); @@ -71,6 +73,7 @@ describe('auth-reducer', () => { expect(state).toEqual({ apiToken: undefined, sshKeys: [], + sessions: [], user: { email: "test@test.com", firstName: "John", diff --git a/src/store/auth/auth-reducer.ts b/src/store/auth/auth-reducer.ts index a8e4340a..a2822f10 100644 --- a/src/store/auth/auth-reducer.ts +++ b/src/store/auth/auth-reducer.ts @@ -6,17 +6,20 @@ import { authActions, AuthAction } from "./auth-action"; import { User } from "~/models/user"; import { ServiceRepository } from "~/services/services"; import { SshKeyResource } from '~/models/ssh-key'; +import { Session } from "~/models/session"; export interface AuthState { user?: User; apiToken?: string; sshKeys: SshKeyResource[]; + sessions: Session[]; } const initialState: AuthState = { user: undefined, apiToken: undefined, - sshKeys: [] + sshKeys: [], + sessions: [] }; export const authReducer = (services: ServiceRepository) => (state = initialState, action: AuthAction) => { @@ -45,6 +48,26 @@ export const authReducer = (services: ServiceRepository) => (state = initialStat REMOVE_SSH_KEY: (uuid: string) => { return { ...state, sshKeys: state.sshKeys.filter((sshKey) => sshKey.uuid !== uuid )}; }, + SET_SESSIONS: (sessions: Session[]) => { + return { ...state, sessions }; + }, + ADD_SESSION: (session: Session) => { + return { ...state, sessions: state.sessions.concat(session) }; + }, + REMOVE_SESSION: (clusterId: string) => { + return { + ...state, + sessions: state.sessions.filter( + session => session.clusterId !== clusterId + )}; + }, + UPDATE_SESSION: (session: Session) => { + return { + ...state, + sessions: state.sessions.map( + s => s.clusterId === session.clusterId ? session : s + )}; + }, default: () => state }); }; diff --git a/src/store/breadcrumbs/breadcrumbs-actions.ts b/src/store/breadcrumbs/breadcrumbs-actions.ts index 8b1eb2b0..71de5ce4 100644 --- a/src/store/breadcrumbs/breadcrumbs-actions.ts +++ b/src/store/breadcrumbs/breadcrumbs-actions.ts @@ -14,6 +14,7 @@ import { ServiceRepository } from '~/services/services'; import { SidePanelTreeCategory, activateSidePanelTreeItem } from '~/store/side-panel-tree/side-panel-tree-actions'; import { updateResources } from '../resources/resources-actions'; import { ResourceKind } from '~/models/resource'; +import { GroupResource } from '~/models/group'; export const BREADCRUMBS = 'breadcrumbs'; @@ -89,3 +90,22 @@ export const setProcessBreadcrumbs = (processUuid: string) => dispatch(setProjectBreadcrumbs(process.containerRequest.ownerUuid)); } }; + +export const GROUPS_PANEL_LABEL = 'Groups'; + +export const setGroupsBreadcrumbs = () => + setBreadcrumbs([{ label: GROUPS_PANEL_LABEL }]); + +export const setGroupDetailsBreadcrumbs = (groupUuid: string) => + (dispatch: Dispatch, getState: () => RootState) => { + + const group = getResource(groupUuid)(getState().resources); + + const breadcrumbs: ResourceBreadcrumb[] = [ + { label: GROUPS_PANEL_LABEL, uuid: GROUPS_PANEL_LABEL }, + { label: group ? group.name : groupUuid, uuid: groupUuid }, + ]; + + dispatch(setBreadcrumbs(breadcrumbs)); + + }; diff --git a/src/store/file-viewers/file-viewers-actions.ts b/src/store/file-viewers/file-viewers-actions.ts new file mode 100644 index 00000000..44bfd2fd --- /dev/null +++ b/src/store/file-viewers/file-viewers-actions.ts @@ -0,0 +1,25 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import { Dispatch } from 'redux'; +import { ServiceRepository } from '~/services/services'; +import { propertiesActions } from '~/store/properties/properties-actions'; +import { FILE_VIEWERS_PROPERTY_NAME, DEFAULT_FILE_VIEWERS } from '~/store/file-viewers/file-viewers-selectors'; +import { FileViewerList } from '~/models/file-viewers-config'; + +export const loadFileViewersConfig = async (dispatch: Dispatch, _: {}, { fileViewersConfig }: ServiceRepository) => { + + let config: FileViewerList; + try{ + config = await fileViewersConfig.get(); + } catch (e){ + config = DEFAULT_FILE_VIEWERS; + } + + dispatch(propertiesActions.SET_PROPERTY({ + key: FILE_VIEWERS_PROPERTY_NAME, + value: config, + })); + +}; diff --git a/src/store/file-viewers/file-viewers-selectors.ts b/src/store/file-viewers/file-viewers-selectors.ts new file mode 100644 index 00000000..abc9d3d1 --- /dev/null +++ b/src/store/file-viewers/file-viewers-selectors.ts @@ -0,0 +1,12 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import { PropertiesState, getProperty } from '~/store/properties/properties'; +import { FileViewerList } from '~/models/file-viewers-config'; + +export const FILE_VIEWERS_PROPERTY_NAME = 'fileViewers'; + +export const DEFAULT_FILE_VIEWERS: FileViewerList = []; +export const getFileViewers = (state: PropertiesState) => + getProperty(FILE_VIEWERS_PROPERTY_NAME)(state) || DEFAULT_FILE_VIEWERS; diff --git a/src/store/group-details-panel/group-details-panel-actions.ts b/src/store/group-details-panel/group-details-panel-actions.ts new file mode 100644 index 00000000..4ad01594 --- /dev/null +++ b/src/store/group-details-panel/group-details-panel-actions.ts @@ -0,0 +1,132 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import { bindDataExplorerActions } from '~/store/data-explorer/data-explorer-action'; +import { Dispatch } from 'redux'; +import { propertiesActions } from '~/store/properties/properties-actions'; +import { getProperty } from '~/store/properties/properties'; +import { Person } from '~/views-components/sharing-dialog/people-select'; +import { dialogActions } from '~/store/dialog/dialog-actions'; +import { reset, startSubmit } from 'redux-form'; +import { addGroupMember, deleteGroupMember } from '~/store/groups-panel/groups-panel-actions'; +import { getResource } from '~/store/resources/resources'; +import { GroupResource } from '~/models/group'; +import { RootState } from '~/store/store'; +import { ServiceRepository } from '~/services/services'; +import { PermissionResource } from '~/models/permission'; +import { GroupDetailsPanel } from '~/views/group-details-panel/group-details-panel'; +import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions'; +import { UserResource, getUserFullname } from '~/models/user'; + +export const GROUP_DETAILS_PANEL_ID = 'groupDetailsPanel'; +export const ADD_GROUP_MEMBERS_DIALOG = 'addGrupMembers'; +export const ADD_GROUP_MEMBERS_FORM = 'addGrupMembers'; +export const ADD_GROUP_MEMBERS_USERS_FIELD_NAME = 'users'; +export const MEMBER_ATTRIBUTES_DIALOG = 'memberAttributesDialog'; +export const MEMBER_REMOVE_DIALOG = 'memberRemoveDialog'; + +export const GroupDetailsPanelActions = bindDataExplorerActions(GROUP_DETAILS_PANEL_ID); + +export const loadGroupDetailsPanel = (groupUuid: string) => + (dispatch: Dispatch) => { + dispatch(propertiesActions.SET_PROPERTY({ key: GROUP_DETAILS_PANEL_ID, value: groupUuid })); + dispatch(GroupDetailsPanelActions.REQUEST_ITEMS()); + }; + +export const getCurrentGroupDetailsPanelUuid = getProperty(GROUP_DETAILS_PANEL_ID); + +export interface AddGroupMembersFormData { + [ADD_GROUP_MEMBERS_USERS_FIELD_NAME]: Person[]; +} + +export const openAddGroupMembersDialog = () => + (dispatch: Dispatch) => { + dispatch(dialogActions.OPEN_DIALOG({ id: ADD_GROUP_MEMBERS_DIALOG, data: {} })); + dispatch(reset(ADD_GROUP_MEMBERS_FORM)); + }; + +export const addGroupMembers = ({ users }: AddGroupMembersFormData) => + + async (dispatch: Dispatch, getState: () => RootState, { permissionService }: ServiceRepository) => { + + const groupUuid = getCurrentGroupDetailsPanelUuid(getState().properties); + + if (groupUuid) { + + dispatch(startSubmit(ADD_GROUP_MEMBERS_FORM)); + + const group = getResource(groupUuid)(getState().resources); + + for (const user of users) { + + await addGroupMember({ + user, + group: { + uuid: groupUuid, + name: group ? group.name : groupUuid, + }, + dispatch, + permissionService, + }); + + } + + dispatch(dialogActions.CLOSE_DIALOG({ id: ADD_GROUP_MEMBERS_FORM })); + dispatch(GroupDetailsPanelActions.REQUEST_ITEMS()); + + } + }; + +export const openGroupMemberAttributes = (uuid: string) => + (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { + const { resources } = getState(); + const data = getResource(uuid)(resources); + dispatch(dialogActions.OPEN_DIALOG({ id: MEMBER_ATTRIBUTES_DIALOG, data })); + }; + +export const openRemoveGroupMemberDialog = (uuid: string) => + (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { + dispatch(dialogActions.OPEN_DIALOG({ + id: MEMBER_REMOVE_DIALOG, + data: { + title: 'Remove member', + text: 'Are you sure you want to remove this member from this group?', + confirmButtonLabel: 'Remove', + uuid + } + })); + }; + +export const removeGroupMember = (uuid: string) => + + async (dispatch: Dispatch, getState: () => RootState, { permissionService }: ServiceRepository) => { + + const groupUuid = getCurrentGroupDetailsPanelUuid(getState().properties); + + if (groupUuid) { + + const group = getResource(groupUuid)(getState().resources); + const user = getResource(groupUuid)(getState().resources); + + dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removing ...' })); + + await deleteGroupMember({ + user: { + uuid, + name: user ? getUserFullname(user) : uuid, + }, + group: { + uuid: groupUuid, + name: group ? group.name : groupUuid, + }, + permissionService, + dispatch, + }); + + dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removed.', hideDuration: 2000, kind: SnackbarKind.SUCCESS })); + dispatch(GroupDetailsPanelActions.REQUEST_ITEMS()); + + } + + }; diff --git a/src/store/group-details-panel/group-details-panel-middleware-service.ts b/src/store/group-details-panel/group-details-panel-middleware-service.ts new file mode 100644 index 00000000..bf424c54 --- /dev/null +++ b/src/store/group-details-panel/group-details-panel-middleware-service.ts @@ -0,0 +1,79 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import { Dispatch, MiddlewareAPI } from "redux"; +import { DataExplorerMiddlewareService, listResultsToDataExplorerItemsMeta } from "~/store/data-explorer/data-explorer-middleware-service"; +import { RootState } from "~/store/store"; +import { ServiceRepository } from "~/services/services"; +import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions'; +import { getDataExplorer } from "~/store/data-explorer/data-explorer-reducer"; +import { FilterBuilder } from '~/services/api/filter-builder'; +import { updateResources } from '~/store/resources/resources-actions'; +import { getCurrentGroupDetailsPanelUuid, GroupDetailsPanelActions } from '~/store/group-details-panel/group-details-panel-actions'; +import { LinkClass } from '~/models/link'; + +export class GroupDetailsPanelMiddlewareService extends DataExplorerMiddlewareService { + + constructor(private services: ServiceRepository, id: string) { + super(id); + } + + async requestItems(api: MiddlewareAPI) { + + const dataExplorer = getDataExplorer(api.getState().dataExplorer, this.getId()); + const groupUuid = getCurrentGroupDetailsPanelUuid(api.getState().properties); + + if (!dataExplorer || !groupUuid) { + + api.dispatch(groupsDetailsPanelDataExplorerIsNotSet()); + + } else { + + try { + + const permissions = await this.services.permissionService.list({ + + filters: new FilterBuilder() + .addEqual('tailUuid', groupUuid) + .addEqual('linkClass', LinkClass.PERMISSION) + .getFilters() + + }); + + api.dispatch(updateResources(permissions.items)); + + const users = await this.services.userService.list({ + + filters: new FilterBuilder() + .addIn('uuid', permissions.items.map(item => item.headUuid)) + .getFilters() + + }); + + api.dispatch(GroupDetailsPanelActions.SET_ITEMS({ + ...listResultsToDataExplorerItemsMeta(permissions), + items: users.items.map(item => item.uuid), + })); + + api.dispatch(updateResources(users.items)); + + } catch (e) { + + api.dispatch(couldNotFetchGroupDetailsContents()); + + } + } + } +} + +const groupsDetailsPanelDataExplorerIsNotSet = () => + snackbarActions.OPEN_SNACKBAR({ + message: 'Group details panel is not ready.' + }); + +const couldNotFetchGroupDetailsContents = () => + snackbarActions.OPEN_SNACKBAR({ + message: 'Could not fetch group details.', + kind: SnackbarKind.ERROR + }); diff --git a/src/store/groups-panel/groups-panel-actions.ts b/src/store/groups-panel/groups-panel-actions.ts new file mode 100644 index 00000000..8632098e --- /dev/null +++ b/src/store/groups-panel/groups-panel-actions.ts @@ -0,0 +1,225 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import { Dispatch } from 'redux'; +import { reset, startSubmit, stopSubmit, FormErrors } from 'redux-form'; +import { bindDataExplorerActions } from "~/store/data-explorer/data-explorer-action"; +import { dialogActions } from '~/store/dialog/dialog-actions'; +import { Person } from '~/views-components/sharing-dialog/people-select'; +import { RootState } from '~/store/store'; +import { ServiceRepository } from '~/services/services'; +import { getResource } from '~/store/resources/resources'; +import { GroupResource } from '~/models/group'; +import { getCommonResourceServiceError, CommonResourceServiceError } from '~/services/common-service/common-resource-service'; +import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions'; +import { PermissionLevel, PermissionResource } from '~/models/permission'; +import { PermissionService } from '~/services/permission-service/permission-service'; +import { FilterBuilder } from '~/services/api/filter-builder'; + +export const GROUPS_PANEL_ID = "groupsPanel"; +export const CREATE_GROUP_DIALOG = "createGroupDialog"; +export const CREATE_GROUP_FORM = "createGroupForm"; +export const CREATE_GROUP_NAME_FIELD_NAME = 'name'; +export const CREATE_GROUP_USERS_FIELD_NAME = 'users'; +export const GROUP_ATTRIBUTES_DIALOG = 'groupAttributesDialog'; +export const GROUP_REMOVE_DIALOG = 'groupRemoveDialog'; + +export const GroupsPanelActions = bindDataExplorerActions(GROUPS_PANEL_ID); + +export const loadGroupsPanel = () => GroupsPanelActions.REQUEST_ITEMS(); + +export const openCreateGroupDialog = () => + (dispatch: Dispatch) => { + dispatch(dialogActions.OPEN_DIALOG({ id: CREATE_GROUP_DIALOG, data: {} })); + dispatch(reset(CREATE_GROUP_FORM)); + }; + +export const openGroupAttributes = (uuid: string) => + (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { + const { resources } = getState(); + const data = getResource(uuid)(resources); + dispatch(dialogActions.OPEN_DIALOG({ id: GROUP_ATTRIBUTES_DIALOG, data })); + }; + +export const removeGroup = (uuid: string) => + async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { + dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removing ...' })); + await services.groupsService.delete(uuid); + dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removed.', hideDuration: 2000, kind: SnackbarKind.SUCCESS })); + dispatch(loadGroupsPanel()); + }; + +export const openRemoveGroupDialog = (uuid: string) => + (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { + dispatch(dialogActions.OPEN_DIALOG({ + id: GROUP_REMOVE_DIALOG, + data: { + title: 'Remove group', + text: 'Are you sure you want to remove this group?', + confirmButtonLabel: 'Remove', + uuid + } + })); + }; + +export interface CreateGroupFormData { + [CREATE_GROUP_NAME_FIELD_NAME]: string; + [CREATE_GROUP_USERS_FIELD_NAME]?: Person[]; +} + +export const createGroup = ({ name, users = [] }: CreateGroupFormData) => + async (dispatch: Dispatch, _: {}, { groupsService, permissionService }: ServiceRepository) => { + + dispatch(startSubmit(CREATE_GROUP_FORM)); + + try { + + const newGroup = await groupsService.create({ name }); + + for (const user of users) { + + await addGroupMember({ + user, + group: newGroup, + dispatch, + permissionService, + }); + + } + + dispatch(dialogActions.CLOSE_DIALOG({ id: CREATE_GROUP_DIALOG })); + dispatch(reset(CREATE_GROUP_FORM)); + dispatch(loadGroupsPanel()); + dispatch(snackbarActions.OPEN_SNACKBAR({ + message: `${newGroup.name} group has been created`, + kind: SnackbarKind.SUCCESS + })); + + return newGroup; + + } catch (e) { + + const error = getCommonResourceServiceError(e); + if (error === CommonResourceServiceError.UNIQUE_VIOLATION) { + dispatch(stopSubmit(CREATE_GROUP_FORM, { name: 'Group with the same name already exists.' } as FormErrors)); + } + + return; + + } + }; + +interface AddGroupMemberArgs { + user: { uuid: string, name: string }; + group: { uuid: string, name: string }; + dispatch: Dispatch; + permissionService: PermissionService; +} + +/** + * Group membership is determined by whether the group has can_read permission on an object. + * If a group G can_read an object A, then we say A is a member of G. + * + * [Permission model docs](https://doc.arvados.org/api/permission-model.html) + */ +export const addGroupMember = async ({ user, group, ...args }: AddGroupMemberArgs) => { + + await createPermission({ + head: { ...user }, + tail: { ...group }, + permissionLevel: PermissionLevel.CAN_READ, + ...args, + }); + +}; + +interface CreatePermissionLinkArgs { + head: { uuid: string, name: string }; + tail: { uuid: string, name: string }; + permissionLevel: PermissionLevel; + dispatch: Dispatch; + permissionService: PermissionService; +} + +const createPermission = async ({ head, tail, permissionLevel, dispatch, permissionService }: CreatePermissionLinkArgs) => { + + try { + + await permissionService.create({ + tailUuid: tail.uuid, + headUuid: head.uuid, + name: permissionLevel, + }); + + } catch (e) { + + dispatch(snackbarActions.OPEN_SNACKBAR({ + message: `Could not add ${tail.name} -> ${head.name} relation`, + kind: SnackbarKind.ERROR, + })); + + } + +}; + +interface DeleteGroupMemberArgs { + user: { uuid: string, name: string }; + group: { uuid: string, name: string }; + dispatch: Dispatch; + permissionService: PermissionService; +} + +export const deleteGroupMember = async ({ user, group, ...args }: DeleteGroupMemberArgs) => { + + await deletePermission({ + tail: group, + head: user, + ...args, + }); + +}; + +interface DeletePermissionLinkArgs { + head: { uuid: string, name: string }; + tail: { uuid: string, name: string }; + dispatch: Dispatch; + permissionService: PermissionService; +} + +export const deletePermission = async ({ head, tail, dispatch, permissionService }: DeletePermissionLinkArgs) => { + + try { + + const permissionsResponse = await permissionService.list({ + + filters: new FilterBuilder() + .addEqual('tailUuid', tail.uuid) + .addEqual('headUuid', head.uuid) + .getFilters() + + }); + + const [permission] = permissionsResponse.items; + + if (permission) { + + await permissionService.delete(permission.uuid); + + } else { + + throw new Error('Permission not found'); + + } + + + } catch (e) { + + dispatch(snackbarActions.OPEN_SNACKBAR({ + message: `Could not delete ${tail.name} -> ${head.name} relation`, + kind: SnackbarKind.ERROR, + })); + + } + +}; \ No newline at end of file diff --git a/src/store/groups-panel/groups-panel-middleware-service.ts b/src/store/groups-panel/groups-panel-middleware-service.ts new file mode 100644 index 00000000..7c70666e --- /dev/null +++ b/src/store/groups-panel/groups-panel-middleware-service.ts @@ -0,0 +1,97 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import { Dispatch, MiddlewareAPI } from "redux"; +import { DataExplorerMiddlewareService, listResultsToDataExplorerItemsMeta, dataExplorerToListParams } from "~/store/data-explorer/data-explorer-middleware-service"; +import { RootState } from "~/store/store"; +import { ServiceRepository } from "~/services/services"; +import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions'; +import { getDataExplorer, DataExplorer, getSortColumn } from "~/store/data-explorer/data-explorer-reducer"; +import { GroupsPanelActions } from '~/store/groups-panel/groups-panel-actions'; +import { FilterBuilder } from '~/services/api/filter-builder'; +import { updateResources } from '~/store/resources/resources-actions'; +import { OrderBuilder, OrderDirection } from '~/services/api/order-builder'; +import { GroupResource, GroupClass } from '~/models/group'; +import { SortDirection } from '~/components/data-table/data-column'; +import { GroupsPanelColumnNames } from '~/views/groups-panel/groups-panel'; + +export class GroupsPanelMiddlewareService extends DataExplorerMiddlewareService { + + constructor(private services: ServiceRepository, id: string) { + super(id); + } + + async requestItems(api: MiddlewareAPI) { + + const dataExplorer = getDataExplorer(api.getState().dataExplorer, this.getId()); + + if (!dataExplorer) { + + api.dispatch(groupsPanelDataExplorerIsNotSet()); + + } else { + + try { + + const order = new OrderBuilder(); + const sortColumn = getSortColumn(dataExplorer); + if (sortColumn) { + const direction = + sortColumn.sortDirection === SortDirection.ASC && sortColumn.name === GroupsPanelColumnNames.GROUP + ? OrderDirection.ASC + : OrderDirection.DESC; + + order.addOrder(direction, 'name'); + } + + const filters = new FilterBuilder() + .addNotIn('groupClass', [GroupClass.PROJECT]) + .addILike('name', dataExplorer.searchValue) + .getFilters(); + + const response = await this.services.groupsService + .list({ + ...dataExplorerToListParams(dataExplorer), + filters, + order: order.getOrder(), + }); + + api.dispatch(updateResources(response.items)); + + api.dispatch(GroupsPanelActions.SET_ITEMS({ + ...listResultsToDataExplorerItemsMeta(response), + items: response.items.map(item => item.uuid), + })); + + const permissions = await this.services.permissionService.list({ + + filters: new FilterBuilder() + .addIn('tailUuid', response.items.map(item => item.uuid)) + .getFilters() + + }); + + api.dispatch(updateResources(permissions.items)); + + + } catch (e) { + + api.dispatch(couldNotFetchFavoritesContents()); + + } + } + } +} + +const groupsPanelDataExplorerIsNotSet = () => + snackbarActions.OPEN_SNACKBAR({ + message: 'Groups panel is not ready.' + }); + +const couldNotFetchFavoritesContents = () => + snackbarActions.OPEN_SNACKBAR({ + message: 'Could not fetch groups.', + kind: SnackbarKind.ERROR + }); + diff --git a/src/store/navigation/navigation-action.ts b/src/store/navigation/navigation-action.ts index 92443c02..f610eb5e 100644 --- a/src/store/navigation/navigation-action.ts +++ b/src/store/navigation/navigation-action.ts @@ -8,9 +8,10 @@ import { ResourceKind, extractUuidKind } from '~/models/resource'; import { getCollectionUrl } from "~/models/collection"; import { getProjectUrl } from "~/models/project"; import { SidePanelTreeCategory } from '../side-panel-tree/side-panel-tree-actions'; -import { Routes, getProcessUrl, getProcessLogUrl } from '~/routes/routes'; +import { Routes, getProcessUrl, getProcessLogUrl, getGroupUrl } from '~/routes/routes'; import { RootState } from '~/store/store'; import { ServiceRepository } from '~/services/services'; +import { GROUPS_PANEL_LABEL } from '~/store/breadcrumbs/breadcrumbs-actions'; export const navigateTo = (uuid: string) => async (dispatch: Dispatch) => { @@ -32,6 +33,8 @@ export const navigateTo = (uuid: string) => dispatch(navigateToWorkflows); } else if (uuid === SidePanelTreeCategory.TRASH) { dispatch(navigateToTrash); + } else if (uuid === GROUPS_PANEL_LABEL) { + dispatch(navigateToGroups); } }; @@ -74,6 +77,8 @@ export const navigateToSshKeysAdmin= push(Routes.SSH_KEYS_ADMIN); export const navigateToSshKeysUser= push(Routes.SSH_KEYS_USER); +export const navigateToSiteManager= push(Routes.SITE_MANAGER); + export const navigateToMyAccount = push(Routes.MY_ACCOUNT); export const navigateToKeepServices = push(Routes.KEEP_SERVICES); @@ -84,4 +89,8 @@ export const navigateToUsers = push(Routes.USERS); export const navigateToApiClientAuthorizations = push(Routes.API_CLIENT_AUTHORIZATIONS); -export const navigateToLinks = push(Routes.LINKS); \ No newline at end of file +export const navigateToGroups = push(Routes.GROUPS); + +export const navigateToGroupDetails = compose(push, getGroupUrl); + +export const navigateToLinks = push(Routes.LINKS); diff --git a/src/store/store.ts b/src/store/store.ts index d196e632..14a6ba11 100644 --- a/src/store/store.ts +++ b/src/store/store.ts @@ -49,6 +49,10 @@ import { keepServicesReducer } from '~/store/keep-services/keep-services-reducer import { UserMiddlewareService } from '~/store/users/user-panel-middleware-service'; import { USERS_PANEL_ID } from '~/store/users/users-actions'; import { apiClientAuthorizationsReducer } from '~/store/api-client-authorizations/api-client-authorizations-reducer'; +import { GroupsPanelMiddlewareService } from '~/store/groups-panel/groups-panel-middleware-service'; +import { GROUPS_PANEL_ID } from '~/store/groups-panel/groups-panel-actions'; +import { GroupDetailsPanelMiddlewareService } from '~/store/group-details-panel/group-details-panel-middleware-service'; +import { GROUP_DETAILS_PANEL_ID } from '~/store/group-details-panel/group-details-panel-actions'; import { LINK_PANEL_ID } from '~/store/link-panel/link-panel-actions'; import { LinkMiddlewareService } from '~/store/link-panel/link-panel-middleware-service'; import { COMPUTE_NODE_PANEL_ID } from '~/store/compute-nodes/compute-nodes-actions'; @@ -87,6 +91,13 @@ export function configureStore(history: History, services: ServiceRepository): R const userPanelMiddleware = dataExplorerMiddleware( new UserMiddlewareService(services, USERS_PANEL_ID) ); + const groupsPanelMiddleware = dataExplorerMiddleware( + new GroupsPanelMiddlewareService(services, GROUPS_PANEL_ID) + ); + const groupDetailsPanelMiddleware = dataExplorerMiddleware( + new GroupDetailsPanelMiddlewareService(services, GROUP_DETAILS_PANEL_ID) + ); + const linkPanelMiddleware = dataExplorerMiddleware( new LinkMiddlewareService(services, LINK_PANEL_ID) ); @@ -103,8 +114,10 @@ export function configureStore(history: History, services: ServiceRepository): R sharedWithMePanelMiddleware, workflowPanelMiddleware, userPanelMiddleware, + groupsPanelMiddleware, + groupDetailsPanelMiddleware, linkPanelMiddleware, - computeNodeMiddleware + computeNodeMiddleware, ]; const enhancer = composeEnhancers(applyMiddleware(...middlewares)); return createStore(rootReducer, enhancer); diff --git a/src/store/workbench/workbench-actions.ts b/src/store/workbench/workbench-actions.ts index e42e6c3e..46ab1f59 100644 --- a/src/store/workbench/workbench-actions.ts +++ b/src/store/workbench/workbench-actions.ts @@ -14,7 +14,7 @@ import { favoritePanelActions } from '~/store/favorite-panel/favorite-panel-acti import { projectPanelColumns } from '~/views/project-panel/project-panel'; import { favoritePanelColumns } from '~/views/favorite-panel/favorite-panel'; import { matchRootRoute } from '~/routes/routes'; -import { setSidePanelBreadcrumbs, setProcessBreadcrumbs, setSharedWithMeBreadcrumbs, setTrashBreadcrumbs, setBreadcrumbs } from '~/store/breadcrumbs/breadcrumbs-actions'; +import { setSidePanelBreadcrumbs, setProcessBreadcrumbs, setSharedWithMeBreadcrumbs, setTrashBreadcrumbs, setBreadcrumbs, setGroupDetailsBreadcrumbs, setGroupsBreadcrumbs } from '~/store/breadcrumbs/breadcrumbs-actions'; import { navigateToProject } from '~/store/navigation/navigation-action'; import { MoveToFormDialogData } from '~/store/move-to-dialog/move-to-dialog'; import { ServiceRepository } from '~/services/services'; @@ -39,8 +39,9 @@ import { sharedWithMePanelActions } from '~/store/shared-with-me-panel/shared-wi import { loadSharedWithMePanel } from '~/store/shared-with-me-panel/shared-with-me-panel-actions'; 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 { loadSshKeysPanel } from '~/store/auth/auth-action-ssh'; import { loadMyAccountPanel } from '~/store/my-account/my-account-panel-actions'; +import { loadSiteManagerPanel } from '~/store/auth/auth-action-session'; 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'; @@ -65,6 +66,10 @@ import { linkPanelColumns } from '~/views/link-panel/link-panel-root'; import { userPanelColumns } from '~/views/user-panel/user-panel'; import { computeNodePanelColumns } from '~/views/compute-node-panel/compute-node-panel-root'; import { loadApiClientAuthorizationsPanel } from '~/store/api-client-authorizations/api-client-authorizations-actions'; +import * as groupPanelActions from '~/store/groups-panel/groups-panel-actions'; +import { groupsPanelColumns } from '~/views/groups-panel/groups-panel'; +import * as groupDetailsPanelActions from '~/store/group-details-panel/group-details-panel-actions'; +import { groupDetailsPanelColumns } from '~/views/group-details-panel/group-details-panel'; export const WORKBENCH_LOADING_SCREEN = 'workbenchLoadingScreen'; @@ -99,6 +104,8 @@ export const loadWorkbench = () => dispatch(workflowPanelActions.SET_COLUMNS({ columns: workflowPanelColumns })); dispatch(searchResultsPanelActions.SET_COLUMNS({ columns: searchResultsPanelColumns })); dispatch(userBindedActions.SET_COLUMNS({ columns: userPanelColumns })); + dispatch(groupPanelActions.GroupsPanelActions.SET_COLUMNS({ columns: groupsPanelColumns })); + dispatch(groupDetailsPanelActions.GroupDetailsPanelActions.SET_COLUMNS({columns: groupDetailsPanelColumns})); dispatch(linkPanelActions.SET_COLUMNS({ columns: linkPanelColumns })); dispatch(computeNodesActions.SET_COLUMNS({ columns: computeNodePanelColumns })); dispatch(initSidePanelTree()); @@ -429,6 +436,11 @@ export const loadSshKeys = handleFirstTimeLoad( await dispatch(loadSshKeysPanel()); }); +export const loadSiteManager = handleFirstTimeLoad( +async (dispatch: Dispatch) => { + await dispatch(loadSiteManagerPanel()); +}); + export const loadMyAccount = handleFirstTimeLoad( (dispatch: Dispatch) => { dispatch(loadMyAccountPanel()); @@ -455,6 +467,20 @@ export const loadApiClientAuthorizations = handleFirstTimeLoad( await dispatch(loadApiClientAuthorizationsPanel()); }); +export const loadGroupsPanel = handleFirstTimeLoad( + (dispatch: Dispatch) => { + dispatch(setGroupsBreadcrumbs()); + dispatch(groupPanelActions.loadGroupsPanel()); + }); + + +export const loadGroupDetailsPanel = (groupUuid: string) => + handleFirstTimeLoad( + (dispatch: Dispatch) => { + dispatch(setGroupDetailsBreadcrumbs(groupUuid)); + dispatch(groupDetailsPanelActions.loadGroupDetailsPanel(groupUuid)); + }); + const finishLoadingProject = (project: GroupContentsResource | string) => async (dispatch: Dispatch) => { const uuid = typeof project === 'string' ? project : project.uuid; diff --git a/src/validators/is-remote-host.tsx b/src/validators/is-remote-host.tsx new file mode 100644 index 00000000..b5e22312 --- /dev/null +++ b/src/validators/is-remote-host.tsx @@ -0,0 +1,10 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + + +const ERROR_MESSAGE = 'Remote host is invalid'; + +export const isRemoteHost = (value: string) => { + return value.match(/\w+\.\w+\.\w+/i) ? undefined : ERROR_MESSAGE; +}; diff --git a/src/validators/min-length.tsx b/src/validators/min-length.tsx new file mode 100644 index 00000000..9b269531 --- /dev/null +++ b/src/validators/min-length.tsx @@ -0,0 +1,10 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +export const ERROR_MESSAGE = (minLength: number) => `Min length is ${minLength}`; + +export const minLength = + (minLength: number, errorMessage = ERROR_MESSAGE) => + (value: { length: number }) => + value && value.length >= minLength ? undefined : errorMessage(minLength); diff --git a/src/validators/validators.tsx b/src/validators/validators.tsx index 9bc76419..acef9744 100644 --- a/src/validators/validators.tsx +++ b/src/validators/validators.tsx @@ -5,6 +5,7 @@ import { require } from './require'; import { maxLength } from './max-length'; import { isRsaKey } from './is-rsa-key'; +import { isRemoteHost } from "./is-remote-host"; export const TAG_KEY_VALIDATION = [require, maxLength(255)]; export const TAG_VALUE_VALIDATION = [require, maxLength(255)]; @@ -31,4 +32,6 @@ export const USER_LENGTH_VALIDATION = [maxLength(255)]; export const SSH_KEY_PUBLIC_VALIDATION = [require, isRsaKey, maxLength(1024)]; export const SSH_KEY_NAME_VALIDATION = [require, maxLength(255)]; +export const SITE_MANAGER_REMOTE_HOST_VALIDATION = [require, isRemoteHost, maxLength(255)]; + export const MY_ACCOUNT_VALIDATION = [require]; diff --git a/src/views-components/api-token/api-token.tsx b/src/views-components/api-token/api-token.tsx index 718d3589..43c55a92 100644 --- a/src/views-components/api-token/api-token.tsx +++ b/src/views-components/api-token/api-token.tsx @@ -5,13 +5,17 @@ import { RouteProps } from "react-router"; import * as React from "react"; import { connect, DispatchProp } from "react-redux"; -import { getUserDetails, saveApiToken } from "~/store/auth/auth-action"; +import { authActions, getUserDetails, saveApiToken } from "~/store/auth/auth-action"; import { getUrlParameter } from "~/common/url"; import { AuthService } from "~/services/auth-service/auth-service"; import { navigateToRootProject } from "~/store/navigation/navigation-action"; +import { User } from "~/models/user"; +import { Config } from "~/common/config"; +import { initSessions } from "~/store/auth/auth-action-session"; interface ApiTokenProps { authService: AuthService; + config: Config; } export const ApiToken = connect()( @@ -20,7 +24,9 @@ export const ApiToken = connect()( const search = this.props.location ? this.props.location.search : ""; const apiToken = getUrlParameter(search, 'api_token'); this.props.dispatch(saveApiToken(apiToken)); - this.props.dispatch(getUserDetails()).finally(() => { + this.props.dispatch(getUserDetails()).then((user: User) => { + this.props.dispatch(initSessions(this.props.authService, this.props.config, user)); + }).finally(() => { this.props.dispatch(navigateToRootProject); }); } diff --git a/src/views-components/context-menu/action-sets/collection-files-item-action-set.ts b/src/views-components/context-menu/action-sets/collection-files-item-action-set.ts index b5564891..94f702e8 100644 --- a/src/views-components/context-menu/action-sets/collection-files-item-action-set.ts +++ b/src/views-components/context-menu/action-sets/collection-files-item-action-set.ts @@ -6,6 +6,7 @@ import { ContextMenuActionSet } from "../context-menu-action-set"; import { RenameIcon, RemoveIcon } from "~/components/icon/icon"; import { DownloadCollectionFileAction } from "../actions/download-collection-file-action"; import { openFileRemoveDialog, openRenameFileDialog } from '~/store/collection-panel/collection-panel-files/collection-panel-files-actions'; +import { FileViewerActions } from '~/views-components/context-menu/actions/file-viewer-actions'; export const collectionFilesItemActionSet: ContextMenuActionSet = [[{ @@ -23,4 +24,7 @@ export const collectionFilesItemActionSet: ContextMenuActionSet = [[{ execute: (dispatch, resource) => { dispatch(openFileRemoveDialog(resource.uuid)); } +}], [{ + component: FileViewerActions, + execute: () => { return; }, }]]; diff --git a/src/views-components/context-menu/action-sets/group-action-set.ts b/src/views-components/context-menu/action-sets/group-action-set.ts new file mode 100644 index 00000000..8d718a33 --- /dev/null +++ b/src/views-components/context-menu/action-sets/group-action-set.ts @@ -0,0 +1,28 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import { ContextMenuActionSet } from "~/views-components/context-menu/context-menu-action-set"; +import { AdvancedIcon, RemoveIcon, AttributesIcon } from "~/components/icon/icon"; +import { openAdvancedTabDialog } from "~/store/advanced-tab/advanced-tab"; +import { openGroupAttributes, openRemoveGroupDialog } from "~/store/groups-panel/groups-panel-actions"; + +export const groupActionSet: ContextMenuActionSet = [[{ + name: "Attributes", + icon: AttributesIcon, + execute: (dispatch, { uuid }) => { + dispatch(openGroupAttributes(uuid)); + } +}, { + name: "Advanced", + icon: AdvancedIcon, + execute: (dispatch, resource) => { + dispatch(openAdvancedTabDialog(resource.uuid)); + } +}, { + name: "Remove", + icon: RemoveIcon, + execute: (dispatch, { uuid }) => { + dispatch(openRemoveGroupDialog(uuid)); + } +}]]; \ No newline at end of file diff --git a/src/views-components/context-menu/action-sets/group-member-action-set.ts b/src/views-components/context-menu/action-sets/group-member-action-set.ts new file mode 100644 index 00000000..a8b3dd1f --- /dev/null +++ b/src/views-components/context-menu/action-sets/group-member-action-set.ts @@ -0,0 +1,28 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import { ContextMenuActionSet } from "~/views-components/context-menu/context-menu-action-set"; +import { AdvancedIcon, RemoveIcon, AttributesIcon } from "~/components/icon/icon"; +import { openAdvancedTabDialog } from "~/store/advanced-tab/advanced-tab"; +import { openGroupMemberAttributes, openRemoveGroupMemberDialog } from '~/store/group-details-panel/group-details-panel-actions'; + +export const groupMemberActionSet: ContextMenuActionSet = [[{ + name: "Attributes", + icon: AttributesIcon, + execute: (dispatch, { uuid }) => { + dispatch(openGroupMemberAttributes(uuid)); + } +}, { + name: "Advanced", + icon: AdvancedIcon, + execute: (dispatch, resource) => { + dispatch(openAdvancedTabDialog(resource.uuid)); + } +}, { + name: "Remove", + icon: RemoveIcon, + execute: (dispatch, { uuid }) => { + dispatch(openRemoveGroupMemberDialog(uuid)); + } +}]]; \ No newline at end of file diff --git a/src/views-components/context-menu/action-sets/ssh-key-action-set.ts b/src/views-components/context-menu/action-sets/ssh-key-action-set.ts index 0ce0c431..c2885185 100644 --- a/src/views-components/context-menu/action-sets/ssh-key-action-set.ts +++ b/src/views-components/context-menu/action-sets/ssh-key-action-set.ts @@ -4,7 +4,7 @@ import { ContextMenuActionSet } from "~/views-components/context-menu/context-menu-action-set"; import { AdvancedIcon, RemoveIcon, AttributesIcon } from "~/components/icon/icon"; -import { openSshKeyRemoveDialog, openSshKeyAttributesDialog } from '~/store/auth/auth-action'; +import { openSshKeyRemoveDialog, openSshKeyAttributesDialog } from '~/store/auth/auth-action-ssh'; import { openAdvancedTabDialog } from '~/store/advanced-tab/advanced-tab'; export const sshKeyActionSet: ContextMenuActionSet = [[{ diff --git a/src/views-components/context-menu/actions/file-viewer-actions.tsx b/src/views-components/context-menu/actions/file-viewer-actions.tsx new file mode 100644 index 00000000..961e1828 --- /dev/null +++ b/src/views-components/context-menu/actions/file-viewer-actions.tsx @@ -0,0 +1,81 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import * as React from "react"; +import { ListItemText, ListItem, ListItemIcon, Icon } from "@material-ui/core"; +import { RootState } from '~/store/store'; +import { getNodeValue } from '~/models/tree'; +import { CollectionDirectory, CollectionFile, CollectionFileType } from '~/models/collection-file'; +import { FileViewerList, FileViewer } from '~/models/file-viewers-config'; +import { getFileViewers } from '~/store/file-viewers/file-viewers-selectors'; +import { connect } from 'react-redux'; +import { OpenIcon } from '~/components/icon/icon'; + +interface FileViewerActionProps { + fileUrl: string; + viewers: FileViewerList; +} + +const mapStateToProps = (state: RootState): FileViewerActionProps => { + const { resource } = state.contextMenu; + if (resource) { + const file = getNodeValue(resource.uuid)(state.collectionPanelFiles); + if (file) { + const fileViewers = getFileViewers(state.properties); + return { + fileUrl: file.url, + viewers: fileViewers.filter(enabledViewers(file)), + }; + } + } + return { + fileUrl: '', + viewers: [], + }; +}; + +const enabledViewers = (file: CollectionFile | CollectionDirectory) => + ({ extensions, collections }: FileViewer) => { + if (collections && file.type === CollectionFileType.DIRECTORY) { + return true; + } else if (extensions) { + return extensions.some(extension => file.name.endsWith(extension)); + } else { + return true; + } + }; + +const fillViewerUrl = (fileUrl: string, { url, filePathParam }: FileViewer) => { + const viewerUrl = new URL(url); + viewerUrl.searchParams.append(filePathParam, fileUrl); + return viewerUrl.href; +}; + +export const FileViewerActions = connect(mapStateToProps)( + ({ fileUrl, viewers, onClick }: FileViewerActionProps & { onClick: () => void }) => + <> + {viewers.map(viewer => + + + { + viewer.iconUrl + ? + + + : + } + + + {viewer.name} + + + )} + ); diff --git a/src/views-components/context-menu/context-menu.tsx b/src/views-components/context-menu/context-menu.tsx index a9200ebb..4ce2f521 100644 --- a/src/views-components/context-menu/context-menu.tsx +++ b/src/views-components/context-menu/context-menu.tsx @@ -75,6 +75,8 @@ export enum ContextMenuKind { VIRTUAL_MACHINE = "VirtualMachine", KEEP_SERVICE = "KeepService", USER = "User", + NODE = "Node", + GROUPS = "Group", + GROUP_MEMBER = "GroupMember", LINK = "Link", - NODE = "Node" } diff --git a/src/views-components/data-explorer/data-explorer.tsx b/src/views-components/data-explorer/data-explorer.tsx index 710d202d..8cddf3ba 100644 --- a/src/views-components/data-explorer/data-explorer.tsx +++ b/src/views-components/data-explorer/data-explorer.tsx @@ -23,7 +23,8 @@ interface Props { const mapStateToProps = (state: RootState, { id }: Props) => { const progress = state.progressIndicator.find(p => p.id === id); const working = progress && progress.working; - return { ...getDataExplorer(state.dataExplorer, id), working }; + const currentRoute = state.router.location ? state.router.location.pathname : ''; + return { ...getDataExplorer(state.dataExplorer, id), working, paperKey: currentRoute }; }; const mapDispatchToProps = () => { diff --git a/src/views-components/dialog-create/dialog-ssh-key-create.tsx b/src/views-components/dialog-create/dialog-ssh-key-create.tsx index b7c9b1fb..aed1cd24 100644 --- a/src/views-components/dialog-create/dialog-ssh-key-create.tsx +++ b/src/views-components/dialog-create/dialog-ssh-key-create.tsx @@ -7,7 +7,7 @@ import { InjectedFormProps } from 'redux-form'; import { WithDialogProps } from '~/store/dialog/with-dialog'; import { FormDialog } from '~/components/form-dialog/form-dialog'; import { SshKeyPublicField, SshKeyNameField } from '~/views-components/form-fields/ssh-key-form-fields'; -import { SshKeyCreateFormDialogData } from '~/store/auth/auth-action'; +import { SshKeyCreateFormDialogData } from '~/store/auth/auth-action-ssh'; type DialogSshKeyProps = WithDialogProps<{}> & InjectedFormProps; diff --git a/src/views-components/dialog-forms/add-group-member-dialog.tsx b/src/views-components/dialog-forms/add-group-member-dialog.tsx new file mode 100644 index 00000000..f4a5c2cf --- /dev/null +++ b/src/views-components/dialog-forms/add-group-member-dialog.tsx @@ -0,0 +1,48 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import * as React from 'react'; +import { compose } from "redux"; +import { reduxForm, InjectedFormProps, WrappedFieldArrayProps, FieldArray } from 'redux-form'; +import { withDialog, WithDialogProps } from "~/store/dialog/with-dialog"; +import { FormDialog } from '~/components/form-dialog/form-dialog'; +import { PeopleSelect, Person } from '~/views-components/sharing-dialog/people-select'; +import { ADD_GROUP_MEMBERS_DIALOG, ADD_GROUP_MEMBERS_FORM, AddGroupMembersFormData, ADD_GROUP_MEMBERS_USERS_FIELD_NAME, addGroupMembers } from '~/store/group-details-panel/group-details-panel-actions'; +import { minLength } from '~/validators/min-length'; + +export const AddGroupMembersDialog = compose( + withDialog(ADD_GROUP_MEMBERS_DIALOG), + reduxForm({ + form: ADD_GROUP_MEMBERS_FORM, + onSubmit: (data, dispatch) => { + dispatch(addGroupMembers(data)); + }, + }) +)( + (props: AddGroupMembersDialogProps) => + +); + +type AddGroupMembersDialogProps = WithDialogProps<{}> & InjectedFormProps; + +const UsersField = () => + ; + +const UsersFieldValidation = [minLength(1, () => 'Select at least one user')]; + +const UsersSelect = ({ fields }: WrappedFieldArrayProps) => + ; diff --git a/src/views-components/dialog-forms/create-group-dialog.tsx b/src/views-components/dialog-forms/create-group-dialog.tsx new file mode 100644 index 00000000..554ad790 --- /dev/null +++ b/src/views-components/dialog-forms/create-group-dialog.tsx @@ -0,0 +1,62 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import * as React from 'react'; +import { compose } from "redux"; +import { reduxForm, InjectedFormProps, Field, WrappedFieldArrayProps, FieldArray } from 'redux-form'; +import { withDialog, WithDialogProps } from "~/store/dialog/with-dialog"; +import { FormDialog } from '~/components/form-dialog/form-dialog'; +import { CREATE_GROUP_DIALOG, CREATE_GROUP_FORM, createGroup, CreateGroupFormData, CREATE_GROUP_NAME_FIELD_NAME, CREATE_GROUP_USERS_FIELD_NAME } from '~/store/groups-panel/groups-panel-actions'; +import { TextField } from '~/components/text-field/text-field'; +import { maxLength } from '~/validators/max-length'; +import { require } from '~/validators/require'; +import { PeopleSelect, Person } from '~/views-components/sharing-dialog/people-select'; + +export const CreateGroupDialog = compose( + withDialog(CREATE_GROUP_DIALOG), + reduxForm({ + form: CREATE_GROUP_FORM, + onSubmit: (data, dispatch) => { + dispatch(createGroup(data)); + } + }) +)( + (props: CreateGroupDialogComponentProps) => + +); + +type CreateGroupDialogComponentProps = WithDialogProps<{}> & InjectedFormProps; + +const CreateGroupFormFields = () => + <> + + + ; + +const GroupNameField = () => + ; + +const GROUP_NAME_VALIDATION = [require, maxLength(255)]; + +const UsersField = () => + ; + +const UsersSelect = ({ fields }: WrappedFieldArrayProps) => + ; diff --git a/src/views-components/dialog-forms/create-ssh-key-dialog.ts b/src/views-components/dialog-forms/create-ssh-key-dialog.ts index e9652433..6472c3ae 100644 --- a/src/views-components/dialog-forms/create-ssh-key-dialog.ts +++ b/src/views-components/dialog-forms/create-ssh-key-dialog.ts @@ -5,7 +5,11 @@ import { compose } from "redux"; import { reduxForm } from 'redux-form'; import { withDialog } from "~/store/dialog/with-dialog"; -import { SSH_KEY_CREATE_FORM_NAME, createSshKey, SshKeyCreateFormDialogData } from '~/store/auth/auth-action'; +import { + SSH_KEY_CREATE_FORM_NAME, + createSshKey, + SshKeyCreateFormDialogData +} from '~/store/auth/auth-action-ssh'; import { DialogSshKeyCreate } from '~/views-components/dialog-create/dialog-ssh-key-create'; export const CreateSshKeyDialog = compose( @@ -16,4 +20,4 @@ export const CreateSshKeyDialog = compose( dispatch(createSshKey(data)); } }) -)(DialogSshKeyCreate); \ No newline at end of file +)(DialogSshKeyCreate); diff --git a/src/views-components/form-fields/search-bar-form-fields.tsx b/src/views-components/form-fields/search-bar-form-fields.tsx index da0b12b5..85abbe19 100644 --- a/src/views-components/form-fields/search-bar-form-fields.tsx +++ b/src/views-components/form-fields/search-bar-form-fields.tsx @@ -3,7 +3,7 @@ // SPDX-License-Identifier: AGPL-3.0 import * as React from "react"; -import { Field, WrappedFieldProps, FieldArray } from 'redux-form'; +import { Field, WrappedFieldProps, FieldArray, formValues } from 'redux-form'; import { TextField, DateTextField } from "~/components/text-field/text-field"; import { CheckboxField } from '~/components/checkbox-field/checkbox-field'; import { NativeSelectField } from '~/components/select-field/select-field'; @@ -14,6 +14,10 @@ import { SEARCH_BAR_ADVANCE_FORM_PICKER_ID } from '~/store/search-bar/search-bar import { SearchBarAdvancedPropertiesView } from '~/views-components/search-bar/search-bar-advanced-properties-view'; import { TreeItem } from "~/components/tree/tree"; import { ProjectsTreePickerItem } from "~/views-components/projects-tree-picker/generic-projects-tree-picker"; +import { PropertyKeyInput } from '~/views-components/resource-properties-form/property-key-field'; +import { PropertyValueInput, PropertyValueFieldProps } from '~/views-components/resource-properties-form/property-value-field'; +import { VocabularyProp, connectVocabulary } from '~/views-components/resource-properties-form/property-field-common'; +import { compose } from 'redux'; export const SearchBarTypeField = () => (_: any, { id }: TreeItem) => { props.input.onChange(id); } - }/> + } />
; export const SearchBarTrashField = () => @@ -74,17 +78,22 @@ export const SearchBarPropertiesField = () => name="properties" component={SearchBarAdvancedPropertiesView} />; -export const SearchBarKeyField = () => - ; +export const SearchBarKeyField = connectVocabulary( + ({ vocabulary }: VocabularyProp) => + ); -export const SearchBarValueField = () => - ; +export const SearchBarValueField = compose( + connectVocabulary, + formValues({ propertyKey: 'key' }) +)( + (props: PropertyValueFieldProps) => + ); export const SearchBarSaveSearchField = () => ((theme: ArvadosTheme) => ({ + rightContainer: { + textAlign: 'right', + paddingRight: theme.spacing.unit * 2, + color: theme.palette.grey["500"] + }, + leftContainer: { + textAlign: 'left', + paddingLeft: theme.spacing.unit * 2 + }, + spacing: { + paddingTop: theme.spacing.unit * 2 + }, +})); + +interface GroupAttributesDataProps { + data: GroupResource; +} + +type GroupAttributesProps = GroupAttributesDataProps & WithStyles; + +export const GroupAttributesDialog = compose( + withDialog(GROUP_ATTRIBUTES_DIALOG), + styles)( + (props: WithDialogProps & GroupAttributesProps) => + + Attributes + + + {props.data && attributes(props.data, props.classes)} + + + + + + + ); + +const attributes = (group: GroupResource, classes: any) => { + const { uuid, ownerUuid, createdAt, modifiedAt, modifiedByClientUuid, modifiedByUserUuid, name, deleteAt, description, etag, href, isTrashed, trashAt} = group; + return ( + + + + {name && Name} + {ownerUuid && Owner uuid} + {createdAt && Created at} + {modifiedAt && Modified at} + {modifiedByUserUuid && Modified by user uuid} + {modifiedByClientUuid && Modified by client uuid} + {uuid && uuid} + {deleteAt && Delete at} + {description && Description} + {etag && Etag} + {href && Href} + {isTrashed && Is trashed} + {trashAt && Trashed at} + + + {name} + {ownerUuid} + {createdAt} + {modifiedAt} + {modifiedByUserUuid} + {modifiedByClientUuid} + {uuid} + {deleteAt} + {description} + {etag} + {href} + {isTrashed} + {trashAt} + + + + ); +}; diff --git a/src/views-components/groups-dialog/member-attributes-dialog.tsx b/src/views-components/groups-dialog/member-attributes-dialog.tsx new file mode 100644 index 00000000..7aa8653d --- /dev/null +++ b/src/views-components/groups-dialog/member-attributes-dialog.tsx @@ -0,0 +1,95 @@ +// 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, Grid } from "@material-ui/core"; +import { WithDialogProps } from "~/store/dialog/with-dialog"; +import { withDialog } from '~/store/dialog/with-dialog'; +import { WithStyles, withStyles } from '@material-ui/core/styles'; +import { ArvadosTheme } from '~/common/custom-theme'; +import { compose } from "redux"; +import { PermissionResource } from "~/models/permission"; +import { MEMBER_ATTRIBUTES_DIALOG } from '~/store/group-details-panel/group-details-panel-actions'; + +type CssRules = 'rightContainer' | 'leftContainer' | 'spacing'; + +const styles = withStyles((theme: ArvadosTheme) => ({ + rightContainer: { + textAlign: 'right', + paddingRight: theme.spacing.unit * 2, + color: theme.palette.grey["500"] + }, + leftContainer: { + textAlign: 'left', + paddingLeft: theme.spacing.unit * 2 + }, + spacing: { + paddingTop: theme.spacing.unit * 2 + }, +})); + +interface GroupAttributesDataProps { + data: PermissionResource; +} + +type GroupAttributesProps = GroupAttributesDataProps & WithStyles; + +export const GroupMemberAttributesDialog = compose( + withDialog(MEMBER_ATTRIBUTES_DIALOG), + styles)( + (props: WithDialogProps & GroupAttributesProps) => + + Attributes + + + {props.data && attributes(props.data, props.classes)} + + + + + + + ); + +const attributes = (memberGroup: PermissionResource, classes: any) => { + const { uuid, ownerUuid, createdAt, modifiedAt, modifiedByClientUuid, modifiedByUserUuid, name, etag, href, linkClass } = memberGroup; + return ( + + + + {name && Name} + {ownerUuid && Owner uuid} + {createdAt && Created at} + {modifiedAt && Modified at} + {modifiedByUserUuid && Modified by user uuid} + {modifiedByClientUuid && Modified by client uuid} + {uuid && uuid} + {linkClass && Link Class} + {etag && Etag} + {href && Href} + + + {name} + {ownerUuid} + {createdAt} + {modifiedAt} + {modifiedByUserUuid} + {modifiedByClientUuid} + {uuid} + {linkClass} + {etag} + {href} + + + + ); +}; diff --git a/src/views-components/groups-dialog/member-remove-dialog.ts b/src/views-components/groups-dialog/member-remove-dialog.ts new file mode 100644 index 00000000..bb5c3a2d --- /dev/null +++ b/src/views-components/groups-dialog/member-remove-dialog.ts @@ -0,0 +1,21 @@ +// 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 { removeGroupMember, MEMBER_REMOVE_DIALOG } from '~/store/group-details-panel/group-details-panel-actions'; + +const mapDispatchToProps = (dispatch: Dispatch, props: WithDialogProps) => ({ + onConfirm: () => { + props.closeDialog(); + dispatch(removeGroupMember(props.data.uuid)); + } +}); + +export const RemoveGroupMemberDialog = compose( + withDialog(MEMBER_REMOVE_DIALOG), + connect(null, mapDispatchToProps) +)(ConfirmationDialog); \ No newline at end of file diff --git a/src/views-components/groups-dialog/remove-dialog.ts b/src/views-components/groups-dialog/remove-dialog.ts new file mode 100644 index 00000000..8220198e --- /dev/null +++ b/src/views-components/groups-dialog/remove-dialog.ts @@ -0,0 +1,21 @@ +// 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 { removeGroup, GROUP_REMOVE_DIALOG } from '~/store/groups-panel/groups-panel-actions'; + +const mapDispatchToProps = (dispatch: Dispatch, props: WithDialogProps) => ({ + onConfirm: () => { + props.closeDialog(); + dispatch(removeGroup(props.data.uuid)); + } +}); + +export const RemoveGroupDialog = compose( + withDialog(GROUP_REMOVE_DIALOG), + connect(null, mapDispatchToProps) +)(ConfirmationDialog); \ No newline at end of file diff --git a/src/views-components/main-app-bar/account-menu.tsx b/src/views-components/main-app-bar/account-menu.tsx index 1609aafa..6c1e46c5 100644 --- a/src/views-components/main-app-bar/account-menu.tsx +++ b/src/views-components/main-app-bar/account-menu.tsx @@ -12,24 +12,31 @@ 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 { navigateToSshKeysUser, navigateToMyAccount } from '~/store/navigation/navigation-action'; +import { + navigateToSiteManager, + navigateToSshKeysUser, + navigateToMyAccount +} from '~/store/navigation/navigation-action'; import { openUserVirtualMachines } from "~/store/virtual-machines/virtual-machines-actions"; interface AccountMenuProps { user?: User; + currentRoute: string; } const mapStateToProps = (state: RootState): AccountMenuProps => ({ - user: state.auth.user + user: state.auth.user, + currentRoute: state.router.location ? state.router.location.pathname : '' }); export const AccountMenu = connect(mapStateToProps)( - ({ user, dispatch }: AccountMenuProps & DispatchProp) => + ({ user, dispatch, currentRoute }: AccountMenuProps & DispatchProp) => user ? } id="account-menu" - title="Account Management"> + title="Account Management" + key={currentRoute}> {getUserFullname(user)} @@ -37,6 +44,7 @@ export const AccountMenu = connect(mapStateToProps)( {!user.isAdmin && dispatch(openRepositoriesPanel())}>Repositories} dispatch(openCurrentTokenDialog)}>Current token dispatch(navigateToSshKeysUser)}>Ssh Keys + dispatch(navigateToSiteManager)}>Site Manager dispatch(navigateToMyAccount)}>My account dispatch(logout())}>Logout diff --git a/src/views-components/main-app-bar/admin-menu.tsx b/src/views-components/main-app-bar/admin-menu.tsx index 88aafbae..9b94c064 100644 --- a/src/views-components/main-app-bar/admin-menu.tsx +++ b/src/views-components/main-app-bar/admin-menu.tsx @@ -17,27 +17,30 @@ import { openUserPanel } from "~/store/users/users-actions"; interface AdminMenuProps { user?: User; + currentRoute: string; } const mapStateToProps = (state: RootState): AdminMenuProps => ({ - user: state.auth.user + user: state.auth.user, + currentRoute: state.router.location ? state.router.location.pathname : '' }); export const AdminMenu = connect(mapStateToProps)( - ({ user, dispatch }: AdminMenuProps & DispatchProp) => + ({ user, dispatch, currentRoute }: AdminMenuProps & DispatchProp) => user ? } id="admin-menu" - title="Admin Panel"> + title="Admin Panel" + key={currentRoute}> dispatch(openRepositoriesPanel())}>Repositories dispatch(openAdminVirtualMachines())}>Virtual Machines dispatch(NavigationAction.navigateToSshKeysAdmin)}>Ssh Keys dispatch(NavigationAction.navigateToApiClientAuthorizations)}>Api Tokens dispatch(openUserPanel())}>Users + dispatch(NavigationAction.navigateToGroups)}>Groups} dispatch(NavigationAction.navigateToComputeNodes)}>Compute Nodes dispatch(NavigationAction.navigateToKeepServices)}>Keep Services dispatch(NavigationAction.navigateToLinks)}>Links - dispatch(logout())}>Logout : null); diff --git a/src/views-components/main-app-bar/help-menu.tsx b/src/views-components/main-app-bar/help-menu.tsx index 26604228..94da69e7 100644 --- a/src/views-components/main-app-bar/help-menu.tsx +++ b/src/views-components/main-app-bar/help-menu.tsx @@ -3,11 +3,14 @@ // SPDX-License-Identifier: AGPL-3.0 import * as React from "react"; -import { MenuItem, Typography, ListSubheader } from "@material-ui/core"; +import { MenuItem, Typography } from "@material-ui/core"; import { DropdownMenu } from "~/components/dropdown-menu/dropdown-menu"; import { ImportContactsIcon, HelpIcon } from "~/components/icon/icon"; import { ArvadosTheme } from '~/common/custom-theme'; import { StyleRulesCallback, WithStyles, withStyles } from '@material-ui/core/styles'; +import { RootState } from "~/store/store"; +import { compose } from "redux"; +import { connect } from "react-redux"; type CssRules = 'link' | 'icon' | 'title' | 'linkTitle'; @@ -52,22 +55,33 @@ const links = [ }, ]; -export const HelpMenu = withStyles(styles)( - ({ classes }: WithStyles) => - } - id="help-menu" - title="Help"> - Help - { - links.map(link => - - - - {link.title} - - - ) - } - -); +interface HelpMenuProps { + currentRoute: string; +} + +const mapStateToProps = ({ router }: RootState) => ({ + currentRoute: router.location ? router.location.pathname : '', +}); + +export const HelpMenu = compose( + connect(mapStateToProps), + withStyles(styles))( + ({ classes, currentRoute }: HelpMenuProps & WithStyles) => + } + id="help-menu" + title="Help" + key={currentRoute}> + Help + { + links.map(link => + + + + {link.title} + + + ) + } + + ); diff --git a/src/views-components/main-content-bar/main-content-bar.tsx b/src/views-components/main-content-bar/main-content-bar.tsx index 3806b524..c0014d00 100644 --- a/src/views-components/main-content-bar/main-content-bar.tsx +++ b/src/views-components/main-content-bar/main-content-bar.tsx @@ -21,6 +21,7 @@ const isButtonVisible = ({ router }: RootState) => { return !Routes.matchWorkflowRoute(pathname) && !Routes.matchUserVirtualMachineRoute(pathname) && !Routes.matchAdminVirtualMachineRoute(pathname) && !Routes.matchRepositoriesRoute(pathname) && !Routes.matchSshKeysAdminRoute(pathname) && !Routes.matchSshKeysUserRoute(pathname) && + !Routes.matchSiteManagerRoute(pathname) && !Routes.matchKeepServicesRoute(pathname) && !Routes.matchComputeNodesRoute(pathname) && !Routes.matchApiClientAuthorizationsRoute(pathname) && !Routes.matchUsersRoute(pathname) && !Routes.matchMyAccountRoute(pathname) && !Routes.matchLinksRoute(pathname); diff --git a/src/views-components/rename-file-dialog/rename-file-dialog.tsx b/src/views-components/rename-file-dialog/rename-file-dialog.tsx index 9e276ade..1a806511 100644 --- a/src/views-components/rename-file-dialog/rename-file-dialog.tsx +++ b/src/views-components/rename-file-dialog/rename-file-dialog.tsx @@ -37,5 +37,5 @@ const RenameDialogFormFields = (props: WithDialogProps) => component={TextField} autoFocus={true} /> - + ; diff --git a/src/views-components/resource-properties-form/property-key-field.tsx b/src/views-components/resource-properties-form/property-key-field.tsx index e6708a39..3fb2d377 100644 --- a/src/views-components/resource-properties-form/property-key-field.tsx +++ b/src/views-components/resource-properties-form/property-key-field.tsx @@ -20,7 +20,7 @@ export const PropertyKeyField = connectVocabulary( vocabulary={vocabulary} validate={getValidation(vocabulary)} />); -const PropertyKeyInput = ({ vocabulary, ...props }: WrappedFieldProps & VocabularyProp) => +export const PropertyKeyInput = ({ vocabulary, ...props }: WrappedFieldProps & VocabularyProp) => ); -const PropertyValueInput = ({ vocabulary, propertyKey, ...props }: WrappedFieldProps & PropertyValueFieldProps) => +export const PropertyValueInput = ({ vocabulary, propertyKey, ...props }: WrappedFieldProps & PropertyValueFieldProps) => }; export const SearchBarView = withStyles(styles)( - (props : SearchBarViewProps) => { - const { classes, isPopoverOpen } = props; - return ( - - -
- handleInputClick(e, props)} - onKeyDown={e => handleKeyDown(e, props)} - startAdornment={ - - - - - - - - } - endAdornment={ - - - handleDropdownClick(e, props)}> - - - - - } /> -
-
- {isPopoverOpen && getView({...props})} + class SearchBarView extends React.Component { + + viewAnchorRef = React.createRef(); + + render() { + const { children, ...props } = this.props; + const { classes, isPopoverOpen } = props; + return ( + +
+
+ +
+ + { + getView({ ...props }) + } +
- - ); + ); + } + + getViewWidth() { + const { current } = this.viewAnchorRef; + return current ? current.offsetWidth : 0; + } } + ); +const SearchInput = (props: SearchBarViewProps) => { + const { classes } = props; + return handleInputClick(e, props)} + onKeyDown={e => handleKeyDown(e, props)} + startAdornment={ + + + + + + + + } + endAdornment={ + + + handleDropdownClick(e, props)}> + + + + + } />; +}; + +const SearchViewContainer = (props: SearchBarViewProps & { width: number, anchorEl: HTMLElement | null, children: React.ReactNode }) => + + { + props.children + } + ; + + const getView = (props: SearchBarViewProps) => { switch (props.currentView) { case SearchView.AUTOCOMPLETE: diff --git a/src/views-components/sharing-dialog/people-select.tsx b/src/views-components/sharing-dialog/people-select.tsx index 2aada00e..f62e6f55 100644 --- a/src/views-components/sharing-dialog/people-select.tsx +++ b/src/views-components/sharing-dialog/people-select.tsx @@ -17,9 +17,12 @@ export interface Person { email: string; uuid: string; } + export interface PeopleSelectProps { items: Person[]; + label?: string; + autofocus?: boolean; onBlur?: (event: React.FocusEvent) => void; onFocus?: (event: React.FocusEvent) => void; @@ -43,12 +46,16 @@ export const PeopleSelect = connect()( }; render() { + + const { label = 'Invite people' } = this.props; + return ( ({ } }); -const mapStateToProps = (state: RootState) => ({ +const mapStateToProps = ({ router }: RootState) => ({ + currentRoute: router.location ? router.location.pathname : '', }); export const SidePanel = withStyles(styles)( connect(mapStateToProps, mapDispatchToProps)( - ({ classes, ...props }: WithStyles & SidePanelTreeProps) => - - - - -)); + ({ classes, ...props }: WithStyles & SidePanelTreeProps & { currentRoute: string }) => + + + + + )); diff --git a/src/views-components/ssh-keys-dialog/attributes-dialog.tsx b/src/views-components/ssh-keys-dialog/attributes-dialog.tsx index ce896dcc..0c164dbd 100644 --- a/src/views-components/ssh-keys-dialog/attributes-dialog.tsx +++ b/src/views-components/ssh-keys-dialog/attributes-dialog.tsx @@ -4,9 +4,9 @@ import * as React from "react"; import { compose } from 'redux'; -import { withStyles, Dialog, DialogTitle, DialogContent, DialogActions, Button, StyleRulesCallback, WithStyles, Typography, Grid } from '@material-ui/core'; +import { withStyles, Dialog, DialogTitle, DialogContent, DialogActions, Button, StyleRulesCallback, WithStyles, Grid } from '@material-ui/core'; import { WithDialogProps, withDialog } from "~/store/dialog/with-dialog"; -import { SSH_KEY_ATTRIBUTES_DIALOG } from '~/store/auth/auth-action'; +import { SSH_KEY_ATTRIBUTES_DIALOG } from '~/store/auth/auth-action-ssh'; import { ArvadosTheme } from '~/common/custom-theme'; import { SshKeyResource } from "~/models/ssh-key"; @@ -66,4 +66,4 @@ export const AttributesSshKeyDialog = compose( - ); \ No newline at end of file + ); diff --git a/src/views-components/ssh-keys-dialog/public-key-dialog.tsx b/src/views-components/ssh-keys-dialog/public-key-dialog.tsx index 77c6cfde..11ec1595 100644 --- a/src/views-components/ssh-keys-dialog/public-key-dialog.tsx +++ b/src/views-components/ssh-keys-dialog/public-key-dialog.tsx @@ -6,7 +6,7 @@ import * as React from "react"; import { compose } from 'redux'; import { withStyles, Dialog, DialogTitle, DialogContent, DialogActions, Button, StyleRulesCallback, WithStyles } from '@material-ui/core'; import { WithDialogProps, withDialog } from "~/store/dialog/with-dialog"; -import { SSH_KEY_PUBLIC_KEY_DIALOG } from '~/store/auth/auth-action'; +import { SSH_KEY_PUBLIC_KEY_DIALOG } from '~/store/auth/auth-action-ssh'; import { ArvadosTheme } from '~/common/custom-theme'; import { DefaultCodeSnippet } from '~/components/default-code-snippet/default-code-snippet'; @@ -52,4 +52,4 @@ export const PublicKeyDialog = compose( - ); \ No newline at end of file + ); diff --git a/src/views-components/ssh-keys-dialog/remove-dialog.tsx b/src/views-components/ssh-keys-dialog/remove-dialog.tsx index 8077f21b..916e918c 100644 --- a/src/views-components/ssh-keys-dialog/remove-dialog.tsx +++ b/src/views-components/ssh-keys-dialog/remove-dialog.tsx @@ -5,7 +5,7 @@ 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 { SSH_KEY_REMOVE_DIALOG, removeSshKey } from '~/store/auth/auth-action'; +import { SSH_KEY_REMOVE_DIALOG, removeSshKey } from '~/store/auth/auth-action-ssh'; const mapDispatchToProps = (dispatch: Dispatch, props: WithDialogProps) => ({ onConfirm: () => { @@ -17,4 +17,4 @@ const mapDispatchToProps = (dispatch: Dispatch, props: WithDialogProps) => export const RemoveSshKeyDialog = compose( withDialog(SSH_KEY_REMOVE_DIALOG), connect(null, mapDispatchToProps) -)(ConfirmationDialog); \ No newline at end of file +)(ConfirmationDialog); diff --git a/src/views/group-details-panel/group-details-panel.tsx b/src/views/group-details-panel/group-details-panel.tsx new file mode 100644 index 00000000..f81c2404 --- /dev/null +++ b/src/views/group-details-panel/group-details-panel.tsx @@ -0,0 +1,126 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import * as React from 'react'; +import { connect } from 'react-redux'; + +import { DataExplorer } from "~/views-components/data-explorer/data-explorer"; +import { DataColumns } from '~/components/data-table/data-table'; +import { ResourceUuid, ResourceFirstName, ResourceLastName, ResourceEmail, ResourceUsername } from '~/views-components/data-explorer/renderers'; +import { createTree } from '~/models/tree'; +import { noop } from 'lodash/fp'; +import { RootState } from '~/store/store'; +import { GROUP_DETAILS_PANEL_ID, openAddGroupMembersDialog } from '~/store/group-details-panel/group-details-panel-actions'; +import { openContextMenu } from '~/store/context-menu/context-menu-actions'; +import { ResourcesState, getResource } from '~/store/resources/resources'; +import { ContextMenuKind } from '~/views-components/context-menu/context-menu'; +import { PermissionResource } from '~/models/permission'; +import { Grid, Button } from '@material-ui/core'; +import { AddIcon } from '~/components/icon/icon'; + +export enum GroupDetailsPanelColumnNames { + FIRST_NAME = "First name", + LAST_NAME = "Last name", + UUID = "UUID", + EMAIL = "Email", + USERNAME = "Username", +} + +export const groupDetailsPanelColumns: DataColumns = [ + { + name: GroupDetailsPanelColumnNames.FIRST_NAME, + selected: true, + configurable: true, + filters: createTree(), + render: uuid => + }, + { + name: GroupDetailsPanelColumnNames.LAST_NAME, + selected: true, + configurable: true, + filters: createTree(), + render: uuid => + }, + { + name: GroupDetailsPanelColumnNames.UUID, + selected: true, + configurable: true, + filters: createTree(), + render: uuid => + }, + { + name: GroupDetailsPanelColumnNames.EMAIL, + selected: true, + configurable: true, + filters: createTree(), + render: uuid => + }, + { + name: GroupDetailsPanelColumnNames.USERNAME, + selected: true, + configurable: true, + filters: createTree(), + render: uuid => + }, +]; + +const mapStateToProps = (state: RootState) => { + return { + resources: state.resources + }; +}; + +const mapDispatchToProps = { + onContextMenu: openContextMenu, + onAddUser: openAddGroupMembersDialog, +}; + +export interface GroupDetailsPanelProps { + onContextMenu: (event: React.MouseEvent, item: any) => void; + onAddUser: () => void; + resources: ResourcesState; +} + +export const GroupDetailsPanel = connect( + mapStateToProps, mapDispatchToProps +)( + class GroupDetailsPanel extends React.Component { + + render() { + return ( + + + + } /> + ); + } + + handleContextMenu = (event: React.MouseEvent, resourceUuid: string) => { + const resource = getResource(resourceUuid)(this.props.resources); + if (resource) { + this.props.onContextMenu(event, { + name: '', + uuid: resource.uuid, + ownerUuid: resource.ownerUuid, + kind: resource.kind, + menuKind: ContextMenuKind.GROUP_MEMBER + }); + } + } + }); + diff --git a/src/views/groups-panel/groups-panel.tsx b/src/views/groups-panel/groups-panel.tsx new file mode 100644 index 00000000..f50a344b --- /dev/null +++ b/src/views/groups-panel/groups-panel.tsx @@ -0,0 +1,133 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import * as React from 'react'; +import { connect } from 'react-redux'; +import { Grid, Button, Typography } from "@material-ui/core"; +import { DataExplorer } from "~/views-components/data-explorer/data-explorer"; +import { DataColumns } from '~/components/data-table/data-table'; +import { SortDirection } from '~/components/data-table/data-column'; +import { ResourceOwner } from '~/views-components/data-explorer/renderers'; +import { AddIcon } from '~/components/icon/icon'; +import { ResourceName } from '~/views-components/data-explorer/renderers'; +import { createTree } from '~/models/tree'; +import { GROUPS_PANEL_ID, openCreateGroupDialog } from '~/store/groups-panel/groups-panel-actions'; +import { noop } from 'lodash/fp'; +import { ContextMenuKind } from '~/views-components/context-menu/context-menu'; +import { getResource, ResourcesState, filterResources } from '~/store/resources/resources'; +import { GroupResource } from '~/models/group'; +import { RootState } from '~/store/store'; +import { openContextMenu } from '~/store/context-menu/context-menu-actions'; +import { ResourceKind } from '~/models/resource'; +import { LinkClass, LinkResource } from '~/models/link'; +import { navigateToGroupDetails } from '~/store/navigation/navigation-action'; + +export enum GroupsPanelColumnNames { + GROUP = "Name", + OWNER = "Owner", + MEMBERS = "Members", +} + +export const groupsPanelColumns: DataColumns = [ + { + name: GroupsPanelColumnNames.GROUP, + selected: true, + configurable: true, + sortDirection: SortDirection.ASC, + filters: createTree(), + render: uuid => + }, + { + name: GroupsPanelColumnNames.OWNER, + selected: true, + configurable: true, + filters: createTree(), + render: uuid => , + }, + { + name: GroupsPanelColumnNames.MEMBERS, + selected: true, + configurable: true, + filters: createTree(), + render: uuid => , + }, +]; + +const mapStateToProps = (state: RootState) => { + return { + resources: state.resources + }; +}; + +const mapDispatchToProps = { + onContextMenu: openContextMenu, + onRowDoubleClick: (uuid: string) => + navigateToGroupDetails(uuid), + onNewGroup: openCreateGroupDialog, +}; + +export interface GroupsPanelProps { + onNewGroup: () => void; + onContextMenu: (event: React.MouseEvent, item: any) => void; + onRowDoubleClick: (item: string) => void; + resources: ResourcesState; +} + +export const GroupsPanel = connect( + mapStateToProps, mapDispatchToProps +)( + class GroupsPanel extends React.Component { + + render() { + return ( + + + + } /> + ); + } + + handleContextMenu = (event: React.MouseEvent, resourceUuid: string) => { + const resource = getResource(resourceUuid)(this.props.resources); + if (resource) { + this.props.onContextMenu(event, { + name: '', + uuid: resource.uuid, + ownerUuid: resource.ownerUuid, + kind: resource.kind, + menuKind: ContextMenuKind.GROUPS + }); + } + } + }); + + +const GroupMembersCount = connect( + (state: RootState, props: { uuid: string }) => { + + const permissions = filterResources((resource: LinkResource) => + resource.kind === ResourceKind.LINK && + resource.linkClass === LinkClass.PERMISSION && + resource.tailUuid === props.uuid + )(state.resources); + + return { + children: permissions.length, + }; + + } +)(Typography); diff --git a/src/views/site-manager-panel/site-manager-panel-root.tsx b/src/views/site-manager-panel/site-manager-panel-root.tsx new file mode 100644 index 00000000..2b6d3c97 --- /dev/null +++ b/src/views/site-manager-panel/site-manager-panel-root.tsx @@ -0,0 +1,183 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: AGPL-3.0 + +import * as React from 'react'; +import { + Card, + CardContent, + CircularProgress, + Grid, + StyleRulesCallback, + Table, + TableBody, + TableCell, + TableHead, + TableRow, + Typography, + WithStyles, + withStyles +} from '@material-ui/core'; +import { ArvadosTheme } from '~/common/custom-theme'; +import { Session, SessionStatus } from "~/models/session"; +import Button from "@material-ui/core/Button"; +import { compose, Dispatch } from "redux"; +import { Field, FormErrors, InjectedFormProps, reduxForm, reset, stopSubmit } from "redux-form"; +import { TextField } from "~/components/text-field/text-field"; +import { addSession } from "~/store/auth/auth-action-session"; +import { SITE_MANAGER_REMOTE_HOST_VALIDATION } from "~/validators/validators"; + +type CssRules = 'root' | 'link' | 'buttonContainer' | 'table' | 'tableRow' | + 'remoteSiteInfo' | 'buttonAdd' | 'buttonLoggedIn' | 'buttonLoggedOut' | + 'statusCell'; + +const styles: StyleRulesCallback = (theme: ArvadosTheme) => ({ + root: { + width: '100%', + overflow: 'auto' + }, + link: { + color: theme.palette.primary.main, + textDecoration: 'none', + margin: '0px 4px' + }, + buttonContainer: { + textAlign: 'right' + }, + table: { + marginTop: theme.spacing.unit + }, + tableRow: { + '& td, th': { + whiteSpace: 'nowrap' + } + }, + statusCell: { + minWidth: 160 + }, + remoteSiteInfo: { + marginTop: 20 + }, + buttonAdd: { + marginLeft: 10, + marginTop: theme.spacing.unit * 3 + }, + buttonLoggedIn: { + minHeight: theme.spacing.unit, + padding: 5, + color: '#fff', + backgroundColor: '#009966', + '&:hover': { + backgroundColor: '#008450', + } + }, + buttonLoggedOut: { + minHeight: theme.spacing.unit, + padding: 5, + color: '#000', + backgroundColor: '#FFC414', + '&:hover': { + backgroundColor: '#eaaf14', + } + } +}); + +export interface SiteManagerPanelRootActionProps { + toggleSession: (session: Session) => void; +} + +export interface SiteManagerPanelRootDataProps { + sessions: Session[]; +} + +type SiteManagerPanelRootProps = SiteManagerPanelRootDataProps & SiteManagerPanelRootActionProps & WithStyles & InjectedFormProps; +const SITE_MANAGER_FORM_NAME = 'siteManagerForm'; + +const submitSession = (remoteHost: string) => + (dispatch: Dispatch) => { + dispatch(addSession(remoteHost)).then(() => { + dispatch(reset(SITE_MANAGER_FORM_NAME)); + }).catch((e: any) => { + const errors = { + remoteHost: e + } as FormErrors; + dispatch(stopSubmit(SITE_MANAGER_FORM_NAME, errors)); + }); + }; + +export const SiteManagerPanelRoot = compose( + reduxForm<{remoteHost: string}>({ + form: SITE_MANAGER_FORM_NAME, + touchOnBlur: false, + onSubmit: (data, dispatch) => { + dispatch(submitSession(data.remoteHost)); + } + }), + withStyles(styles)) + (({ classes, sessions, handleSubmit, toggleSession }: SiteManagerPanelRootProps) => + + + + + + You can log in to multiple Arvados sites here, then use the multi-site search page to search collections and projects on all sites at once. + + + + + {sessions.length > 0 && + + + Cluster ID + Username + Email + Status + + + + {sessions.map((session, index) => { + const validating = session.status === SessionStatus.BEING_VALIDATED; + return + {session.clusterId} + {validating ? : session.username} + {validating ? : session.email} + + + + ; + })} + +
} +
+
+ + + + To add a remote Arvados site, paste the remote site's host here (see "ARVADOS_API_HOST" on the "current token" page). + + + + + + + + + +
+
+
+ ); diff --git a/src/views/site-manager-panel/site-manager-panel.tsx b/src/views/site-manager-panel/site-manager-panel.tsx new file mode 100644 index 00000000..4532e856 --- /dev/null +++ b/src/views/site-manager-panel/site-manager-panel.tsx @@ -0,0 +1,27 @@ +// 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 { + SiteManagerPanelRoot, SiteManagerPanelRootActionProps, + SiteManagerPanelRootDataProps +} from "~/views/site-manager-panel/site-manager-panel-root"; +import { Session } from "~/models/session"; +import { toggleSession } from "~/store/auth/auth-action-session"; + +const mapStateToProps = (state: RootState): SiteManagerPanelRootDataProps => { + return { + sessions: state.auth.sessions + }; +}; + +const mapDispatchToProps = (dispatch: Dispatch): SiteManagerPanelRootActionProps => ({ + toggleSession: (session: Session) => { + dispatch(toggleSession(session)); + } +}); + +export const SiteManagerPanel = connect(mapStateToProps, mapDispatchToProps)(SiteManagerPanelRoot); diff --git a/src/views/ssh-key-panel/ssh-key-panel.tsx b/src/views/ssh-key-panel/ssh-key-panel.tsx index 4e800296..6575a9cc 100644 --- a/src/views/ssh-key-panel/ssh-key-panel.tsx +++ b/src/views/ssh-key-panel/ssh-key-panel.tsx @@ -5,7 +5,7 @@ import { RootState } from '~/store/store'; import { Dispatch } from 'redux'; import { connect } from 'react-redux'; -import { openSshKeyCreateDialog, openPublicKeyDialog } from '~/store/auth/auth-action'; +import { openSshKeyCreateDialog, openPublicKeyDialog } from '~/store/auth/auth-action-ssh'; import { openSshKeyContextMenu } from '~/store/context-menu/context-menu-actions'; import { SshKeyPanelRoot, SshKeyPanelRootDataProps, SshKeyPanelRootActionProps } from '~/views/ssh-key-panel/ssh-key-panel-root'; @@ -28,4 +28,4 @@ const mapDispatchToProps = (dispatch: Dispatch): SshKeyPanelRootActionProps => ( } }); -export const SshKeyPanel = connect(mapStateToProps, mapDispatchToProps)(SshKeyPanelRoot); \ No newline at end of file +export const SshKeyPanel = connect(mapStateToProps, mapDispatchToProps)(SshKeyPanelRoot); diff --git a/src/views/workbench/workbench.tsx b/src/views/workbench/workbench.tsx index 025540e2..90b2dad0 100644 --- a/src/views/workbench/workbench.tsx +++ b/src/views/workbench/workbench.tsx @@ -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 { SiteManagerPanel } from "~/views/site-manager-panel/site-manager-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'; @@ -79,6 +80,14 @@ import { UserPanel } from '~/views/user-panel/user-panel'; import { UserAttributesDialog } from '~/views-components/user-dialog/attributes-dialog'; import { CreateUserDialog } from '~/views-components/dialog-forms/create-user-dialog'; import { HelpApiClientAuthorizationDialog } from '~/views-components/api-client-authorizations-dialog/help-dialog'; +import { GroupsPanel } from '~/views/groups-panel/groups-panel'; +import { CreateGroupDialog } from '~/views-components/dialog-forms/create-group-dialog'; +import { RemoveGroupDialog } from '~/views-components/groups-dialog/remove-dialog'; +import { GroupAttributesDialog } from '~/views-components/groups-dialog/attributes-dialog'; +import { GroupDetailsPanel } from '~/views/group-details-panel/group-details-panel'; +import { RemoveGroupMemberDialog } from '~/views-components/groups-dialog/member-remove-dialog'; +import { GroupMemberAttributesDialog } from '~/views-components/groups-dialog/member-attributes-dialog'; +import { AddGroupMembersDialog } from '~/views-components/dialog-forms/add-group-member-dialog'; type CssRules = 'root' | 'container' | 'splitter' | 'asidePanel' | 'contentWrapper' | 'content'; @@ -153,11 +162,14 @@ export const WorkbenchPanel = + + + @@ -167,6 +179,7 @@ export const WorkbenchPanel = + @@ -178,6 +191,7 @@ export const WorkbenchPanel = + @@ -185,6 +199,8 @@ export const WorkbenchPanel = + + @@ -197,6 +213,8 @@ export const WorkbenchPanel = + + @@ -215,4 +233,4 @@ export const WorkbenchPanel = - ); \ No newline at end of file + ); diff --git a/yarn.lock b/yarn.lock index d3d6396d..b642d71a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -130,6 +130,11 @@ csstype "^2.0.0" indefinite-observable "^1.0.1" +"@types/jssha@0.0.29": + version "0.0.29" + resolved "https://registry.yarnpkg.com/@types/jssha/-/jssha-0.0.29.tgz#95e83dba98787ff796d2d5f37a1925abf41bc9cb" + integrity sha1-leg9uph4f/eW0tXzehklq/Qbycs= + "@types/lodash@4.14.116": version "4.14.116" resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.116.tgz#5ccf215653e3e8c786a58390751033a9adca0eb9" @@ -5540,6 +5545,11 @@ jss@^9.3.3: symbol-observable "^1.1.0" warning "^3.0.0" +jssha@2.3.1: + version "2.3.1" + resolved "https://registry.yarnpkg.com/jssha/-/jssha-2.3.1.tgz#147b2125369035ca4b2f7d210dc539f009b3de9a" + integrity sha1-FHshJTaQNcpLL30hDcU58Amz3po= + keycode@^2.1.9: version "2.2.0" resolved "https://registry.yarnpkg.com/keycode/-/keycode-2.2.0.tgz#3d0af56dc7b8b8e5cba8d0a97f107204eec22b04"