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