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