"use strict"; /** * Licensed Materials - Property of IBM * IBM Cognos Products: admin * Copyright IBM Corp. 2015, 2020 * US Government Users Restricted Rights - * Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. */ define(['underscore', 'bi/commons/ui/core/Class', 'bi/admin/nls/StringResource', 'bi/admin/common/utils/AJAXUtils', 'ba-react-admin/ba-react-admin.min'], function (_, Class, StringResource, AJAXUtils, AdminReact) { 'use strict'; //NOSONAR: meant to be strict var AccountExplorer = Class.extend({ _searchTypes: { 0: 'contains', 1: 'startsExact', 2: 'matchExact' }, _pathStack: [], _nameSpaces: [], _content: [], _accountTypes: { 'namespaceFolder': { svgIcon: 'common-folder', titleId: 'namespaceFolder' }, 'group': { svgIcon: 'common-group', titleId: 'group' }, 'account': { svgIcon: 'common-user', titleId: 'account' }, 'role': { svgIcon: 'common-role', titleId: 'role' } }, _rootDirectory: { type: 'directory', defaultName: StringResource.get('namespaces'), url: '#' }, _defaultTypes: ['namespaceFolder', 'group'], _defaultNamespaceName: null, _selectedNamespace: null, init: function init(options) { AccountExplorer.inherited('init', this, arguments); this.glassContext = options.glassContext; this.logger = this.glassContext.services.logger; this.sortColumnName = 'defaultName'; this.sortOrder = 'asc'; this.isHandlingMorePage = false; this.searchPageFrom = 0; this.searchPageSize = 100; this.searchOffset = 0; this._filterType = { 'account': true, 'role': true, 'group': true }; var options = { method: 'GET', contentType: 'application/json; charset=utf-8', dataType: 'json', url: 'v1/configuration/keys?keys=Admin.mtCloudBuild' }; this._getTenantNsFolderId(); }, getAccount: function getAccount(objectInfo) { var options = { dataType: 'json', type: 'GET', data: { 'fields': 'email,surname,givenName,userName,format,options,contentLocale,productLocale,timeZoneID,searchPath,tenantID,ancestors,permissions,disabled,defaultName,defaultDescription,creationTime,modificationTime,owner.defaultName' }, url: objectInfo._meta.links.self.url, cache: false }; return this.glassContext.services.ajax.ajax(options); }, getItem: function getItem(objectInfo) { var options = { dataType: 'json', type: 'GET', data: { 'fields': 'searchPath,tenantID,ancestors,permissions,disabled,defaultName,defaultDescription,creationTime,modificationTime,owner.defaultName,owner.id,hidden' }, url: objectInfo._meta.links.self.url, cache: false }; return this.glassContext.services.ajax.ajax(options); }, _getChildren: function _getChildren(objType, id, queryString) { var contentURL = 'v1/' + objType + '/' + id + '/items?'; this.currentRequest = contentURL; var options = { dataType: 'json', type: 'GET', data: { 'fields': 'searchPath,tenantID,ancestors,permissions,disabled,defaultName,creationTime,modificationTime,id,hasChildren,hidden' }, url: contentURL + queryString, cache: false }; if (id === 'xOg__' && !this.tenantNsFolderId) { this._getTenantNsFolderId(); } if (!this.pagingEnabled) { //return this.glassContext.services.ajax.ajax(options); return this.glassContext.getCoreSvc('.Ajax').ajax(options); } else { return AdminReact.PaginationHelper.getDataWithLookAhead(0, this.pagingValueSet, this, this.glassContext); } }, _getTenantNsFolderId: function _getTenantNsFolderId() { var upsUrl = 'v1/users/~/user_profile_settings'; var upsSettingsPromise = this.glassContext.services.fetch.get(upsUrl); return upsSettingsPromise.then(function (response) { this.tenantNsFolderId = response.data.rootFolder_CognosNamespace; }.bind(this)).catch(function (e) { this.tenantNsFolderId = null; }.bind(this)); }, getFolderPermission: function getFolderPermission(folderId) { var folderUrl = 'v1/folders/' + folderId; var folderPromise = this.glassContext.services.fetch.get(folderUrl); return folderPromise.then(function (response) { return response.data.permissions; }); }, _getCurrentIdentity: function _getCurrentIdentity() { var identityURL = 'v1/identity'; var options = { dataType: 'json', type: 'GET', data: {}, url: identityURL, cache: false }; return this.glassContext.services.ajax.ajax(options); }, _getNameSpaces: function _getNameSpaces() { var namespaceURL = 'v1/namespaces'; var options = { dataType: 'json', type: 'GET', data: {}, url: namespaceURL, cache: false }; return this.glassContext.services.ajax.ajax(options); }, startUp: function startUp() { return this._getNameSpaces().then(function (response) { var items = _.map(response.data, function (item) { var ct = item.creationTime || StringResource.get('unknown'); ct = ct.split('T')[0]; var mt = item.modificationTime || ""; mt = mt.split('T')[0]; item.creationTime = ct; item.modificationTime = mt; item.owner = StringResource.get('none'); item.description = item.description || item.defaultName; item.svgIcon = 'common-namespace'; item.auth = this._isActiveNS(item); return item; }.bind(this)); this._nameSpaces = items; return this.selectNamespace(); }.bind(this)); }, _isActiveNS: function _isActiveNS(objData) { return _.contains(objData.permissions, 'traverse'); }, _hasMultipleNamespaces: function _hasMultipleNamespaces() { return true; }, _pushStack: function _pushStack(item, ancestor) { var index = _.indexOf(this._pathStack, item); if (index >= 0) { this._pathStack = _.first(this._pathStack, index + 1); } else { if (item.ancestors) { if (ancestor && ancestor.defaultName && ancestor.ancestors) { this._buildPathStack(ancestor); } else { this._pathStack.push(item); } } else if (item.type === 'namespace') { this._pathStack.push(item); } else { this._pathStack = [item]; } } this._patchLink(item); }, _buildPathStack: function _buildPathStack(ancestor) { this._pathStack = []; _.each(ancestor.ancestors, function (member) { if (member.type === 'directory') { member.defaultName = StringResource.get('namespaces'); } this._pathStack.push(member); }.bind(this)); if (ancestor.type === 'directory') { ancestor.defaultName = StringResource.get('namespaces'); } this._pathStack.push(ancestor); }, _patchLink: function _patchLink(item) { if (item.label && item.url) { return; } item.label = item.label || item.defaultName; var objType = ''; if (item.type === 'namespace') { objType = 'namespaces'; } else if (item.type === 'namespaceFolder') { objType = 'folders'; } item.url = 'v1/' + objType + '/' + item.id; }, selectRootDirectory: function selectRootDirectory() { this._pushStack(this._rootDirectory); this._selectedNamespace = null; return Promise.resolve(); }, updateHasMoreData: function updateHasMoreData() { this.noMoreData = this._fullContent.length <= this._content.length; }, selectNamespace: function selectNamespace(ns) { this._content = []; this.clearGroupedContent(); this._pathStack = []; this.searchOffset = 0; if (this._hasMultipleNamespaces()) { this._pushStack(this._rootDirectory); } ns = ns || this._defaultNamespaceName; this._selectedNamespace = this._getNamespaceObj(ns); if (this._canTraverseNamespace()) { var nsId = this._selectedNamespace.id; return new Promise(function (resolve, reject) { this._getChildren('namespaces', nsId, this.getQueryString()).then(function (result) { this._fullContent = result.data.data; this._fullContent.parentId = nsId; if (!this.pagingEnabled) { this._content = result.data.data.slice(0, this.searchPageSize); if (this._content.length <= this._fullContent.length) { this.noMoreData = true; } else { this.noMoreData = false; } } ; var parentNamespace; if (nsId === 'xOg__') { parentNamespace = this.tenantNsFolderId; } else { parentNamespace = nsId; } this.getFolderPermission(parentNamespace).then(function (tenantNsFolderPermissions) { this.parentObjectPermissions = tenantNsFolderPermissions; }.bind(this)).catch(function (e) { this.parentObjectPermissions = null; }.bind(this)); this._pushStack(this._selectedNamespace); resolve(); }.bind(this)).catch(function (e) { reject(e); }.bind(this)); }.bind(this)); } else { this._fullContent = []; return Promise.resolve(); } }, _canTraverseNamespace: function _canTraverseNamespace() { return this._selectedNamespace && this._selectedNamespace.permissions.indexOf('traverse') > -1; }, _getNamespaceObj: function _getNamespaceObj(ns) { if (_.isString(ns)) { return _.find(this._nameSpaces, function (item) { return item.defaultName === ns; }); } else { return ns; } }, selectGroup: function selectGroup(group) { this._content = []; this.clearGroupedContent(); if (group.permissions) { this.parentObjectPermissions = group.permissions; } return new Promise(function (resolve, reject) { this._getChildren('groups', group.id, this.getQueryString()).then(function (result) { this._fullContent = result.data.data; this._fullContent.parentId = group.id; if (!this.pagingEnabled) { this._content = result.data.data.slice(0, this.searchPageSize); } else { this._content = result.data.data.slice(0, this.pagingValueSet); } if (result.data.length > 0) { this._pushStack(result.data[0], group); } else { this._pushStack(group); } resolve(); }.bind(this)).catch(function (e) { reject(e); }.bind(this)); }.bind(this)); }, selectRole: function selectRole(role) { this._content = []; this.clearGroupedContent(); if (role.permissions) { this.parentObjectPermissions = role.permissions; } return new Promise(function (resolve, reject) { this._getChildren('roles', role.id, this.getQueryString()).then(function (result) { this._fullContent = result.data.data; this._fullContent.parentId = role.id; if (!this.pagingEnabled) { this._content = result.data.data.slice(0, this.searchPageSize); } else { this._content = result.data.data.slice(0, this.pagingValueSet); } if (result.data.length > 0) { this._pushStack(result.data[0], role); } else { this._pushStack(role); } resolve(); }.bind(this)).catch(function (e) { reject(e); }.bind(this)); }.bind(this)); }, selectFolder: function selectFolder(folder) { this._content = []; this.clearGroupedContent(); if (folder.permissions) { this.parentObjectPermissions = folder.permissions; } return new Promise(function (resolve, reject) { this._getChildren('folders', folder.id, this.getQueryString()).then(function (result) { this._fullContent = result.data.data; this._fullContent.parentId = folder.id; if (!this.pagingEnabled) { this._content = result.data.data.slice(0, this.searchPageSize); } else { this._content = result.data.data.slice(0, this.pagingValueSet); } if (result.data.length > 0) { this._pushStack(result.data[0], folder); } else { this._pushStack(folder); } resolve(); }.bind(this)).catch(function (e) { reject(e); }.bind(this)); }.bind(this)); }, selectCurrentPath: function selectCurrentPath() { return this.selectPath(this.getCurrentPath()); }, selectPath: function selectPath(item) { //NOSONAR switch (item.type) { case 'directory': return this.selectRootDirectory(); case 'namespace': return this.selectNamespace(item.defaultName || 'Cognos'); case 'namespaceFolder': return this.selectFolder(item); case 'role': return this.selectRole(item); case 'group': return this.selectGroup(item); default: this.glassContext.services.logger.error("unknown object type for selection:", item); } return Promise.resolve(); }, isTopOfPage: function isTopOfPage() { return this.searchOffset === 0; }, getNextBrowsePage: function getNextBrowsePage(isPageDown) { if (isPageDown) { this.searchOffset += this.searchPageSize; this._content = this._fullContent.slice(Math.max(0, this.searchOffset - 3), this.searchOffset + this.searchPageSize); } else { this.searchOffset -= this.searchPageSize; if (this.searchOffset < 0) { this.searchOffset = 0; } this._content = this._fullContent.slice(this.searchOffset, this.searchOffset + this.searchPageSize); } if (this.searchOffset + this.searchPageSize >= this._fullContent.length) { this.noMoreData = true; } else { this.noMoreData = false; } }, getNextSearchPage: function getNextSearchPage(isPageDown) { var hasAllTheData = isPageDown ? this.isHandlingMorePage : this.isTopOfPage(); if (!this.isHandlingMorePage && !hasAllTheData && !_.isUndefined(this.lastSearchedKeyword)) { this.isHandlingMorePage = true; this.searchOffset = isPageDown ? this.searchPageSize + this.searchOffset : this.searchOffset - this.searchPageSize; return this.search(this.lastSearchedKeyword).then(function (data) { this.isHandlingMorePage = false; return data; }.bind(this)); } else { return Promise.resolve(); } }, newSearch: function newSearch() { this.searchOffset = 0; this.lastSearchedKeyword = null; }, search: function search(searchWord, searchMethod) { var method = this._searchTypes[searchMethod]; var text = decodeURI(searchWord); var hasMixed1 = text.indexOf('"') !== -1 && (text.indexOf("'") !== -1 || text.indexOf("`") !== -1); var hasMixed2 = text.indexOf("'") !== -1 && (text.indexOf('"') !== -1 || text.indexOf("`") !== -1); var hasMixed3 = text.indexOf("`") !== -1 && (text.indexOf('"') !== -1 || text.indexOf("'") !== -1); if (hasMixed1 || hasMixed2 || hasMixed3) { //don't bother searching for names with mixed quotest. It can't exist in cm if (this.searchOffset === 0) { this._content = []; } else { this._content = this.oldContent; this.searchOffset -= this.searchPageSize; } this.noMoreData = true; return Promise.resolve(); } return new Promise(function (resolve, reject) { var keyword = searchWord.replace(/^\s+|\s+$/g, ''); this.lastSearchedKeyword = keyword; var contextstoreid = _.last(this.getPathStack()).id; if (contextstoreid === 'xOg__' && this.tenantNsFolderId && this.tenantNsFolderId !== 'xOg__') { contextstoreid = this.tenantNsFolderId; } this.clearGroupedContent(); var sortChar = (this.sortOrder || 'asc') === 'asc' ? '%2b' : '-'; var options = { method: 'GET', contentType: 'application/json; charset=utf-8', dataType: 'json' }; options.url = AJAXUtils.getAJAXURL("namespace") + "/" + contextstoreid + '/search?types=' + this._getTypeString() + "&method=" + method + '&fields=id,position,userName,searchPath,tenantID,ancestors,permissions,disabled,defaultName,creationTime,modificationTime,objectClass,hasChildren&filter=' + keyword; options.url += "&sort=" + sortChar + this.sortColumnName; this.currentRequest = options.url; //searchPageSize + 1 because we wanted the rest call to return 1 more entry than what is required //for the page so we can know if there was more entries overall options.url += "&limit=" + (this.searchPageSize + 1); options.url += "&offset=" + this.searchOffset; options.success = function (data) { this._content = data.data; //searchPageSize + 1 because we wanted the rest call to return 1 more entry than what is required //for the page so we can know if there was more entries overall this.noMoreData = data.data.length !== this.searchPageSize + 1; if (!this.noMoreData) { data.data.pop(); } resolve(data); }.bind(this); options.error = function (jqXHR, textStatus, errorThrown) { if (jqXHR.status === 404) { if (this.searchOffset === 0) { this._content = []; } else { this._content = this.oldContent; this.searchOffset -= this.searchPageSize; } this.noMoreData = true; resolve(); } else { reject(jqXHR, textStatus, errorThrown); } }.bind(this); this.glassContext.services.ajax.ajax(options); }.bind(this)); }, _getTypeString: function _getTypeString() { var typeString = "namespace,namespaceFolder"; typeString = typeString.concat(this._filterType.account ? ',account' : '', this._filterType.role ? ',role' : '', this._filterType.group ? ',group' : ''); return typeString; }, cacheOldContent: function cacheOldContent() { this.oldContent = this._content; }, clearGroupedContent: function clearGroupedContent() { this._groupedContent = null; }, getContent: function getContent(types) { var items = []; if (!_.isEmpty(this._content)) { types = types || this._defaultTypes; items = _.filter(this._content, function (item) { return _.contains(types, item.type); }); items = _.map(items, function (item) { return this._patchItem(item); }.bind(this)); } return items; }, _patchItem: function _patchItem(item) { var at = this._accountTypes[item.type]; if (item.type === 'account' && item.givenName && item.surname) { item.defaultName = item.givenName + ' ' + item.surname; } item.title = item.defaultName; item.svgIcon = at.svgIcon || 'common-folder'; item.toolTip = item.defaultName; item.disabled = !!item.disabled; return item; }, getGroupedContent: function getGroupedContent() { if (!this._groupedContent) { this._groupedContent = {}; if (!_.isEmpty(this.getContent())) { var items = _.map(this.getContent(), function (item) { return this._patchItem(item); }.bind(this)); this._groupedContent = _.groupBy(items, function (item) { return item.type; }); } _.each(this._accountTypes, function (value, key) { this._groupedContent[key] = this._groupedContent[key] || []; }.bind(this)); } return this._groupedContent; }, getNamespaces: function getNamespaces() { var namespacesArray = _.sortBy(this._nameSpaces, this.sortColumnName || 'defaultName'); return (this.sortOrder || 'asc') === 'asc' ? namespacesArray : namespacesArray.reverse(); }, setPathStack: function setPathStack(newStack) { this._pathStack = newStack; }, getPathStack: function getPathStack() { return this._pathStack; }, getCurrentNamespace: function getCurrentNamespace() { return this._selectedNamespace; }, isBuiltinNamespace: function isBuiltinNamespace() { return this._selectedNamespace && this._selectedNamespace.defaultName === 'Cognos'; }, isCognosUsersNamespace: function isCognosUsersNamespace() { return this._selectedNamespace && this._selectedNamespace.defaultName === 'Cognos Users'; }, isOidcNamespace: function isOidcNamespace() { var ns = this.getCurrentNamespace(); if (ns) { if (_.contains(ns.capabilities, 'notBrowsable')) { return true; } } return false; }, getCurrentPath: function getCurrentPath() { return _.last(this._pathStack); }, getAccountType: function getAccountType(name) { return this._accountTypes[name]; }, getQueryString: function getQueryString() { var pageSize = 0; if (this.pagingEnabled) { pageSize = this.pagingValueSet; } var columnName = this.sortColumnName || 'defaultName'; var order = this.sortOrder || 'asc'; return 'page=0|' + pageSize + '&sorting=' + columnName + '|' + order; } }); return AccountExplorer; });