Security/ Package Name changes
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / AppsControllerExternalRequest.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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.onap.portalapp.portal.controller;
39
40 import java.util.List;
41
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
44
45 import org.onap.portalapp.portal.domain.EPApp;
46 import org.onap.portalapp.portal.domain.EPUser;
47 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
48 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
49 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
50 import org.onap.portalapp.portal.service.AdminRolesService;
51 import org.onap.portalapp.portal.service.EPAppService;
52 import org.onap.portalapp.portal.service.PortalAdminService;
53 import org.onap.portalapp.portal.service.UserService;
54 import org.onap.portalapp.portal.transport.FieldsValidator;
55 import org.onap.portalapp.portal.transport.OnboardingApp;
56 import org.onap.portalapp.portal.utils.EcompPortalUtils;
57 import org.onap.portalapp.portal.utils.PortalConstants;
58 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
59 import org.springframework.beans.factory.annotation.Autowired;
60 import org.springframework.context.annotation.Configuration;
61 import org.springframework.context.annotation.EnableAspectJAutoProxy;
62 import org.springframework.web.bind.annotation.PathVariable;
63 import org.springframework.web.bind.annotation.RequestBody;
64 import org.springframework.web.bind.annotation.RequestMapping;
65 import org.springframework.web.bind.annotation.RequestMethod;
66 import org.springframework.web.bind.annotation.ResponseBody;
67 import org.springframework.web.bind.annotation.RestController;
68
69 import io.swagger.annotations.ApiOperation;
70
71 /**
72  * Processes requests from external systems (i.e., not the front-end web UI).
73  * First use case is ECOMP Controller, which has to create an admin and onboard
74  * itself upon launch of a fresh Portal.
75  * 
76  * Listens on the "auxapi" path prefix. Provides alternate implementations of
77  * methods in several existing controllers because an EPUser object is not
78  * available in the session for these requests.
79  * 
80  * Checks credentials sent via HTTP Basic Authentication. The Portal's basic
81  * HTTP authentication system requires that the user names and endpoints are
82  * registered together.
83  */
84 @RestController
85 @RequestMapping(PortalConstants.REST_AUX_API)
86 @Configuration
87 @EnableAspectJAutoProxy
88 @EPAuditLog
89 public class AppsControllerExternalRequest implements BasicAuthenticationController {
90
91         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsControllerExternalRequest.class);
92
93         private static final String ONBOARD_APP = "/onboardApp";
94
95         // Where is this used?
96         public boolean isAuxRESTfulCall() {
97                 return true;
98         }
99
100         /**
101          * For testing whether a user is a superadmin.
102          */
103         @Autowired
104         private AdminRolesService adminRolesService;
105
106         /**
107          * For onboarding or updating an app
108          */
109         @Autowired
110         private EPAppService appService;
111
112         /**
113          * For promoting a user to Portal admin
114          */
115         @Autowired
116         private PortalAdminService portalAdminService;
117
118         /**
119          * For creating a new user
120          */
121         @Autowired
122         private UserService userService;
123
124         /**
125          * Creates a new user as a Portal administrator.
126          * 
127          * <PRE>
128          { 
129                 "loginId" : "abc123",
130                 "loginPwd": "",
131                 "email":"ecomp@controller" 
132          }
133          * </PRE>
134          * 
135          * @param request
136          *            HttpServletRequest
137          * @param epUser
138          *            User details; the email and orgUserId fields are mandatory
139          * @param response
140          *            HttpServletResponse
141          * @return PortalRestResponse with success or failure
142          */
143         @ApiOperation(value = "Creates a new user as a Portal administrator.", response = PortalRestResponse.class)
144         @RequestMapping(value = "/portalAdmin", method = RequestMethod.POST, produces = "application/json")
145         @ResponseBody
146         public PortalRestResponse<String> postPortalAdmin(HttpServletRequest request, HttpServletResponse response,
147                         @RequestBody EPUser epUser) {
148                 EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "request", epUser);
149                 PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
150
151                 // Check mandatory fields.
152                 if (epUser.getEmail() == null || epUser.getEmail().trim().length() == 0 //
153                                 || epUser.getLoginId() == null || epUser.getLoginId().trim().length() == 0 //
154                                 || epUser.getLoginPwd() == null) {
155                         portalResponse.setStatus(PortalRestStatusEnum.ERROR);
156                         portalResponse.setMessage("Missing required field: email, loginId, or loginPwd");
157                         return portalResponse;
158                 }
159
160                 try {
161                         // Check for existing user; create if not found.
162                         List<EPUser> userList = userService.getUserByUserId(epUser.getOrgUserId());
163                         if (userList == null || userList.size() == 0) {
164                                 // Create user with first, last names etc.; do check for
165                                 // duplicates.
166                                 String userCreateResult = userService.saveNewUser(epUser, "Yes");
167                                 if (!"success".equals(userCreateResult)) {
168                                         portalResponse.setStatus(PortalRestStatusEnum.ERROR);
169                                         portalResponse.setMessage(userCreateResult);
170                                         return portalResponse;
171                                 }
172                         }
173
174                         // Check for Portal admin status; promote if not.
175                         if (adminRolesService.isSuperAdmin(epUser)) {
176                                 portalResponse.setStatus(PortalRestStatusEnum.OK);
177                         } else {
178                                 FieldsValidator fv = portalAdminService.createPortalAdmin(epUser.getOrgUserId());
179                                 if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
180                                         portalResponse.setStatus(PortalRestStatusEnum.OK);
181                                 } else {
182                                         portalResponse.setStatus(PortalRestStatusEnum.ERROR);
183                                         portalResponse.setMessage(fv.toString());
184                                 }
185                         }
186                 } catch (Exception ex) {
187                         // Uncaught exceptions yield 404 and an empty error page
188                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
189                         portalResponse.setStatus(PortalRestStatusEnum.ERROR);
190                         portalResponse.setMessage(ex.toString());
191                 }
192
193                 EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "response", portalResponse);
194                 return portalResponse;
195         }
196
197         /**
198          * Gets the specified application that is on-boarded in Portal.
199          * 
200          * @param request
201          *            HttpServletRequest
202          * @param appId
203          *            Application ID to get
204          * @param response
205          *            httpServletResponse
206          * @return OnboardingApp objects
207          */
208         @ApiOperation(value = "Gets the specified application that is on-boarded in Portal.", response = OnboardingApp.class)
209         @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.GET, produces = "application/json")
210         @ResponseBody
211         public OnboardingApp getOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
212                         @PathVariable("appId") Long appId) {
213                 EPApp epApp = appService.getApp(appId);
214                 OnboardingApp obApp = new OnboardingApp();
215                 appService.createOnboardingFromApp(epApp, obApp);
216                 EcompPortalUtils.logAndSerializeObject(logger, "getOnboardAppExternal", "response", obApp);
217                 return obApp;
218         }
219
220         /**
221          * Adds a new application to Portal. The My Logins App Owner in the request
222          * must be the organization user ID of a person who is a Portal
223          * administrator.
224          * 
225          * <pre>
226          * { 
227                 "myLoginsAppOwner" : "abc123",
228                 "name": "dashboard",
229                 "url": "http://k8s/something",
230                 "restUrl" : "http://targeturl.com",
231                 "restrictedApp" : true,
232                 "isOpen" : true,
233                 "isEnabled": false
234                 }
235          * </pre>
236          * 
237          * @param request
238          *            HttpServletRequest
239          * @param response
240          *            httpServletResponse
241          * @param newOnboardApp
242          *            Message with details about the app to add
243          * @return PortalRestResponse
244          */
245         @ApiOperation(value = "Adds a new application to Portal.", response = PortalRestResponse.class)
246         @RequestMapping(value = { ONBOARD_APP }, method = RequestMethod.POST, produces = "application/json")
247         @ResponseBody
248         public PortalRestResponse<String> postOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
249                         @RequestBody OnboardingApp newOnboardApp) {
250                 EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "request", newOnboardApp);
251                 PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
252
253                 // Validate fields
254                 if (newOnboardApp.id != null) {
255                         portalResponse.setStatus(PortalRestStatusEnum.ERROR);
256                         portalResponse.setMessage("Unexpected field: id");
257                         return portalResponse;
258                 }
259                 if (newOnboardApp.name == null || newOnboardApp.name.trim().length() == 0 //
260                                 || newOnboardApp.url == null || newOnboardApp.url.trim().length() == 0 //
261                                 || newOnboardApp.restUrl == null || newOnboardApp.restUrl.trim().length() == 0
262                                 || newOnboardApp.myLoginsAppOwner == null || newOnboardApp.myLoginsAppOwner.trim().length() == 0
263                                 || newOnboardApp.restrictedApp == null //
264                                 || newOnboardApp.isOpen == null //
265                                 || newOnboardApp.isEnabled == null) {
266                         portalResponse.setStatus(PortalRestStatusEnum.ERROR);
267                         portalResponse.setMessage(
268                                         "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner");
269                         return portalResponse;
270                 }
271
272                 try {
273                         List<EPUser> userList = userService.getUserByUserId(newOnboardApp.myLoginsAppOwner);
274                         if (userList == null || userList.size() != 1) {
275                                 portalResponse.setStatus(PortalRestStatusEnum.ERROR);
276                                 portalResponse.setMessage("Failed to find user: " + newOnboardApp.myLoginsAppOwner);
277                                 return portalResponse;
278                         }
279
280                         EPUser epUser = userList.get(0);
281                         // Check for Portal admin status
282                         if (! adminRolesService.isSuperAdmin(epUser)) {
283                                 portalResponse.setStatus(PortalRestStatusEnum.ERROR);
284                                 portalResponse.setMessage("User lacks Portal admin role: " + epUser.getLoginId());
285                                 return portalResponse;                          
286                         }
287                                 
288                         newOnboardApp.normalize();
289                         FieldsValidator fv = appService.addOnboardingApp(newOnboardApp, epUser);
290                         if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
291                                 portalResponse.setStatus(PortalRestStatusEnum.OK);
292                         } else {
293                                 portalResponse.setStatus(PortalRestStatusEnum.ERROR);
294                                 portalResponse.setMessage(fv.toString());
295                         }
296                 } catch (Exception ex) {
297                         // Uncaught exceptions yield 404 and an empty error page
298                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
299                         portalResponse.setStatus(PortalRestStatusEnum.ERROR);
300                         portalResponse.setMessage(ex.toString());
301                 }
302                 EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "response", portalResponse);
303                 return portalResponse;
304         }
305
306         /**
307          * Updates information about an on-boarded application in Portal. The My
308          * Logins App Owner in the request must be the organization user ID of a
309          * person who is a Portal administrator.
310          * <pre>
311            { 
312                 "id" : 123,
313                 "myLoginsAppOwner" : "abc123",
314                 "name": "dashboard",
315                 "url": "http://k8s/something",
316                 "restUrl" : "http://targeturl.com",
317                 "restrictedApp" : true,
318                 "isOpen" : true,
319                 "isEnabled": false
320                 }
321                 </pre>
322          * @param request
323          *            HttpServletRequest
324          * @param response
325          *            httpServletResponse
326          * @param appId
327          *            application id
328          * @param oldOnboardApp
329          *            Message with details about the app to add
330          * @return PortalRestResponse
331          */
332         @ApiOperation(value = "Updates information about an on-boarded application in Portal.", response = PortalRestResponse.class)
333         @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.PUT, produces = "application/json")
334         @ResponseBody
335         public PortalRestResponse<String> putOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
336                         @PathVariable("appId") Long appId, @RequestBody OnboardingApp oldOnboardApp) {
337                 EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "request", oldOnboardApp);
338                 PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
339                 // Validate fields.
340                 if (oldOnboardApp.id == null || !appId.equals(oldOnboardApp.id)) {
341                         portalResponse.setStatus(PortalRestStatusEnum.ERROR);
342                         portalResponse.setMessage("Unexpected value for field: id");
343                         return portalResponse;
344                 }
345                 if (oldOnboardApp.name == null || oldOnboardApp.name.trim().length() == 0 //
346                                 || oldOnboardApp.url == null || oldOnboardApp.url.trim().length() == 0 //
347                                 || oldOnboardApp.restUrl == null || oldOnboardApp.restUrl.trim().length() == 0
348                                 || oldOnboardApp.myLoginsAppOwner == null || oldOnboardApp.myLoginsAppOwner.trim().length() == 0
349                                 || oldOnboardApp.restrictedApp == null //
350                                 || oldOnboardApp.isOpen == null //
351                                 || oldOnboardApp.isEnabled == null) {
352                         portalResponse.setStatus(PortalRestStatusEnum.ERROR);
353                         portalResponse.setMessage(
354                                         "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner");
355                         return portalResponse;
356                 }
357
358                 try {
359                         List<EPUser> userList = userService.getUserByUserId(oldOnboardApp.myLoginsAppOwner);
360                         if (userList == null || userList.size() != 1) {
361                                 portalResponse.setStatus(PortalRestStatusEnum.ERROR);
362                                 portalResponse.setMessage("Failed to find user: " + oldOnboardApp.myLoginsAppOwner);
363                                 return portalResponse;
364                         }
365
366                         EPUser epUser = userList.get(0);
367                         // Check for Portal admin status
368                         if (! adminRolesService.isSuperAdmin(epUser)) {
369                                 portalResponse.setStatus(PortalRestStatusEnum.ERROR);
370                                 portalResponse.setMessage("User lacks Portal admin role: " + epUser.getLoginId());
371                                 return portalResponse;                          
372                         }
373
374                         oldOnboardApp.normalize();
375                         FieldsValidator fv = appService.modifyOnboardingApp(oldOnboardApp, epUser);
376                         if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
377                                 portalResponse.setStatus(PortalRestStatusEnum.OK);
378                         } else {
379                                 portalResponse.setStatus(PortalRestStatusEnum.ERROR);
380                                 portalResponse.setMessage(fv.toString());
381                         }
382                 } catch (Exception ex) {
383                         // Uncaught exceptions yield 404 and an empty error page
384                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
385                         portalResponse.setStatus(PortalRestStatusEnum.ERROR);
386                         portalResponse.setMessage(ex.toString());
387                 }
388                 EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "response", portalResponse);
389                 return portalResponse;
390         }
391
392 }