pushing error and audit log changes for portal
[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.format.EPAppMessagesEnum;
59 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
60 import org.onap.portalapp.portal.service.AdminRolesService;
61 import org.onap.portalapp.portal.service.ApplicationsRestClientService;
62 import org.onap.portalapp.portal.service.SearchService;
63 import org.onap.portalapp.portal.service.UserRolesService;
64 import org.onap.portalapp.portal.transport.AppNameIdIsAdmin;
65 import org.onap.portalapp.portal.transport.AppWithRolesForUser;
66 import org.onap.portalapp.portal.transport.AppsListWithAdminRole;
67 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
68 import org.onap.portalapp.portal.transport.FieldsValidator;
69 import org.onap.portalapp.portal.transport.RoleInAppForUser;
70 import org.onap.portalapp.portal.transport.UserApplicationRoles;
71 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
72 import org.onap.portalapp.portal.utils.EcompPortalUtils;
73 import org.onap.portalapp.portal.utils.PortalConstants;
74 import org.onap.portalapp.util.EPUserUtils;
75 import org.onap.portalsdk.core.domain.AuditLog;
76 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
77 import org.onap.portalsdk.core.restful.domain.EcompRole;
78 import org.onap.portalsdk.core.service.AuditService;
79 import org.onap.portalsdk.core.service.DataAccessService;
80 import org.onap.portalsdk.core.util.SystemProperties;
81 import org.slf4j.MDC;
82 import org.springframework.beans.factory.annotation.Autowired;
83 import org.springframework.context.annotation.EnableAspectJAutoProxy;
84 import org.springframework.web.bind.annotation.PathVariable;
85 import org.springframework.web.bind.annotation.RequestBody;
86 import org.springframework.web.bind.annotation.GetMapping;
87 import org.springframework.web.bind.annotation.PutMapping;
88 import org.springframework.web.bind.annotation.RequestParam;
89 import org.springframework.web.bind.annotation.RestController;
90
91 @RestController
92 @org.springframework.context.annotation.Configuration
93 @EnableAspectJAutoProxy
94 @EPAuditLog
95 public class UserRolesController extends EPRestrictedBaseController {
96
97     private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class);
98
99     @Autowired
100     private SearchService searchService;
101     @Autowired
102     private AdminRolesService adminRolesService;
103     private @Autowired UserRolesService userRolesService;
104     @Autowired
105     private ApplicationsRestClientService applicationsRestClientService;
106     @Autowired
107     private AuditService auditService;
108     @Autowired
109         private DataAccessService dataAccessService;
110
111     private static final String FAILURE = "failure";
112
113     /**
114      * RESTful service method to fetch users in the WebPhone external service
115      *
116      * @param request HttpServletRequest
117      * @param searchString search string
118      * @param response HttpServletResponse
119      * @return array of found users as json
120      */
121     @GetMapping(value = { "/portalApi/queryUsers" }, produces = "application/json")
122     public String getPhoneBookSearchResult(HttpServletRequest request, @RequestParam("search") String searchString,
123             HttpServletResponse response) {
124         EPUser user = EPUserUtils.getUserSession(request);
125         String searchResult = null;
126         if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)
127                 && !adminRolesService.isRoleAdmin(user)) {
128             EcompPortalUtils.setBadPermissions(user, response, "getPhoneBookSearchResult");
129         } else {
130             searchString = searchString.trim();
131             if (searchString.length() > 2) {
132                 searchResult = searchService.searchUsersInPhoneBook(searchString);
133             } else {
134                 logger.info(EELFLoggerDelegate.errorLogger,
135                         "getPhoneBookSearchResult - too short search string: " + searchString);
136             }
137         }
138         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/queryUsers", "result =", searchResult);
139
140         return searchResult;
141     }
142
143     /**
144      * RESTful service method to fetch applications where user is admin
145      *
146      * @param request HttpServletRequest
147      * @param orgUserId search string
148      * @param response HttpServletResponse
149      * @return for GET: array of all applications with boolean isAdmin=true/false for each application
150      */
151     @GetMapping(value = { "/portalApi/adminAppsRoles" }, 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     @PutMapping(value = { "/portalApi/adminAppsRoles" }, produces = "application/json")
202     public FieldsValidator putAppsWithAdminRoleStateForUser(HttpServletRequest request,
203             @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles, HttpServletResponse response) {
204
205         // newAppsListWithAdminRoles.appsRoles
206         FieldsValidator fieldsValidator = new FieldsValidator();
207         StringBuilder newAppRoles = new StringBuilder();
208         if (newAppsListWithAdminRoles != null) {
209             if (!newAppsListWithAdminRoles.appsRoles.isEmpty()) {
210                 newAppRoles
211                         .append("User '" + newAppsListWithAdminRoles.orgUserId + "' has admin role to the apps = { ");
212                 for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) {
213                     if (adminAppRole.isAdmin) {
214                         newAppRoles.append(adminAppRole.appName + " ,");
215                     }
216                 }
217                 newAppRoles.deleteCharAt(newAppRoles.length() - 1);
218                 newAppRoles.append("}.");
219             } else {
220                 newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has no Apps with Admin Role.");
221             }
222         } else {
223             logger.error(EELFLoggerDelegate.errorLogger,
224                     "putAppWithUserRoleStateForUser: putAppsWithAdminRoleStateForUser result is null");
225             fieldsValidator.httpStatusCode = (long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
226         }
227
228         logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString());
229
230         EPUser user = EPUserUtils.getUserSession(request);
231         boolean changesApplied = false;
232
233         if (!adminRolesService.isSuperAdmin(user)) {
234             EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser");
235         } else {
236             changesApplied = adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles);
237             AuditLog auditLog = new AuditLog();
238             auditLog.setUserId(user.getId());
239             auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN);
240             if (newAppsListWithAdminRoles != null) {
241                 auditLog.setAffectedRecordId(newAppsListWithAdminRoles.orgUserId);
242             }
243             auditLog.setComments(
244                     EcompPortalUtils.truncateString(newAppRoles.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE));
245             auditService.logActivity(auditLog, null);
246                         String auditMessageInfo = EPLogUtil.formatAuditLogMessage("UserRolesController.putAppsWithAdminRoleStateForUser",
247                     EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(),
248                     newAppsListWithAdminRoles.orgUserId, newAppRoles.toString());               
249
250                         EPLogUtil.logAuditMessage(logger, auditMessageInfo);
251             
252         }
253         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "put result =", changesApplied);
254
255         return fieldsValidator;
256     }
257
258     /**
259      * It returns a list of user app roles for single app
260      *
261      * @param request HttpServletRequest
262      * @param response HttpServletResponse
263      * @param orgUserId user ID
264      * @param appid application ID
265      * @param extRequestValue set to false if request is from users page otherwise true
266      * @return List<RoleInAppForUser>
267      */
268     @GetMapping(value = { "/portalApi/userAppRoles" }, produces = "application/json")
269     public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("user") String orgUserId,
270             @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue,
271             @RequestParam("isSystemUser") Boolean isSystemUser,
272             HttpServletResponse response) {
273         EPUser user = EPUserUtils.getUserSession(request);
274         List<RoleInAppForUser> result = null;
275         String feErrorString = "";
276         if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)) {
277             logger.debug(EELFLoggerDelegate.debugLogger,
278                     "getAppRolesForUser: Accountadminpermissioncheck {}, RoleAdmincheck {}",
279                     adminRolesService.isAccountAdmin(user), adminRolesService.isRoleAdmin(user));
280             EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser");
281             feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus());
282         } else {
283                 try {
284                         if(orgUserId!=null) {
285                                 EPUser localUser  = getUserInfo(orgUserId,applicationsRestClientService);
286                                 if(localUser !=null) {
287                                         if(localUser.isSystemUser()) {
288                                                 isSystemUser = true;
289                                         }
290                                 }
291                         }
292                         } catch (Exception e) {
293                                 logger.error(EELFLoggerDelegate.errorLogger, "isSystemUser update failed", e);
294                         }
295             if ((!isSystemUser && EcompPortalUtils.legitimateUserId(orgUserId)) || isSystemUser) {
296                 result = userRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue, user);
297                 logger.debug(EELFLoggerDelegate.debugLogger, "getAppRolesForUser: result {}, appId {}", result, appid);
298                 int responseCode = EcompPortalUtils.getExternalAppResponseCode();
299                 if (responseCode != 0 && responseCode != 200) {
300                     // external error
301                     response.setStatus(responseCode);
302                     feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode);
303                 } else if (result == null) {
304                     // If the result is null, there was an internal onap error
305                     // in the service call.
306                     response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
307                     feErrorString = EcompPortalUtils.getFEErrorString(true,
308                             HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
309                 }
310             } else {
311                 logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no Organization User ID");
312                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
313                 feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST);
314             }
315         }
316
317         StringBuilder sbUserApps = new StringBuilder();
318         if (result != null && !result.isEmpty()) {
319             sbUserApps.append("User '" + orgUserId + "' has Roles={");
320             for (RoleInAppForUser appRole : result) {
321                 if (appRole.isApplied) {
322                     sbUserApps.append(appRole.roleName + ", ");
323                 }
324             }
325             sbUserApps.append("} assigned to the appId '" + appid + "'.");
326         } else {
327             // Not sure creating an empty object will make any difference
328             // but would like to give it a shot for defect #DE221057
329             if (result == null) {
330                 result = new ArrayList<>();
331             }
332             sbUserApps.append("User '" + orgUserId + "' and appid " + appid + " has no roles");
333         }
334         logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
335
336         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "get result =", result);
337         if (feErrorString != "") {
338             logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: " + feErrorString);
339
340             response.addHeader("FEErrorString", feErrorString);
341             response.addHeader("Access-Control-Expose-Headers", "FEErrorString");
342         }
343         return result;
344     }
345
346     @PutMapping(value = { "/portalApi/userAppRoles" }, produces = "application/json")
347     public PortalRestResponse<String> putAppWithUserRoleStateForUser(HttpServletRequest request,
348             @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
349         // FieldsValidator fieldsValidator = new FieldsValidator();
350         PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
351         StringBuilder sbUserApps = new StringBuilder();
352         if (newAppRolesForUser != null) {
353             sbUserApps.append("User '" + newAppRolesForUser.getOrgUserId());
354             if (newAppRolesForUser.getAppId() != null && !newAppRolesForUser.getAppRoles().isEmpty()) {
355                 sbUserApps.append("' has roles = { ");
356                 for (RoleInAppForUser appRole : newAppRolesForUser.getAppRoles()) {
357                     if (appRole.isApplied) {
358                         sbUserApps.append(appRole.roleName + " ,");
359                     }
360                 }
361                 sbUserApps.deleteCharAt(sbUserApps.length() - 1);
362                 sbUserApps.append("} assigned for the app " + newAppRolesForUser.getAppId());
363             } else {
364                 sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.getAppId());
365             }
366         }
367         logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", sbUserApps.toString());
368
369         EPUser user = EPUserUtils.getUserSession(request);
370         // boolean changesApplied = false;
371         ExternalRequestFieldsValidator changesApplied = null;
372
373         if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)) {
374             EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser");
375         } else if (newAppRolesForUser == null) {
376             logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleStateForUser: newAppRolesForUser is null");
377         } else {
378             changesApplied = userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser);
379             try {
380                 if (changesApplied.isResult()) {
381                     logger.info(EELFLoggerDelegate.applicationLogger,
382                             "putAppWithUserRoleStateForUser: succeeded for app {}, user {}",
383                             newAppRolesForUser.getAppId(),
384                             newAppRolesForUser.getAppId());
385
386                     MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
387                             EPEELFLoggerAdvice.getCurrentDateTimeUTC());
388                     AuditLog auditLog = new AuditLog();
389                     auditLog.setUserId(user.getId());
390                     auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER);
391                     auditLog.setAffectedRecordId(newAppRolesForUser.getOrgUserId());
392                     auditLog.setComments(EcompPortalUtils.truncateString(sbUserApps.toString(),
393                             PortalConstants.AUDIT_LOG_COMMENT_SIZE));
394                     auditService.logActivity(auditLog, null);
395                                 String auditMessageInfo = EPLogUtil.formatAuditLogMessage("UserRolesController.putAppWithUserRoleStateForUser",
396                             EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(),
397                             newAppRolesForUser.getOrgUserId(), sbUserApps.toString());          
398
399                                 EPLogUtil.logAuditMessage(logger, auditMessageInfo);
400
401                                 portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null);
402
403                 }
404                 if (!changesApplied.isResult())
405                     throw new Exception(changesApplied.getDetailMessage());
406
407             } catch (Exception e) {
408                 logger.error(EELFLoggerDelegate.errorLogger,
409                         "putAppWithUserRoleStateForUser: failed for app {}, user {}", newAppRolesForUser.getAppId(),
410                         newAppRolesForUser.getOrgUserId(), e);
411                 portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), null);
412             }
413         }
414
415         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied);
416         return portalResponse;
417     }
418
419     @GetMapping(value = { "/portalApi/updateRemoteUserProfile" }, produces = "application/json")
420     public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request,
421             HttpServletResponse response) {
422
423         String updateRemoteUserFlag = FAILURE;
424         try {
425             // saveNewUser = userService.saveNewUser(newUser);
426             String orgUserId = request.getParameter("loginId");
427             Long appId = Long.parseLong(request.getParameter("appId"));
428             userRolesService.updateRemoteUserProfile(orgUserId, appId);
429
430         } catch (Exception e) {
431             logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
432             return new PortalRestResponse<>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage());
433         }
434         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, "");
435
436     }
437
438     @GetMapping(value = { "/portalApi/app/{appId}/users" }, produces = "application/json")
439     public List<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request,
440             @PathVariable("appId") Long appId) throws HTTPException {
441         try {
442             logger.debug(EELFLoggerDelegate.debugLogger, "/portalApi/app/{}/users was invoked", appId);
443             return userRolesService.getUsersFromAppEndpoint(appId);
444         } catch (Exception e) {
445             logger.error(EELFLoggerDelegate.errorLogger, "getUsersFromAppEndpoint failed", e);
446             return new ArrayList<>();
447         }
448     }
449
450     @GetMapping(value = { "/portalApi/app/{appId}/roles" }, produces = "application/json")
451     public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId)
452             throws HTTPException {
453         EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
454         List<EcompRole> rolesList = Arrays.asList(appRoles);
455         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId,
456                 rolesList);
457
458         return rolesList;
459     }
460
461     @GetMapping(value = { "/portalApi/admin/import/app/{appId}/roles" }, produces = "application/json")
462     public List<EPRole> importRolesFromRemoteApplication(HttpServletRequest request, @PathVariable("appId") Long appId)
463             throws HTTPException {
464         List<EPRole> rolesList = userRolesService.importRolesFromRemoteApplication(appId);
465         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles",
466                 "response for appId=" + appId, rolesList);
467
468         return rolesList;
469     }
470
471     @GetMapping(value = { "/portalApi/app/{appId}/user/{orgUserId}/roles" }, produces = "application/json")
472     public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId,
473             @PathVariable("orgUserId") String orgUserId) throws Exception {
474         if (!EcompPortalUtils.legitimateUserId(orgUserId)) {
475             String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId;
476             logger.error(EELFLoggerDelegate.errorLogger, msg);
477             throw new Exception(msg);
478         }
479         EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId,
480                 String.format("/user/%s/roles", orgUserId));
481         if (roles.length != 1) {
482             String msg = "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length;
483             logger.error(EELFLoggerDelegate.errorLogger, msg);
484             throw new Exception(msg);
485         }
486
487         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles",
488                 "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]);
489         return roles[0];
490     }
491
492     @PutMapping(value = { "/portalApi/saveUserAppRoles" }, produces = "application/json")
493     public FieldsValidator putAppWithUserRoleRequest(HttpServletRequest request,
494             @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
495         FieldsValidator fieldsValidator = null;
496         try {
497
498             EPUser user = EPUserUtils.getUserSession(request);
499             fieldsValidator = userRolesService.putUserAppRolesRequest(newAppRolesForUser, user);
500             response.setStatus(fieldsValidator.httpStatusCode.intValue());
501
502         } catch (Exception e) {
503             logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleRequest failed", e);
504
505         }
506         // return fieldsValidator;
507         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/saveUserAppRoles", "PUT result =",
508                 response.getStatus());
509         return fieldsValidator;
510     }
511
512     @GetMapping(value = { "/portalApi/appCatalogRoles" }, produces = "application/json")
513     public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(HttpServletRequest request,
514             @RequestParam("appName") String appName) {
515         EPUser user = EPUserUtils.getUserSession(request);
516         List<EPUserAppCatalogRoles> userAppRoleList = null;
517         try {
518             userAppRoleList = userRolesService.getUserAppCatalogRoles(user, appName);
519         } catch (Exception e) {
520             logger.error(EELFLoggerDelegate.errorLogger, "putUserWidgetsSortPref failed", e);
521
522         }
523         Collections.sort(userAppRoleList, getUserAppCatalogRolesComparator);
524         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", userAppRoleList);
525
526         return userAppRoleList;
527
528     }
529
530     private Comparator<EPUserAppCatalogRoles> getUserAppCatalogRolesComparator =
531             new Comparator<EPUserAppCatalogRoles>() {
532                 public int compare(EPUserAppCatalogRoles o1, EPUserAppCatalogRoles o2) {
533                     return o1.getRolename().compareTo(o2.getRolename());
534                 }
535             };
536
537     @GetMapping(value = "/portalApi/externalRequestAccessSystem",
538             produces = "application/json")
539     public ExternalSystemAccess readExternalRequestAccess(HttpServletRequest request) {
540         ExternalSystemAccess result = null;
541         try {
542             result = userRolesService.getExternalRequestAccess();
543             EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =",
544                     result);
545         } catch (Exception e) {
546             logger.error(EELFLoggerDelegate.errorLogger, "readExternalRequestAccess failed: " + e.getMessage());
547         }
548         return result;
549     }
550
551     @GetMapping(value = { "/portalApi/checkIfUserIsSuperAdmin" }, produces = "application/json")
552     public boolean checkIfUserIsSuperAdmin(HttpServletRequest request,
553             HttpServletResponse response) {
554         EPUser user = EPUserUtils.getUserSession(request);
555         boolean isSuperAdmin = false;
556         try {
557             isSuperAdmin = adminRolesService.isSuperAdmin(user);
558         } catch (Exception e) {
559             logger.error(EELFLoggerDelegate.errorLogger, "checkIfUserIsSuperAdmin failed: " + e.getMessage());
560         }
561         return isSuperAdmin;
562     }
563     
564     /**
565          * 
566          * @param userId
567          * @param app
568          * @param applicationsRestClientService
569          * @return EPUser
570          * @throws HTTPException
571          */
572         protected EPUser getUserInfo(String userId, ApplicationsRestClientService applicationsRestClientService)
573                         throws HTTPException {
574                 @SuppressWarnings("unchecked")
575                 List<EPUser> userList = (List<EPUser>) dataAccessService
576                                 .executeQuery("from EPUser where orgUserId='" + userId + "'", null);
577                 if (userList != null && !userList.isEmpty())
578                         return userList.get(0);
579                 else
580                         return null;
581         }
582 }