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