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