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