lowered code smells
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / PortalAdminController.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *  Modification Copyright © 2020 IBM.
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 package org.onap.portalapp.portal.controller;
41
42 import java.util.List;
43
44 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
46
47 import org.onap.portalapp.controller.EPRestrictedBaseController;
48 import org.onap.portalapp.portal.domain.EPRole;
49 import org.onap.portalapp.portal.domain.EPUser;
50 import org.onap.portalapp.portal.domain.EcompAuditLog;
51 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
52 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
53 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
54 import org.onap.portalapp.portal.service.AdminRolesService;
55 import org.onap.portalapp.portal.service.PortalAdminService;
56 import org.onap.portalapp.portal.transport.FieldsValidator;
57 import org.onap.portalapp.portal.transport.PortalAdmin;
58 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
59 import org.onap.portalapp.portal.utils.EcompPortalUtils;
60 import org.onap.portalapp.util.EPUserUtils;
61 import org.onap.portalapp.validation.DataValidator;
62 import org.onap.portalapp.validation.SecureString;
63 import org.onap.portalsdk.core.domain.AuditLog;
64 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
65 import org.onap.portalsdk.core.service.AuditService;
66 import org.onap.portalsdk.core.util.SystemProperties;
67 import org.slf4j.MDC;
68 import org.springframework.beans.factory.annotation.Autowired;
69 import org.springframework.context.annotation.Configuration;
70 import org.springframework.context.annotation.EnableAspectJAutoProxy;
71 import org.springframework.web.bind.annotation.PathVariable;
72 import org.springframework.web.bind.annotation.RequestBody;
73 import org.springframework.web.bind.annotation.GetMapping;
74 import org.springframework.web.bind.annotation.PostMapping;
75 import org.springframework.web.bind.annotation.DeleteMapping;
76 import org.springframework.web.bind.annotation.RestController;
77
78 @RestController
79 @Configuration
80 @EnableAspectJAutoProxy
81 @EPAuditLog
82 public class PortalAdminController extends EPRestrictedBaseController {
83         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminController.class);
84         private static final DataValidator DATA_VALIDATOR = new DataValidator();
85
86         private PortalAdminService portalAdminService;
87         private AdminRolesService adminRolesService;
88         private AuditService auditService;
89
90         @Autowired
91         public PortalAdminController(PortalAdminService portalAdminService,
92                 AdminRolesService adminRolesService, AuditService auditService){
93                 this.portalAdminService = portalAdminService;
94                 this.adminRolesService = adminRolesService;
95                 this.auditService = auditService;
96         }
97
98         @GetMapping(value = { "/portalApi/portalAdmins" }, produces = "application/json")
99         public List<PortalAdmin> getPortalAdmins(HttpServletRequest request, HttpServletResponse response) {
100                 EPUser user = EPUserUtils.getUserSession(request);
101                 List<PortalAdmin> portalAdmins = null;
102                 if (user == null) {
103                         logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, null user");
104                         EcompPortalUtils.setBadPermissions(user, response, "getPortalAdmins");
105                 } else if (!adminRolesService.isSuperAdmin(user)) {
106                         logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, bad permissions");
107                         EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
108                 } else {
109                         // return the list of portal admins
110                         portalAdmins = portalAdminService.getPortalAdmins();
111                         logger.debug(EELFLoggerDelegate.debugLogger, "portalAdmins: called getPortalAdmins()");
112                         EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getPortalAdmins", "result =", portalAdmins);
113                 }
114
115                 return portalAdmins;
116         }
117
118         /**
119          * RESTful service method to create a new portal admin. Requirement: you
120          * must be the ONAP portal super admin user.
121          * @param request 
122          * @param userId 
123          * @param response 
124          * @return FieldsValidator 
125          */
126         @PostMapping(value = { "/portalApi/portalAdmin" })
127         public FieldsValidator createPortalAdmin(HttpServletRequest request, @RequestBody String userId,
128                         HttpServletResponse response) {
129                 EPUser user = EPUserUtils.getUserSession(request);
130                 FieldsValidator fieldsValidator = null;
131                 if(!DATA_VALIDATOR.isValid(new SecureString(userId))){
132                         logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin not valid userId");
133                         EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
134                 }else if (user == null) {
135                         logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin, null user");
136                         EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
137                 } else if (!adminRolesService.isSuperAdmin(user)) {
138                         logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin bad permissions");
139                         EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
140                 } else {
141                         fieldsValidator = portalAdminService.createPortalAdmin(userId);
142                         int statusCode = fieldsValidator.httpStatusCode.intValue();
143                         response.setStatus(statusCode);
144                         if (statusCode == 200) {
145                                 AuditLog auditLog = new AuditLog();
146                                 auditLog.setUserId(user.getId());
147                                 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN);
148                                 auditLog.setAffectedRecordId(userId);
149                                 try {
150                                         auditService.logActivity(auditLog, null);
151                                 } catch (Exception e) {
152                                         logger.error(EELFLoggerDelegate.errorLogger, "createPortalAdmin: failed for save audit log", e);
153                                 }
154                                 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
155                                 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
156                                 EcompPortalUtils.calculateDateTimeDifferenceForLog(
157                                                 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
158                                                 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
159                                 logger.info(EELFLoggerDelegate.auditLogger,
160                                                 EPLogUtil.formatAuditLogMessage("PortalAdminController.createPortalAdmin",
161                                                                 EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN, user.getOrgUserId(), userId,
162                                                                 "A new Portal Admin has been added"));
163                                 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
164                                 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
165                                 MDC.remove(SystemProperties.MDC_TIMER);
166                         }
167                 }
168                 EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "POST result =", response.getStatus());
169
170                 return fieldsValidator;
171         }
172
173         @DeleteMapping(value = { "/portalApi/portalAdmin/{userInfo}" })
174         public FieldsValidator deletePortalAdmin(HttpServletRequest request, @PathVariable("userInfo") String userInfo,
175                         HttpServletResponse response) {
176
177                 if(!DATA_VALIDATOR.isValid(new SecureString(userInfo))){
178                         logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.deletePortalAdmin not valid userId");
179                         return null;
180                 }
181
182                 int userIdIdx = userInfo.indexOf("-");
183                 Long userId = null;
184                 String sbcid = null;
185                 FieldsValidator fieldsValidator = null;
186                 try {
187                         if (userIdIdx == -1) {
188                                 logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin missing userId");
189                                 return fieldsValidator;
190                         } else {
191                                 String userIdStr = userInfo.substring(0, userIdIdx);
192                                 userId = Long.valueOf(userIdStr);
193                                 sbcid = userInfo.substring(userIdIdx + 1, userInfo.length());
194                         }
195                 } catch (Exception e) {
196                         logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin error while parsing the userInfo", e);
197                 }
198                 EPUser user = EPUserUtils.getUserSession(request);
199                 if (!adminRolesService.isSuperAdmin(user)) {
200                         EcompPortalUtils.setBadPermissions(user, response, "deletePortalAdmin");
201                 } else {
202                         fieldsValidator = portalAdminService.deletePortalAdmin(userId);
203                         int statusCode = fieldsValidator.httpStatusCode.intValue();
204                         response.setStatus(statusCode);
205                         if (statusCode == 200) {
206                                 AuditLog auditLog = new AuditLog();
207                                 auditLog.setUserId(user.getId());
208                                 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN);
209                                 auditLog.setAffectedRecordId(sbcid);
210                                 auditService.logActivity(auditLog, null);
211                                 
212                                 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
213                                 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
214                                 EcompPortalUtils.calculateDateTimeDifferenceForLog(
215                                                 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
216                                                 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
217                                 logger.info(EELFLoggerDelegate.auditLogger,
218                                                 EPLogUtil.formatAuditLogMessage("PortalAdminController.deletePortalAdmin",
219                                                                 EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN, user.getOrgUserId(), sbcid,
220                                                                 "A Portal Admin has been deleted"));
221                                 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
222                                 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
223                                 MDC.remove(SystemProperties.MDC_TIMER);
224                         }
225                 }
226                 EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "DELETE result =", response.getStatus());
227
228                 return fieldsValidator;
229         }
230
231         @GetMapping(value = {
232                         "/portalApi/adminAppsRoles/{appId}" }, produces = "application/json")
233         public List<EPRole> getRolesByApp(HttpServletRequest request, @PathVariable("appId") Long appId,
234                         HttpServletResponse response) {
235                 EPUser user = EPUserUtils.getUserSession(request);
236                 List<EPRole> rolesByApp = null;
237
238                 try {
239                         if (user == null) {
240                                 EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
241                         } else {
242                                 rolesByApp = adminRolesService.getRolesByApp(user, appId);
243                         }
244                 } catch (Exception e) {
245                         logger.error(EELFLoggerDelegate.errorLogger,    "getRolesByApp failed", e);
246                 }
247
248                 return rolesByApp;
249         }
250
251 }