nexus site path corrected
[portal.git] / ecomp-portal-BE / src / main / java / org / openecomp / portalapp / portal / controller / UserRolesController.java
1 /*-
2  * ================================================================================
3  * eCOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.controller;
21
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.List;
25
26 import javax.servlet.http.HttpServletRequest;
27 import javax.servlet.http.HttpServletResponse;
28
29 import org.apache.cxf.transport.http.HTTPException;
30 import org.openecomp.portalapp.controller.EPRestrictedBaseController;
31 import org.openecomp.portalapp.portal.domain.EPRole;
32 import org.openecomp.portalapp.portal.domain.EPUser;
33 import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
34 import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
35 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
36 import org.openecomp.portalapp.portal.service.AdminRolesService;
37 import org.openecomp.portalapp.portal.service.ApplicationsRestClientService;
38 import org.openecomp.portalapp.portal.service.SearchService;
39 import org.openecomp.portalapp.portal.service.UserRolesService;
40 import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin;
41 import org.openecomp.portalapp.portal.transport.AppWithRolesForUser;
42 import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole;
43 import org.openecomp.portalapp.portal.transport.FieldsValidator;
44 import org.openecomp.portalapp.portal.transport.RoleInAppForUser;
45 import org.openecomp.portalapp.portal.transport.UserApplicationRoles;
46 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
47 import org.openecomp.portalapp.util.EPUserUtils;
48 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
49 import org.openecomp.portalsdk.core.restful.domain.EcompRole;
50 import org.openecomp.portalsdk.core.service.RoleService;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.context.annotation.EnableAspectJAutoProxy;
53 import org.springframework.web.bind.annotation.PathVariable;
54 import org.springframework.web.bind.annotation.RequestBody;
55 import org.springframework.web.bind.annotation.RequestMapping;
56 import org.springframework.web.bind.annotation.RequestMethod;
57 import org.springframework.web.bind.annotation.RequestParam;
58 import org.springframework.web.bind.annotation.RestController;
59
60 @RestController
61 @org.springframework.context.annotation.Configuration
62 @EnableAspectJAutoProxy
63 @EPAuditLog
64 public class UserRolesController extends EPRestrictedBaseController {
65         
66         static final String FAILURE = "failure";
67
68         @Autowired
69         SearchService searchService;
70         @Autowired
71         AdminRolesService adminRolesService;
72         @Autowired
73         UserRolesService userRolesService;
74         @Autowired
75         ApplicationsRestClientService applicationsRestClientService;
76         @Autowired
77         RoleService roleService;
78
79         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class);
80
81         /**
82          * RESTful service method to fetch users in the WebPhone external service
83          * 
84          * @return array of found users as json
85          */
86         @RequestMapping(value = { "/portalApi/queryUsers" }, method = RequestMethod.GET, produces = "application/json")
87         public String getPhoneBookSearchResult(HttpServletRequest request, @RequestParam("search") String searchString, HttpServletResponse response) {
88                 EPUser user = EPUserUtils.getUserSession(request);
89                 String searchResult = null;
90                 if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)) {
91                         EcompPortalUtils.setBadPermissions(user, response, "getPhoneBookSearchResult");
92                 } else {
93                         searchString = searchString.trim();
94                         if (searchString.length() > 0) {
95                                 //searchResult = searchService.searchUsersInPhoneBook(searchString);
96                                 searchResult = searchService.searchUsersInFnTable(searchString);
97                         } else {
98                                 logger.info(EELFLoggerDelegate.errorLogger, "getPhoneBookSearchResult - too short search string: " + searchString);
99                         }
100                 }
101                 EcompPortalUtils.logAndSerializeObject("/portalApi/queryUsers", "result =", searchResult);
102                 
103                 return searchResult;
104         }
105
106         /**
107          * RESTful service method to fetch applications where user is admin
108          * 
109          * @return for GET: array of all applications with boolean isAdmin=true/false for each application
110          */
111         @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = { RequestMethod.GET }, produces = "application/json")
112         public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(HttpServletRequest request, @RequestParam("orgUserId") String orgUserId,
113                         HttpServletResponse response) {
114                 
115                 EPUser user = EPUserUtils.getUserSession(request);
116                 AppsListWithAdminRole result = null;
117                 if (!adminRolesService.isSuperAdmin(user)) {
118                         EcompPortalUtils.setBadPermissions(user, response, "getAppsWithAdminRoleStateForUser");
119                 } else {
120                         if (EcompPortalUtils.legitimateUserId(orgUserId)) {
121                                 result = adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId);
122                         } else {
123                                 logger.info(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser - parms error, no orgUserId");
124                                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
125                         }
126                 }
127
128                 StringBuilder adminAppRoles = new StringBuilder();
129                 if(result != null && result.appsRoles.size() >= 1) {
130                         adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {");
131                         for(AppNameIdIsAdmin adminAppRole : result.appsRoles) {
132                                 if (adminAppRole.isAdmin) {
133                                         adminAppRoles.append(adminAppRole.appName + ", ");
134                                 }
135                         }
136                         adminAppRoles.append("}.");
137                 } else {
138                         adminAppRoles.append("User '" + result.orgUserId + "' has no Apps with Admin Role.");
139                 }
140                 logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString());
141                 
142                 EcompPortalUtils.logAndSerializeObject("/portalApi/adminAppsRoles", "get result =", result);
143
144                 return result;
145         }
146
147         @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = { RequestMethod.PUT }, produces = "application/json")
148         public FieldsValidator putAppsWithAdminRoleStateForUser(HttpServletRequest request, @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles,
149                         HttpServletResponse response) {
150                 
151                 //newAppsListWithAdminRoles.appsRoles
152                 FieldsValidator fieldsValidator = new FieldsValidator();
153                 StringBuilder newAppRoles = new StringBuilder();
154                 if(newAppsListWithAdminRoles != null && newAppsListWithAdminRoles.appsRoles.size() >= 1) {
155                         newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has admin role to the apps = {");
156                         for(AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) {
157                                 if (adminAppRole.isAdmin) {
158                                         newAppRoles.append(adminAppRole.appName + ", ");
159                                 }
160                         }
161                         newAppRoles.append("}.");
162                 } else {
163                         newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has no Apps with Admin Role.");
164                 }
165                 logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString());
166                         
167                 EPUser user = EPUserUtils.getUserSession(request);
168                 boolean changesApplied = false;
169                 
170                 if (!adminRolesService.isSuperAdmin(user)) {
171                         EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser");
172                 } else {
173                         changesApplied = adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles);
174                 }
175                 EcompPortalUtils.logAndSerializeObject("/portalApi/adminAppsRoles", "put result =", changesApplied);
176                 
177                 return fieldsValidator;
178         }
179
180         @RequestMapping(value = { "/portalApi/userAppRoles" }, method = { RequestMethod.GET }, produces = "application/json")
181         public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("orgUserId") String orgUserId, @RequestParam("app") Long appid, HttpServletResponse response) {
182                 EPUser user = EPUserUtils.getUserSession(request);
183                 List<RoleInAppForUser> result = null;
184                 String feErrorString = "";
185                 if (!adminRolesService.isAccountAdmin(user)) {
186                         EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser");
187                         feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus());
188                 } else {
189                         if (EcompPortalUtils.legitimateUserId(orgUserId)) {
190                                 result = userRolesService.getAppRolesForUser(appid, orgUserId);
191                                 int responseCode = EcompPortalUtils.getExternalAppResponseCode();
192                                 if (responseCode != 0 && responseCode != 200) {
193                                         // external error
194                                         response.setStatus(responseCode);
195                                         feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode);
196                                 } else if (result == null) {
197                                         // If the result is null, there was an internal ecomp error in the service call.
198                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
199                                         feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
200                                 }
201                         } else {
202                                 logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no userId");
203                                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
204                                 feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST);
205                         }
206                 }
207                 
208                 StringBuilder sbUserApps = new StringBuilder();
209                 if (result!=null && result.size()>=1) {
210                         sbUserApps.append("User '" + orgUserId + "' has Roles={");
211                         for(RoleInAppForUser appRole : result) {
212                                 if (appRole.isApplied) {
213                                         sbUserApps.append(appRole.roleName + ", ");
214                                 }
215                         }
216                         sbUserApps.append("} assigned to the appId '" + appid + "'.");
217                 } else {
218                         if (result==null) {
219                                 result = new ArrayList<RoleInAppForUser>();
220                         }
221                         sbUserApps.append("User '" + orgUserId + "' and appid " + appid + " has no roles");
222                 }
223                 logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
224                 
225                 EcompPortalUtils.logAndSerializeObject("/portalApi/userAppRoles", "get result =", result);
226                 if (feErrorString != "") {
227                         logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: "+feErrorString);
228
229                         response.addHeader("FEErrorString", feErrorString);
230                         response.addHeader("Access-Control-Expose-Headers", "FEErrorString");
231                 }
232                 return result;
233         }
234
235         @RequestMapping(value = { "/portalApi/userAppRoles" }, method = { RequestMethod.PUT }, produces = "application/json")
236         public FieldsValidator putAppWithUserRoleStateForUser(HttpServletRequest request, @RequestBody AppWithRolesForUser newAppRolesForUser,
237                         HttpServletResponse response) {
238                 FieldsValidator fieldsValidator = new FieldsValidator();
239                 StringBuilder sbUserApps = new StringBuilder();
240                 if (newAppRolesForUser!=null) {
241                         sbUserApps.append("User '" + newAppRolesForUser.orgUserId);
242                         if (newAppRolesForUser.appRoles!=null && newAppRolesForUser.appRoles.size()>=1) {
243                                 sbUserApps.append("' has roles = {");
244                                 for(RoleInAppForUser appRole : newAppRolesForUser.appRoles) {
245                                                 if (appRole.isApplied) {
246                                                         sbUserApps.append(appRole.roleName + ", ");
247                                                 }
248                                 }
249                                 sbUserApps.append("} assigned for the app '" + newAppRolesForUser.appName + "'.");
250                         } else {
251                                 sbUserApps.append("' has no roles assigned for the app '" + newAppRolesForUser.appName + "'.");
252                         }
253                 }
254                 logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
255                 
256                 EPUser user = EPUserUtils.getUserSession(request);
257                 
258                 boolean changesApplied = false;
259                 if (!adminRolesService.isAccountAdmin(user)) {
260                         EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser");
261                 } else {
262                         changesApplied = userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser);
263                         if (changesApplied == false) {
264                                 logger.debug(EELFLoggerDelegate.debugLogger, "putAppWithUserRoleStateForUser - Set new User Roles failure");
265                         }
266                 }
267
268                 EcompPortalUtils.logAndSerializeObject("/portalApi/userAppRoles", "put result =", changesApplied);
269                                 
270                 return fieldsValidator;
271         }
272         
273         @RequestMapping(value = { "/portalApi/updateRemoteUserProfile" }, method = { RequestMethod.GET }, produces = "application/json")
274         public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request,HttpServletResponse response) {
275                 
276                 String updateRemoteUserFlag = FAILURE;
277                 try {
278                         //saveNewUser = userService.saveNewUser(newUser);
279                         String orgUserId = request.getParameter("loginId");
280                         Long appId = Long.parseLong(request.getParameter("appId"));
281                         userRolesService.updateRemoteUserProfile(orgUserId, appId);
282                         
283                 } catch (Exception e) {
284                         return new PortalRestResponse<String>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage());
285                 }
286                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, "");
287                 
288         }
289
290         @RequestMapping(value = { "/portalApi/app/{appId}/users" }, method = { RequestMethod.GET }, produces = "application/json")
291         public List<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException {
292                 try {
293                         List<UserApplicationRoles> appUsers = userRolesService.getUsersFromAppEndpoint(appId);
294                         return appUsers;
295                 } catch(Exception e) {
296                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing UserRolesController.getUsersFromAppEndpoint. Details: " + EcompPortalUtils.getStackTrace(e));
297                         return new ArrayList<UserApplicationRoles>();
298                 }
299         }
300
301         @RequestMapping(value = { "/portalApi/app/{appId}/roles" }, method = { RequestMethod.GET }, produces = "application/json")
302         public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException {
303                 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
304                 List<EcompRole> rolesList = Arrays.asList(appRoles);
305                 EcompPortalUtils.logAndSerializeObject("/portalApi/app/{appId}/roles", "response for appId=" + appId, rolesList);
306                 
307                 return rolesList;
308         }
309
310         @RequestMapping(value = { "/portalApi/admin/import/app/{appId}/roles" }, method = { RequestMethod.GET }, produces = "application/json")
311         public List<EPRole> importRolesFromRemoteApplication(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException {
312                 List<EPRole> rolesList = userRolesService.importRolesFromRemoteApplication(appId);
313                 EcompPortalUtils.logAndSerializeObject("/portalApi/admin/import/app/{appId}/roles", "response for appId=" + appId, rolesList);
314                 
315                 return rolesList;
316         }
317
318         @RequestMapping(value = { "/portalApi/app/{appId}/user/{orgUserId}/roles" }, method = { RequestMethod.GET }, produces = "application/json")
319         public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId, @PathVariable("orgUserId") String orgUserId) throws Exception {
320                 if (!EcompPortalUtils.legitimateUserId(orgUserId)) {
321                         String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId;
322                         logger.error(EELFLoggerDelegate.errorLogger, msg);
323                         throw new Exception(msg);
324                 }
325                 EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId, String.format("/user/%s/roles", orgUserId));
326                 if (roles.length != 1) {
327                         String msg = "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length;
328                         logger.error(EELFLoggerDelegate.errorLogger, msg);
329                         throw new Exception(msg);
330                 }
331                 
332                 EcompPortalUtils.logAndSerializeObject("/portalApi/app/{appId}/user/{orgUserId}/roles", "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]);
333                 return roles[0];
334         }
335         
336 }