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