b3d64dbca00f87f9469a5542b7f67cd61371c7f9
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / UserRolesController.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  *
37  */
38 package org.onap.portalapp.portal.controller;
39
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Collections;
43 import java.util.Comparator;
44 import java.util.List;
45 import javax.servlet.http.HttpServletRequest;
46 import javax.servlet.http.HttpServletResponse;
47 import org.apache.cxf.transport.http.HTTPException;
48 import org.onap.portalapp.controller.EPRestrictedBaseController;
49 import org.onap.portalapp.portal.domain.EPRole;
50 import org.onap.portalapp.portal.domain.EPUser;
51 import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles;
52 import org.onap.portalapp.portal.domain.EcompAuditLog;
53 import org.onap.portalapp.portal.domain.ExternalSystemAccess;
54 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
55 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
56 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
57 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
58 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
59 import org.onap.portalapp.portal.service.AdminRolesService;
60 import org.onap.portalapp.portal.service.ApplicationsRestClientService;
61 import org.onap.portalapp.portal.service.SearchService;
62 import org.onap.portalapp.portal.service.UserRolesService;
63 import org.onap.portalapp.portal.transport.AppNameIdIsAdmin;
64 import org.onap.portalapp.portal.transport.AppWithRolesForUser;
65 import org.onap.portalapp.portal.transport.AppsListWithAdminRole;
66 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
67 import org.onap.portalapp.portal.transport.FieldsValidator;
68 import org.onap.portalapp.portal.transport.RoleInAppForUser;
69 import org.onap.portalapp.portal.transport.UserApplicationRoles;
70 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
71 import org.onap.portalapp.portal.utils.EcompPortalUtils;
72 import org.onap.portalapp.portal.utils.PortalConstants;
73 import org.onap.portalapp.util.EPUserUtils;
74 import org.onap.portalsdk.core.domain.AuditLog;
75 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
76 import org.onap.portalsdk.core.restful.domain.EcompRole;
77 import org.onap.portalsdk.core.service.AuditService;
78 import org.onap.portalsdk.core.service.DataAccessService;
79 import org.onap.portalsdk.core.util.SystemProperties;
80 import org.slf4j.MDC;
81 import org.springframework.beans.factory.annotation.Autowired;
82 import org.springframework.context.annotation.EnableAspectJAutoProxy;
83 import org.springframework.web.bind.annotation.PathVariable;
84 import org.springframework.web.bind.annotation.RequestBody;
85 import org.springframework.web.bind.annotation.RequestMapping;
86 import org.springframework.web.bind.annotation.RequestMethod;
87 import org.springframework.web.bind.annotation.RequestParam;
88 import org.springframework.web.bind.annotation.RestController;
89
90 @RestController
91 @org.springframework.context.annotation.Configuration
92 @EnableAspectJAutoProxy
93 @EPAuditLog
94 public class UserRolesController extends EPRestrictedBaseController {
95
96     private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class);
97
98     @Autowired
99     private SearchService searchService;
100     @Autowired
101     private AdminRolesService adminRolesService;
102     private @Autowired UserRolesService userRolesService;
103     @Autowired
104     private ApplicationsRestClientService applicationsRestClientService;
105     @Autowired
106     private AuditService auditService;
107     @Autowired
108         private DataAccessService dataAccessService;
109
110     private static final String FAILURE = "failure";
111
112     /**
113      * RESTful service method to fetch users in the WebPhone external service
114      *
115      * @param request HttpServletRequest
116      * @param searchString search string
117      * @param response HttpServletResponse
118      * @return array of found users as json
119      */
120     @RequestMapping(value = { "/portalApi/queryUsers" }, method = RequestMethod.GET, produces = "application/json")
121     public String getPhoneBookSearchResult(HttpServletRequest request, @RequestParam("search") String searchString,
122             HttpServletResponse response) {
123         EPUser user = EPUserUtils.getUserSession(request);
124         String searchResult = null;
125         if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)
126                 && !adminRolesService.isRoleAdmin(user)) {
127             EcompPortalUtils.setBadPermissions(user, response, "getPhoneBookSearchResult");
128         } else {
129             searchString = searchString.trim();
130             if (searchString.length() > 2) {
131                 searchResult = searchService.searchUsersInPhoneBook(searchString);
132             } else {
133                 logger.info(EELFLoggerDelegate.errorLogger,
134                         "getPhoneBookSearchResult - too short search string: " + searchString);
135             }
136         }
137         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/queryUsers", "result =", searchResult);
138
139         return searchResult;
140     }
141
142     /**
143      * RESTful service method to fetch applications where user is admin
144      *
145      * @param request HttpServletRequest
146      * @param orgUserId search string
147      * @param response HttpServletResponse
148      * @return for GET: array of all applications with boolean isAdmin=true/false for each application
149      */
150     @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = {
151             RequestMethod.GET }, produces = "application/json")
152     public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(HttpServletRequest request,
153             @RequestParam("user") String orgUserId, HttpServletResponse response) {
154
155         EPUser user = EPUserUtils.getUserSession(request);
156         AppsListWithAdminRole result = null;
157         if (!adminRolesService.isSuperAdmin(user)) {
158             EcompPortalUtils.setBadPermissions(user, response, "getAppsWithAdminRoleStateForUser");
159         } else {
160             if (EcompPortalUtils.legitimateUserId(orgUserId)) {
161                 result = adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId);
162             } else {
163                 logger.info(EELFLoggerDelegate.errorLogger,
164                         "getAppsWithAdminRoleStateForUser - parms error, no Organization User ID");
165                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
166             }
167         }
168
169         StringBuilder adminAppRoles = new StringBuilder();
170         if (result != null) {
171             if (!result.appsRoles.isEmpty()) {
172                 adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {");
173                 for (AppNameIdIsAdmin adminAppRole : result.appsRoles) {
174                     if (adminAppRole.isAdmin) {
175                         adminAppRoles.append(adminAppRole.appName + ", ");
176                     }
177                 }
178                 adminAppRoles.append("}.");
179             } else {
180                 adminAppRoles.append("User '" + result.orgUserId + "' has no Apps with Admin Role.");
181             }
182         } else {
183             logger.error(EELFLoggerDelegate.errorLogger,
184                     "putAppWithUserRoleStateForUser: getAppsWithAdminRoleStateForUser result is null");
185         }
186
187         logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString());
188
189         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "get result =", result);
190
191         return result;
192     }
193
194     /**
195      *
196      * @param request HttpServletRequest
197      * @param newAppsListWithAdminRoles new apps
198      * @param response HttpServletResponse
199      * @return FieldsValidator
200      */
201     @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = {
202             RequestMethod.PUT }, produces = "application/json")
203     public FieldsValidator putAppsWithAdminRoleStateForUser(HttpServletRequest request,
204             @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles, HttpServletResponse response) {
205
206         // newAppsListWithAdminRoles.appsRoles
207         FieldsValidator fieldsValidator = new FieldsValidator();
208         StringBuilder newAppRoles = new StringBuilder();
209         if (newAppsListWithAdminRoles != null) {
210             if (!newAppsListWithAdminRoles.appsRoles.isEmpty()) {
211                 newAppRoles
212                         .append("User '" + newAppsListWithAdminRoles.orgUserId + "' has admin role to the apps = { ");
213                 for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) {
214                     if (adminAppRole.isAdmin) {
215                         newAppRoles.append(adminAppRole.appName + " ,");
216                     }
217                 }
218                 newAppRoles.deleteCharAt(newAppRoles.length() - 1);
219                 newAppRoles.append("}.");
220             } else {
221                 newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has no Apps with Admin Role.");
222             }
223         } else {
224             logger.error(EELFLoggerDelegate.errorLogger,
225                     "putAppWithUserRoleStateForUser: putAppsWithAdminRoleStateForUser result is null");
226             fieldsValidator.httpStatusCode = (long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
227         }
228
229         logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString());
230
231         EPUser user = EPUserUtils.getUserSession(request);
232         boolean changesApplied = false;
233
234         if (!adminRolesService.isSuperAdmin(user)) {
235             EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser");
236         } else {
237             changesApplied = adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles);
238             AuditLog auditLog = new AuditLog();
239             auditLog.setUserId(user.getId());
240             auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN);
241             if (newAppsListWithAdminRoles != null) {
242                 auditLog.setAffectedRecordId(newAppsListWithAdminRoles.orgUserId);
243             }
244             auditLog.setComments(
245                     EcompPortalUtils.truncateString(newAppRoles.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE));
246             auditService.logActivity(auditLog, null);
247
248             MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
249             MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
250             EcompPortalUtils.calculateDateTimeDifferenceForLog(
251                     MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
252                     MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
253             if (newAppsListWithAdminRoles != null) {
254                 logger.info(EELFLoggerDelegate.auditLogger,
255                         EPLogUtil.formatAuditLogMessage("UserRolesController.putAppsWithAdminRoleStateForUser",
256                                 EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(),
257                                 newAppsListWithAdminRoles.orgUserId, newAppRoles.toString()));
258             }
259             MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
260             MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
261             MDC.remove(SystemProperties.MDC_TIMER);
262         }
263         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "put result =", changesApplied);
264
265         return fieldsValidator;
266     }
267
268     /**
269      * It returns a list of user app roles for single app
270      *
271      * @param request HttpServletRequest
272      * @param response HttpServletResponse
273      * @param orgUserId user ID
274      * @param appid application ID
275      * @param extRequestValue set to false if request is from users page otherwise true
276      * @return List<RoleInAppForUser>
277      */
278     @RequestMapping(value = { "/portalApi/userAppRoles" }, method = {
279             RequestMethod.GET }, produces = "application/json")
280     public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("user") String orgUserId,
281             @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue,
282             @RequestParam("isSystemUser") Boolean isSystemUser,
283             HttpServletResponse response) {
284         EPUser user = EPUserUtils.getUserSession(request);
285         List<RoleInAppForUser> result = null;
286         String feErrorString = "";
287         if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)) {
288             logger.debug(EELFLoggerDelegate.debugLogger,
289                     "getAppRolesForUser: Accountadminpermissioncheck {}, RoleAdmincheck {}",
290                     adminRolesService.isAccountAdmin(user), adminRolesService.isRoleAdmin(user));
291             EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser");
292             feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus());
293         } else {
294                 try {
295                         if(orgUserId!=null) {
296                                 EPUser localUser  = getUserInfo(orgUserId,applicationsRestClientService);
297                                 if(localUser !=null) {
298                                         if(localUser.isSystemUser()) {
299                                                 isSystemUser = true;
300                                         }
301                                 }
302                         }
303                         } catch (Exception e) {
304                                 logger.error(EELFLoggerDelegate.errorLogger, "isSystemUser update failed", e);
305                         }
306             if ((!isSystemUser && EcompPortalUtils.legitimateUserId(orgUserId)) || isSystemUser) {
307                 result = userRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue, user);
308                 logger.debug(EELFLoggerDelegate.debugLogger, "getAppRolesForUser: result {}, appId {}", result, appid);
309                 int responseCode = EcompPortalUtils.getExternalAppResponseCode();
310                 if (responseCode != 0 && responseCode != 200) {
311                     // external error
312                     response.setStatus(responseCode);
313                     feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode);
314                 } else if (result == null) {
315                     // If the result is null, there was an internal onap error
316                     // in the service call.
317                     response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
318                     feErrorString = EcompPortalUtils.getFEErrorString(true,
319                             HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
320                 }
321             } else {
322                 logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no Organization User ID");
323                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
324                 feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST);
325             }
326         }
327
328         StringBuilder sbUserApps = new StringBuilder();
329         if (result != null && !result.isEmpty()) {
330             sbUserApps.append("User '" + orgUserId + "' has Roles={");
331             for (RoleInAppForUser appRole : result) {
332                 if (appRole.isApplied) {
333                     sbUserApps.append(appRole.roleName + ", ");
334                 }
335             }
336             sbUserApps.append("} assigned to the appId '" + appid + "'.");
337         } else {
338             // Not sure creating an empty object will make any difference
339             // but would like to give it a shot for defect #DE221057
340             if (result == null) {
341                 result = new ArrayList<>();
342             }
343             sbUserApps.append("User '" + orgUserId + "' and appid " + appid + " has no roles");
344         }
345         logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
346
347         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "get result =", result);
348         if (feErrorString != "") {
349             logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: " + feErrorString);
350
351             response.addHeader("FEErrorString", feErrorString);
352             response.addHeader("Access-Control-Expose-Headers", "FEErrorString");
353         }
354         return result;
355     }
356
357     @RequestMapping(value = { "/portalApi/userAppRoles" }, method = {
358             RequestMethod.PUT }, produces = "application/json")
359     public PortalRestResponse<String> putAppWithUserRoleStateForUser(HttpServletRequest request,
360             @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
361         // FieldsValidator fieldsValidator = new FieldsValidator();
362         PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
363         StringBuilder sbUserApps = new StringBuilder();
364         if (newAppRolesForUser != null) {
365             sbUserApps.append("User '" + newAppRolesForUser.getOrgUserId());
366             if (newAppRolesForUser.getAppId() != null && !newAppRolesForUser.getAppRoles().isEmpty()) {
367                 sbUserApps.append("' has roles = { ");
368                 for (RoleInAppForUser appRole : newAppRolesForUser.getAppRoles()) {
369                     if (appRole.isApplied) {
370                         sbUserApps.append(appRole.roleName + " ,");
371                     }
372                 }
373                 sbUserApps.deleteCharAt(sbUserApps.length() - 1);
374                 sbUserApps.append("} assigned for the app " + newAppRolesForUser.getAppId());
375             } else {
376                 sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.getAppId());
377             }
378         }
379         logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", sbUserApps.toString());
380
381         EPUser user = EPUserUtils.getUserSession(request);
382         // boolean changesApplied = false;
383         ExternalRequestFieldsValidator changesApplied = null;
384
385         if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)) {
386             EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser");
387         } else if (newAppRolesForUser == null) {
388             logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleStateForUser: newAppRolesForUser is null");
389         } else {
390             changesApplied = userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser);
391             try {
392                 if (changesApplied.isResult()) {
393                     logger.info(EELFLoggerDelegate.applicationLogger,
394                             "putAppWithUserRoleStateForUser: succeeded for app {}, user {}",
395                             newAppRolesForUser.getAppId(),
396                             newAppRolesForUser.getAppId());
397
398                     MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
399                             EPEELFLoggerAdvice.getCurrentDateTimeUTC());
400                     AuditLog auditLog = new AuditLog();
401                     auditLog.setUserId(user.getId());
402                     auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER);
403                     auditLog.setAffectedRecordId(newAppRolesForUser.getOrgUserId());
404                     auditLog.setComments(EcompPortalUtils.truncateString(sbUserApps.toString(),
405                             PortalConstants.AUDIT_LOG_COMMENT_SIZE));
406                     auditService.logActivity(auditLog, null);
407
408                     MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
409                             EPEELFLoggerAdvice.getCurrentDateTimeUTC());
410                     EcompPortalUtils.calculateDateTimeDifferenceForLog(
411                             MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
412                             MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
413                     logger.info(EELFLoggerDelegate.auditLogger,
414                             EPLogUtil.formatAuditLogMessage("UserRolesController.putAppWithUserRoleStateForUser",
415                                     EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(),
416                                     newAppRolesForUser.getOrgUserId(), sbUserApps.toString()));
417                     MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
418                     MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
419                     MDC.remove(SystemProperties.MDC_TIMER);
420                     portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null);
421
422                 }
423                 if (!changesApplied.isResult())
424                     throw new Exception(changesApplied.getDetailMessage());
425
426             } catch (Exception e) {
427                 logger.error(EELFLoggerDelegate.errorLogger,
428                         "putAppWithUserRoleStateForUser: failed for app {}, user {}", newAppRolesForUser.getAppId(),
429                         newAppRolesForUser.getOrgUserId(), e);
430                 portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), null);
431             }
432         }
433
434         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied);
435         return portalResponse;
436     }
437
438     @RequestMapping(value = { "/portalApi/updateRemoteUserProfile" }, method = {
439             RequestMethod.GET }, produces = "application/json")
440     public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request,
441             HttpServletResponse response) {
442
443         String updateRemoteUserFlag = FAILURE;
444         try {
445             // saveNewUser = userService.saveNewUser(newUser);
446             String orgUserId = request.getParameter("loginId");
447             Long appId = Long.parseLong(request.getParameter("appId"));
448             userRolesService.updateRemoteUserProfile(orgUserId, appId);
449
450         } catch (Exception e) {
451             logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
452             return new PortalRestResponse<>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage());
453         }
454         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, "");
455
456     }
457
458     @RequestMapping(value = { "/portalApi/app/{appId}/users" }, method = {
459             RequestMethod.GET }, produces = "application/json")
460     public List<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request,
461             @PathVariable("appId") Long appId) throws HTTPException {
462         try {
463             logger.debug(EELFLoggerDelegate.debugLogger, "/portalApi/app/{}/users was invoked", appId);
464             return userRolesService.getUsersFromAppEndpoint(appId);
465         } catch (Exception e) {
466             logger.error(EELFLoggerDelegate.errorLogger, "getUsersFromAppEndpoint failed", e);
467             return new ArrayList<>();
468         }
469     }
470
471     @RequestMapping(value = { "/portalApi/app/{appId}/roles" }, method = {
472             RequestMethod.GET }, produces = "application/json")
473     public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId)
474             throws HTTPException {
475         EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
476         List<EcompRole> rolesList = Arrays.asList(appRoles);
477         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId,
478                 rolesList);
479
480         return rolesList;
481     }
482
483     @RequestMapping(value = { "/portalApi/admin/import/app/{appId}/roles" }, method = {
484             RequestMethod.GET }, produces = "application/json")
485     public List<EPRole> importRolesFromRemoteApplication(HttpServletRequest request, @PathVariable("appId") Long appId)
486             throws HTTPException {
487         List<EPRole> rolesList = userRolesService.importRolesFromRemoteApplication(appId);
488         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles",
489                 "response for appId=" + appId, rolesList);
490
491         return rolesList;
492     }
493
494     @RequestMapping(value = { "/portalApi/app/{appId}/user/{orgUserId}/roles" }, method = {
495             RequestMethod.GET }, produces = "application/json")
496     public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId,
497             @PathVariable("orgUserId") String orgUserId) throws Exception {
498         if (!EcompPortalUtils.legitimateUserId(orgUserId)) {
499             String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId;
500             logger.error(EELFLoggerDelegate.errorLogger, msg);
501             throw new Exception(msg);
502         }
503         EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId,
504                 String.format("/user/%s/roles", orgUserId));
505         if (roles.length != 1) {
506             String msg = "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length;
507             logger.error(EELFLoggerDelegate.errorLogger, msg);
508             throw new Exception(msg);
509         }
510
511         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles",
512                 "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]);
513         return roles[0];
514     }
515
516     @RequestMapping(value = { "/portalApi/saveUserAppRoles" }, method = {
517             RequestMethod.PUT }, produces = "application/json")
518     public FieldsValidator putAppWithUserRoleRequest(HttpServletRequest request,
519             @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
520         FieldsValidator fieldsValidator = null;
521         try {
522
523             EPUser user = EPUserUtils.getUserSession(request);
524             fieldsValidator = userRolesService.putUserAppRolesRequest(newAppRolesForUser, user);
525             response.setStatus(fieldsValidator.httpStatusCode.intValue());
526
527         } catch (Exception e) {
528             logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleRequest failed", e);
529
530         }
531         // return fieldsValidator;
532         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/saveUserAppRoles", "PUT result =",
533                 response.getStatus());
534         return fieldsValidator;
535     }
536
537     @RequestMapping(value = { "/portalApi/appCatalogRoles" }, method = {
538             RequestMethod.GET }, produces = "application/json")
539     public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(HttpServletRequest request,
540             @RequestParam("appName") String appName) {
541         EPUser user = EPUserUtils.getUserSession(request);
542         List<EPUserAppCatalogRoles> userAppRoleList = null;
543         try {
544             userAppRoleList = userRolesService.getUserAppCatalogRoles(user, appName);
545         } catch (Exception e) {
546             logger.error(EELFLoggerDelegate.errorLogger, "putUserWidgetsSortPref failed", e);
547
548         }
549         Collections.sort(userAppRoleList, getUserAppCatalogRolesComparator);
550         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", userAppRoleList);
551
552         return userAppRoleList;
553
554     }
555
556     private Comparator<EPUserAppCatalogRoles> getUserAppCatalogRolesComparator =
557             new Comparator<EPUserAppCatalogRoles>() {
558                 public int compare(EPUserAppCatalogRoles o1, EPUserAppCatalogRoles o2) {
559                     return o1.getRolename().compareTo(o2.getRolename());
560                 }
561             };
562
563     @RequestMapping(value = "/portalApi/externalRequestAccessSystem", method = RequestMethod.GET,
564             produces = "application/json")
565     public ExternalSystemAccess readExternalRequestAccess(HttpServletRequest request) {
566         ExternalSystemAccess result = null;
567         try {
568             result = userRolesService.getExternalRequestAccess();
569             EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =",
570                     result);
571         } catch (Exception e) {
572             logger.error(EELFLoggerDelegate.errorLogger, "readExternalRequestAccess failed: " + e.getMessage());
573         }
574         return result;
575     }
576
577     @RequestMapping(value = { "/portalApi/checkIfUserIsSuperAdmin" }, method = RequestMethod.GET,
578             produces = "application/json")
579     public boolean checkIfUserIsSuperAdmin(HttpServletRequest request,
580             HttpServletResponse response) {
581         EPUser user = EPUserUtils.getUserSession(request);
582         boolean isSuperAdmin = false;
583         try {
584             isSuperAdmin = adminRolesService.isSuperAdmin(user);
585         } catch (Exception e) {
586             logger.error(EELFLoggerDelegate.errorLogger, "checkIfUserIsSuperAdmin failed: " + e.getMessage());
587         }
588         return isSuperAdmin;
589     }
590     
591     /**
592          * 
593          * @param userId
594          * @param app
595          * @param applicationsRestClientService
596          * @return EPUser
597          * @throws HTTPException
598          */
599         protected EPUser getUserInfo(String userId, ApplicationsRestClientService applicationsRestClientService)
600                         throws HTTPException {
601                 @SuppressWarnings("unchecked")
602                 List<EPUser> userList = (List<EPUser>) dataAccessService
603                                 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
604                 if (userList != null && !userList.isEmpty())
605                         return userList.get(0);
606                 else
607                         return null;
608         }
609 }