10490e731fad3344fa0b514d5bde9d908bbc61a6
[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                                 if(user != null)
148                                         result = addPortalAdminInExternalCentralAuth(user.getOrgUserId(), PortalConstants.PORTAL_ADMIN_ROLE);
149                                 else
150                                         logger.error(EELFLoggerDelegate.errorLogger, "PortalAdminServiceImpl createPortalAdmin: failed to Add role in the external central auth system since User obj is null" );
151                         } catch (Exception e) {
152                                 EcompPortalUtils.rollbackTransaction(transaction, "createPortalAdmin rollback, exception = " + e);
153                                 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
154                         } finally {
155                                 EcompPortalUtils.closeLocalSession(localSession, "createPortalAdmin");
156                         }
157                         if (!result) {
158                                 logger.debug(EELFLoggerDelegate.debugLogger,
159                                                 "LR: createPortalAdmin: no result. setting httpStatusCode to "
160                                                                 + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
161                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
162                                 logger.error(EELFLoggerDelegate.errorLogger, "PortalAdminServiceImpl.createPortalAdmin: bad request");
163                         }
164                 }
165                 return fieldsValidator;
166         }
167         
168         private boolean addPortalAdminInExternalCentralAuth(String loginId, String portalAdminRole){
169                 boolean result = false;
170                 try{
171                         String name = "";
172                         if (EPCommonSystemProperties.containsProperty(
173                                         EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
174                                 name = loginId + SystemProperties
175                                                 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
176                         }
177                         EPApp app = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
178                         String extRole = app.getNameSpace()+"."+portalAdminRole.replaceAll(" ", "_");
179                         ObjectMapper addUserRoleMapper = new ObjectMapper();
180                         ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
181                         String userRole = addUserRoleMapper.writeValueAsString(extUser);
182                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
183
184                         HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
185                         template.exchange(
186                                         SystemProperties.getProperty(
187                                                         EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
188                                                         + "userRole",
189                                         HttpMethod.POST, addUserRole, String.class);
190                         result = true;
191                 } catch (Exception e) {
192                         // This happens only if role already exists in external central access system but not in local DB thats where we logging here
193                         if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
194                                 result = true;
195                                 logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already exists", e.getMessage());
196                         } else{
197                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e);
198                                 result = false;
199                         }
200                 }
201                 return result;
202         }
203
204         public FieldsValidator deletePortalAdmin(Long userId) {
205                 FieldsValidator fieldsValidator = new FieldsValidator();
206                 logger.debug(EELFLoggerDelegate.debugLogger, "deletePortalAdmin: test 1");
207                 boolean result = false;
208                 Session localSession = null;
209                 Transaction transaction = null;
210
211                 try {
212                         localSession = sessionFactory.openSession();
213                         transaction = localSession.beginTransaction();
214                         dataAccessService.deleteDomainObjects(PortalAdminUserRole.class,
215                                         "user_id='" + userId + "' AND role_id='" + SYS_ADMIN_ROLE_ID + "'", null);
216                         transaction.commit();
217                         result = deletePortalAdminInExternalCentralAuth(userId, PortalConstants.PORTAL_ADMIN_ROLE);
218                 } catch (Exception e) {
219                         EcompPortalUtils.rollbackTransaction(transaction, "deletePortalAdmin rollback, exception = " + e);
220                         logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
221                 } finally {
222                         EcompPortalUtils.closeLocalSession(localSession, "deletePortalAdmin");
223                 }
224                 if (result) {
225                 } else {
226                         logger.debug(EELFLoggerDelegate.debugLogger, "deletePortalAdmin: no result. setting httpStatusCode to "
227                                         + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
228                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
229                 }
230                 return fieldsValidator;
231         }
232
233         
234         @SuppressWarnings("unchecked")
235         private boolean deletePortalAdminInExternalCentralAuth(Long userId, String portalAdminRole){
236                 boolean result = false;
237                 try{                                                                    
238                         String name = "";
239                         List<EPUser> localUserList = dataAccessService.getList(EPUser.class, " where user_id = " + userId,
240                                         null, null);
241                         if (EPCommonSystemProperties.containsProperty(
242                                         EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
243                                 name = localUserList.get(0).getOrgUserId() + SystemProperties
244                                                 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
245                         }
246                         EPApp app = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
247                         String extRole = app.getNameSpace()+"."+portalAdminRole.replaceAll(" ", "_");
248                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
249                         HttpEntity<String> addUserRole = new HttpEntity<>(headers);
250                         template.exchange(
251                                         SystemProperties.getProperty(
252                                                         EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
253                                                         + "userRole/"+name+"/"+extRole,
254                                         HttpMethod.DELETE, addUserRole, String.class);
255                         result = true;
256                 } catch (Exception e) {
257                         if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
258                                 logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already deleted or may not be found", e.getMessage());
259                         } else{
260                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e);
261                                 result = false;
262                         }
263                 }
264                 return result;
265         }
266         
267         private void logQuery(String sql) {
268                 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
269         }
270
271         private boolean isLoggedInUserPortalAdmin(Long userId) {
272                 try {
273                         String sql = "SELECT u.user_id, u.first_name, u.last_name, u.login_id "
274                                         + " FROM fn_user u, fn_user_role ur " + " WHERE u.user_id = ur.user_id " + " AND ur.user_id="
275                                         + userId + " AND ur.role_id=" + SYS_ADMIN_ROLE_ID;
276
277                         logQuery(sql);
278
279                         @SuppressWarnings("unchecked")
280                         List<PortalAdmin> portalAdmins = dataAccessService.executeSQLQuery(sql, PortalAdmin.class, null);
281                         logger.debug(EELFLoggerDelegate.debugLogger, portalAdmins.toString());
282                         if (portalAdmins == null || portalAdmins.size() <= 0) {
283                                 return false;
284                         }
285                         return true;
286
287                 } catch (Exception e) {
288                         logger.error(EELFLoggerDelegate.errorLogger,
289                                         "Exception occurred while performing isLoggedInUserPortalAdmin operation, Details: "
290                                                         + EcompPortalUtils.getStackTrace(e));
291                         return false;
292                 }
293         }
294 }