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