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