Update license; improve coverage; add docs dir
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / PortalAdminServiceImpl.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright © 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.openecomp.portalapp.portal.service;
39
40 import java.util.HashMap;
41 import java.util.List;
42 import java.util.Map;
43
44 import javax.annotation.PostConstruct;
45 import javax.servlet.http.HttpServletResponse;
46
47 import org.hibernate.Session;
48 import org.hibernate.SessionFactory;
49 import org.hibernate.Transaction;
50 import org.openecomp.portalapp.portal.domain.EPApp;
51 import org.openecomp.portalapp.portal.domain.EPUser;
52 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
53 import org.openecomp.portalapp.portal.transport.ExternalAccessUser;
54 import org.openecomp.portalapp.portal.transport.FieldsValidator;
55 import org.openecomp.portalapp.portal.transport.PortalAdmin;
56 import org.openecomp.portalapp.portal.transport.PortalAdminUserRole;
57 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
58 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
59 import org.openecomp.portalapp.portal.utils.PortalConstants;
60 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
61 import org.openecomp.portalsdk.core.service.DataAccessService;
62 import org.openecomp.portalsdk.core.util.SystemProperties;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.context.annotation.EnableAspectJAutoProxy;
65 import org.springframework.http.HttpEntity;
66 import org.springframework.http.HttpHeaders;
67 import org.springframework.http.HttpMethod;
68 import org.springframework.stereotype.Service;
69 import org.springframework.web.client.RestTemplate;
70
71 import com.fasterxml.jackson.databind.ObjectMapper;
72
73 @Service("portalAdminService")
74 @org.springframework.context.annotation.Configuration
75 @EnableAspectJAutoProxy
76 @EPMetricsLog
77 public class PortalAdminServiceImpl implements PortalAdminService {     
78
79         private String SYS_ADMIN_ROLE_ID = "1";
80         private String ECOMP_APP_ID = "1";
81
82         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminServiceImpl.class);
83
84         @Autowired
85         private SessionFactory sessionFactory;
86         @Autowired
87         private DataAccessService dataAccessService;
88         @Autowired
89         SearchService searchService;
90         @Autowired
91         private EPAppService epAppService;
92         
93         RestTemplate template = new RestTemplate();
94         
95         @PostConstruct
96         private void init() {
97                 SYS_ADMIN_ROLE_ID = SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID);
98                 ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
99         }
100
101         public List<PortalAdmin> getPortalAdmins() {
102                 try {
103                         Map<String, String> params = new HashMap<>();
104                         params.put("adminRoleId", SYS_ADMIN_ROLE_ID);
105                         @SuppressWarnings("unchecked")
106                         List<PortalAdmin> portalAdmins = (List<PortalAdmin>) dataAccessService.executeNamedQuery("getPortalAdmins",
107                                         params, null);
108                         logger.debug(EELFLoggerDelegate.debugLogger, "getPortalAdmins was successful");
109                         return portalAdmins;
110                 } catch (Exception e) {
111                         logger.error(EELFLoggerDelegate.errorLogger, "getPortalAdmins failed", e);
112                         return null;
113                 }
114         }
115
116         @SuppressWarnings("unchecked")
117         public FieldsValidator createPortalAdmin(String orgUserId) {
118                 FieldsValidator fieldsValidator = new FieldsValidator();
119                 logger.debug(EELFLoggerDelegate.debugLogger, "LR: createPortalAdmin: test 1");
120                 boolean result = false;
121                 EPUser user = null;
122                 boolean createNewUser = false;
123                 List<EPUser> localUserList = dataAccessService.getList(EPUser.class, " where orgUserId='" + orgUserId + "'",
124                                 null, null);
125                 if (localUserList.size() > 0) {
126                         user = localUserList.get(0);
127                 } else {
128                         createNewUser = true;
129                 }
130
131                 if (user != null && isLoggedInUserPortalAdmin(user.getId())) {
132                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
133                         logger.error(EELFLoggerDelegate.errorLogger,
134                                         "User '" + user.getOrgUserId() + "' already has PortalAdmin role assigned.");
135                 } else if (user != null || createNewUser) {
136                         Session localSession = null;
137                         Transaction transaction = null;
138                         try {
139                                 localSession = sessionFactory.openSession();
140
141                                 transaction = localSession.beginTransaction();
142                                 if (createNewUser) {
143                                         user = this.searchService.searchUserByUserId(orgUserId);
144                                         if (user != null) {
145                                                 // insert the user with active true in order to
146                                                 // pass login phase.
147                                                 user.setActive(true);
148                                                 localSession.save(EPUser.class.getName(), user);
149                                         }
150                                 }
151                                 if (user != null) {
152                                         Long userid = user.getId();
153                                         PortalAdminUserRole userRole = new PortalAdminUserRole();
154                                         userRole.userId = userid;
155                                         userRole.roleId = Long.valueOf(SYS_ADMIN_ROLE_ID);
156                                         userRole.appId = Long.valueOf(ECOMP_APP_ID);
157
158                                         localSession.save(PortalAdminUserRole.class.getName(), userRole);
159                                 }
160
161                                 transaction.commit();
162                                 // Add role in the external central auth system
163                                 if(user != null)
164                                         result = addPortalAdminInExternalCentralAuth(user.getOrgUserId(), PortalConstants.PORTAL_ADMIN_ROLE);
165                                 else
166                                         logger.error(EELFLoggerDelegate.errorLogger, "PortalAdminServiceImpl createPortalAdmin: failed to Add role in the external central auth system since User obj is null" );
167                         } catch (Exception e) {
168                                 logger.error(EELFLoggerDelegate.errorLogger, "createPortalAdmin failed", e);
169                                 EcompPortalUtils.rollbackTransaction(transaction, "createPortalAdmin rollback, exception = " + e.toString());
170                         } finally {
171                                 EcompPortalUtils.closeLocalSession(localSession, "createPortalAdmin");
172                         }
173                         if (!result) {
174                                 logger.debug(EELFLoggerDelegate.debugLogger,
175                                                 "LR: createPortalAdmin: no result. setting httpStatusCode to "
176                                                                 + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
177                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
178                                 logger.error(EELFLoggerDelegate.errorLogger, "PortalAdminServiceImpl.createPortalAdmin: bad request");
179                         }
180                 }
181                 return fieldsValidator;
182         }
183         
184         private boolean addPortalAdminInExternalCentralAuth(String loginId, String portalAdminRole){
185                 boolean result = false;
186                 try{
187                         String name = "";
188                         if (EPCommonSystemProperties.containsProperty(
189                                         EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
190                                 name = loginId + SystemProperties
191                                                 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
192                         }
193                         EPApp app = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
194                         String extRole = app.getNameSpace()+"."+portalAdminRole.replaceAll(" ", "_");
195                         ObjectMapper addUserRoleMapper = new ObjectMapper();
196                         ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
197                         String userRole = addUserRoleMapper.writeValueAsString(extUser);
198                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
199
200                         HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
201                         template.exchange(
202                                         SystemProperties.getProperty(
203                                                         EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
204                                                         + "userRole",
205                                         HttpMethod.POST, addUserRole, String.class);
206                         result = true;
207                 } catch (Exception e) {
208                         // This happens only if role already exists in external central access system but not in local DB thats where we logging here
209                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
210                                 result = true;
211                                 logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already exists", e.getMessage());
212                         } else{
213                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e);
214                                 result = false;
215                         }
216                 }
217                 return result;
218         }
219
220         public FieldsValidator deletePortalAdmin(Long userId) {
221                 FieldsValidator fieldsValidator = new FieldsValidator();
222                 logger.debug(EELFLoggerDelegate.debugLogger, "deletePortalAdmin: test 1");
223                 boolean result = false;
224                 Session localSession = null;
225                 Transaction transaction = null;
226
227                 try {
228                         localSession = sessionFactory.openSession();
229                         transaction = localSession.beginTransaction();
230                         dataAccessService.deleteDomainObjects(PortalAdminUserRole.class,
231                                         "user_id='" + userId + "' AND role_id='" + SYS_ADMIN_ROLE_ID + "'", null);
232                         transaction.commit();
233                         result = deletePortalAdminInExternalCentralAuth(userId, PortalConstants.PORTAL_ADMIN_ROLE);
234                 } catch (Exception e) {
235                         logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin failed", e);
236                         EcompPortalUtils.rollbackTransaction(transaction, "deletePortalAdmin rollback, exception = " + e.toString());
237                 } finally {
238                         EcompPortalUtils.closeLocalSession(localSession, "deletePortalAdmin");
239                 }
240                 if (result) {
241                 } else {
242                         logger.debug(EELFLoggerDelegate.debugLogger, "deletePortalAdmin: no result. setting httpStatusCode to "
243                                         + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
244                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
245                 }
246                 return fieldsValidator;
247         }
248
249         
250         @SuppressWarnings("unchecked")
251         private boolean deletePortalAdminInExternalCentralAuth(Long userId, String portalAdminRole){
252                 boolean result = false;
253                 try{                                                                    
254                         String name = "";
255                         List<EPUser> localUserList = dataAccessService.getList(EPUser.class, " where user_id = " + userId,
256                                         null, null);
257                         if (EPCommonSystemProperties.containsProperty(
258                                         EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
259                                 name = localUserList.get(0).getOrgUserId() + SystemProperties
260                                                 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
261                         }
262                         EPApp app = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
263                         String extRole = app.getNameSpace()+"."+portalAdminRole.replaceAll(" ", "_");
264                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
265                         HttpEntity<String> addUserRole = new HttpEntity<>(headers);
266                         template.exchange(
267                                         SystemProperties.getProperty(
268                                                         EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
269                                                         + "userRole/"+name+"/"+extRole,
270                                         HttpMethod.DELETE, addUserRole, String.class);
271                         result = true;
272                 } catch (Exception e) {
273                         if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
274                                 logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already deleted or may not be found", e.getMessage());
275                         } else{
276                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e);
277                                 result = false;
278                         }
279                 }
280                 return result;
281         }
282         
283         private void logQuery(String sql) {
284                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
285         }
286
287         private boolean isLoggedInUserPortalAdmin(Long userId) {
288                 try {
289                         String sql = "SELECT u.user_id, u.first_name, u.last_name, u.login_id "
290                                         + " FROM fn_user u, fn_user_role ur " + " WHERE u.user_id = ur.user_id " + " AND ur.user_id="
291                                         + userId + " AND ur.role_id=" + SYS_ADMIN_ROLE_ID;
292
293                         logQuery(sql);
294
295                         @SuppressWarnings("unchecked")
296                         List<PortalAdmin> portalAdmins = dataAccessService.executeSQLQuery(sql, PortalAdmin.class, null);
297                         logger.debug(EELFLoggerDelegate.debugLogger, portalAdmins.toString());
298                         if (portalAdmins == null || portalAdmins.size() <= 0) {
299                                 return false;
300                         }
301                         return true;
302
303                 } catch (Exception e) {
304                         logger.error(EELFLoggerDelegate.errorLogger, "isLoggedInUserPortalAdmin failed", e);
305                         return false;
306                 }
307         }
308 }