fixed some issues from sonar
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / RolesApprovalSystemController.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38
39 package org.onap.portalapp.portal.controller;
40
41 import java.util.ArrayList;
42
43 import javax.servlet.http.HttpServletRequest;
44 import javax.servlet.http.HttpServletResponse;
45
46 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
47 import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser;
48 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
49 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
50 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
51 import org.onap.portalapp.portal.service.UserRolesService;
52 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
53 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.context.annotation.Configuration;
56 import org.springframework.context.annotation.EnableAspectJAutoProxy;
57 import org.springframework.web.bind.annotation.RequestBody;
58 import org.springframework.web.bind.annotation.RequestMapping;
59 import org.springframework.web.bind.annotation.PostMapping;
60 import org.springframework.web.bind.annotation.PutMapping;
61 import org.springframework.web.bind.annotation.DeleteMapping;
62 import org.springframework.web.bind.annotation.RestController;
63
64 import io.swagger.annotations.ApiOperation;
65
66 @RestController
67 @RequestMapping("/auxapi")
68 @Configuration
69 @EnableAspectJAutoProxy
70 @EPAuditLog
71 public class RolesApprovalSystemController implements BasicAuthenticationController {
72         
73         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RolesApprovalSystemController.class);
74
75         @Autowired
76         private UserRolesService userRolesService;
77
78         /**
79          * Creates an application user with the specified roles.
80          * 
81          * @param request
82          * @param extSysUser
83          * @return PortalRestResponse with appropriate status value and message
84          */
85         @ApiOperation(value = "Creates an application user with the specified roles.", response = PortalRestResponse.class)
86         @PostMapping(value = { "/userProfile" }, produces = "application/json")
87         public PortalRestResponse<String> postUserProfile(HttpServletRequest request,
88                         @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) {
89                 ExternalRequestFieldsValidator reqResult = null;
90                 try {
91                         logger.info(EELFLoggerDelegate.debugLogger, "postUserProfile: request received for app {}, user {}",
92                                         extSysUser.getApplicationName(), extSysUser.getLoginId());
93                         
94                         validateExtSystemUser(extSysUser, true);
95                  reqResult = userRolesService.setExternalRequestUserAppRole(extSysUser, "POST");
96                  if (!reqResult.isResult())
97                                 throw new Exception(reqResult.getDetailMessage());
98                 } catch (Exception e) {
99                         logger.error(EELFLoggerDelegate.errorLogger, "postUserProfile: failed for app {}, user {}",
100                                         extSysUser.getApplicationName(), extSysUser.getLoginId(), e);
101                         if(reqResult == null || (!reqResult.isResult()  && !e.getMessage().contains("404") && !e.getMessage().contains("405"))){
102                                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
103                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
104                                                 e.getMessage(), "save user profile failed"); 
105                     } else if(e.getMessage().contains("404")){
106                                 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
107                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
108                                                 e.getMessage(), "save user profile failed");
109                     } else if(e.getMessage().contains("500")){
110                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
111                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
112                                                 e.getMessage(), "save user profile failed");
113                         } else if (e.getMessage().contains("405")) {
114                                 response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
115                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(),
116                                                 "save user profile failed");
117                         } else {
118                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
119                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(),
120                                                 "save user profile failed");
121                         }
122                 }
123                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, reqResult.getDetailMessage(), "Success");
124         }
125
126         /**
127          * Updates an application user to have only the specified roles.
128          * 
129          * @param request
130          * @param extSysUser
131          * @return PortalRestResponse with appropriate status value and message
132          */
133         @ApiOperation(value = "Updates an application user to have only the specified roles.", response = PortalRestResponse.class)
134         @PutMapping(value = { "/userProfile" }, produces = "application/json")
135         public PortalRestResponse<String> putUserProfile(HttpServletRequest request,
136                         @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) {
137                 ExternalRequestFieldsValidator reqResult = null;
138                 try {
139                         logger.info(EELFLoggerDelegate.debugLogger, "putUserProfile: request received for app {}, user {}", 
140                                         extSysUser.getApplicationName(), extSysUser.getLoginId());
141                         validateExtSystemUser(extSysUser, true);
142                         reqResult = userRolesService.setExternalRequestUserAppRole(extSysUser, "PUT");
143                          if (!reqResult.isResult())
144                                         throw new Exception(reqResult.getDetailMessage());
145                 } catch (Exception e) {
146                         logger.error(EELFLoggerDelegate.errorLogger, "putUserProfile: failed for app {}, user {}",
147                                         extSysUser.getApplicationName(), extSysUser.getLoginId(), e);
148                         if(reqResult == null || (!reqResult.isResult()  && !e.getMessage().contains("404") && !e.getMessage().contains("405"))){
149                                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
150                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
151                                                 e.getMessage(), "save user profile failed"); 
152                     } else if(e.getMessage().contains("404")){
153                                 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
154                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
155                                                 e.getMessage(), "save user profile failed");
156                         } else if(e.getMessage().contains("500")){
157                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
158                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
159                                                 e.getMessage(), "save user profile failed");
160                         } else if (e.getMessage().contains("405")) {
161                                 response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
162                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), "save user profile failed");
163                         } else{
164                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
165                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
166                                                 e.getMessage(), "save user profile failed");
167                         }
168                 }
169                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, reqResult.getDetailMessage() , "Success");
170         }
171
172         /**
173          * Deletes an application user by removing all assigned roles.
174          * 
175          * @param request
176          * @param extSysUser
177          *            This object must have zero roles.
178          * @return PortalRestResponse with appropriate status value and message
179          */
180         @ApiOperation(value = "Processes a request to delete one or more application roles for one      specified user who has roles.", response = PortalRestResponse.class)
181         @DeleteMapping(value = { "/userProfile" }, produces = "application/json")
182         public PortalRestResponse<String> deleteUserProfile(HttpServletRequest request,
183                         @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) {
184                 ExternalRequestFieldsValidator reqResult  = null;
185                 try {
186                         logger.info(EELFLoggerDelegate.debugLogger, "deleteUserProfile: request received for app {}, user {}", 
187                                         extSysUser.getApplicationName(), extSysUser.getLoginId());
188                         validateExtSystemUser(extSysUser, false);
189                         // Ignore any roles that might be mistakenly present in the request
190                         extSysUser.setRoles(new ArrayList<ExternalSystemRoleApproval>());
191                         reqResult = userRolesService.setExternalRequestUserAppRole(extSysUser, "DELETE");
192                          if (!reqResult.isResult())
193                                         throw new Exception(reqResult.getDetailMessage());
194                 } catch (Exception e) {
195                         logger.error(EELFLoggerDelegate.errorLogger, "deleteUserProfile: failed for app {}, user {}",
196                                         extSysUser.getApplicationName(), extSysUser.getLoginId(), e);
197                         if(reqResult == null || (!reqResult.isResult()  && !e.getMessage().contains("404"))){
198                                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
199                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
200                                                 e.getMessage(), "delete user profile failed"); 
201                     }else if(e.getMessage().contains("404")){
202                                 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
203                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
204                                                 e.getMessage(), "delete user profile failed");
205                         } else{
206                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
207                                 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
208                                                 e.getMessage(), "delete user profile failed");
209                         }
210                 }
211                 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Deleted Successfully", "Success");
212         }
213
214         /**
215          * Checks for presence of required fields.
216          * 
217          * @param extSysUser
218          * @param rolesRequired
219          *            If true, checks whether roles are present
220          * @throws Exception
221          *             If any field is missing.
222          */
223         private void validateExtSystemUser(ExternalSystemUser extSysUser, boolean rolesRequired) throws Exception {
224                 if (extSysUser.getLoginId() == null || extSysUser.getLoginId().equals(""))
225                         throw new Exception("Request has no login ID");
226                 if (extSysUser.getApplicationName() == null || extSysUser.getApplicationName().equals(""))
227                         throw new Exception("Request has no application name");
228                 if (extSysUser.getMyloginrequestId() == null)
229                         throw new Exception("Request has no request ID");
230                 if (rolesRequired && (extSysUser.getRoles() == null || extSysUser.getRoles().size() == 0))
231                         throw new Exception("Request has no roles");
232         }
233
234 }