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