2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.service;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.List;
45 import javax.annotation.PostConstruct;
46 import javax.servlet.http.HttpServletResponse;
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;
76 import com.fasterxml.jackson.databind.ObjectMapper;
78 @Service("portalAdminService")
79 @org.springframework.context.annotation.Configuration
80 @EnableAspectJAutoProxy
82 public class PortalAdminServiceImpl implements PortalAdminService {
84 private String SYS_ADMIN_ROLE_ID = "1";
85 private String ECOMP_APP_ID = "1";
87 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminServiceImpl.class);
90 private SessionFactory sessionFactory;
92 private DataAccessService dataAccessService;
94 SearchService searchService;
96 private EPAppService epAppService;
98 RestTemplate template = new RestTemplate();
101 ExternalAccessRolesService externalAccessRolesService;
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);
109 public List<PortalAdmin> getPortalAdmins() {
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",
116 logger.debug(EELFLoggerDelegate.debugLogger, "getPortalAdmins was successful");
118 } catch (Exception e) {
119 logger.error(EELFLoggerDelegate.errorLogger, "getPortalAdmins failed", e);
124 public FieldsValidator createPortalAdmin(String orgUserId) {
125 FieldsValidator fieldsValidator = new FieldsValidator();
126 logger.debug(EELFLoggerDelegate.debugLogger, "LR: createPortalAdmin: orgUserId is {}", orgUserId);
128 boolean createNewUser = false;
129 List<EPUser> localUserList = getUserListWithOrguseId(orgUserId);
130 if (!localUserList.isEmpty()) {
131 user = localUserList.get(0);
133 createNewUser = true;
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;
144 localSession = sessionFactory.openSession();
146 transaction = localSession.beginTransaction();
148 user = this.searchService.searchUserByUserId(orgUserId);
150 // insert the user with active true in order to
152 user.setActive(true);
153 localSession.save(EPUser.class.getName(), user);
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);
163 localSession.save(PortalAdminUserRole.class.getName(), userRole);
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());
175 addPortalAdminInExternalCentralAuth(user.getOrgUserId(), role.getName());
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);
182 EcompPortalUtils.closeLocalSession(localSession, "createPortalAdmin");
185 return fieldsValidator;
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);
196 private void addPortalAdminInExternalCentralAuth(String loginId, String portalAdminRole) throws Exception{
199 if (EPCommonSystemProperties.containsProperty(
200 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
201 name = loginId + SystemProperties
202 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
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();
211 HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
213 SystemProperties.getProperty(
214 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
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());
222 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e);
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;
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()){
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());
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);
254 EcompPortalUtils.closeLocalSession(localSession, "deletePortalAdmin");
256 return fieldsValidator;
260 private void deletePortalAdminInExternalCentralAuth(Long userId, String portalAdminRole) throws Exception{
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);
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);
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());
282 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e);
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);
296 private void logQuery(String sql) {
297 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
300 private boolean isLoggedInUserPortalAdmin(Long userId) {
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;
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) {
316 } catch (Exception e) {
317 logger.error(EELFLoggerDelegate.errorLogger, "isLoggedInUserPortalAdmin failed", e);