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.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;
75 import com.fasterxml.jackson.databind.ObjectMapper;
77 @Service("portalAdminService")
78 @org.springframework.context.annotation.Configuration
79 @EnableAspectJAutoProxy
81 public class PortalAdminServiceImpl implements PortalAdminService {
83 private String SYS_ADMIN_ROLE_ID = "1";
84 private String ECOMP_APP_ID = "1";
86 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminServiceImpl.class);
89 private SessionFactory sessionFactory;
91 private DataAccessService dataAccessService;
93 SearchService searchService;
95 private EPAppService epAppService;
97 RestTemplate template = new RestTemplate();
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);
105 public List<PortalAdmin> getPortalAdmins() {
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",
112 logger.debug(EELFLoggerDelegate.debugLogger, "getPortalAdmins was successful");
114 } catch (Exception e) {
115 logger.error(EELFLoggerDelegate.errorLogger, "getPortalAdmins failed", e);
120 public FieldsValidator createPortalAdmin(String orgUserId) {
121 FieldsValidator fieldsValidator = new FieldsValidator();
122 logger.debug(EELFLoggerDelegate.debugLogger, "LR: createPortalAdmin: orgUserId is {}", orgUserId);
124 boolean createNewUser = false;
125 List<EPUser> localUserList = getUserListWithOrguseId(orgUserId);
126 if (!localUserList.isEmpty()) {
127 user = localUserList.get(0);
129 createNewUser = true;
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;
140 localSession = sessionFactory.openSession();
142 transaction = localSession.beginTransaction();
144 user = this.searchService.searchUserByUserId(orgUserId);
146 // insert the user with active true in order to
148 user.setActive(true);
149 localSession.save(EPUser.class.getName(), user);
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);
159 localSession.save(PortalAdminUserRole.class.getName(), userRole);
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);
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);
172 EcompPortalUtils.closeLocalSession(localSession, "createPortalAdmin");
175 return fieldsValidator;
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);
186 private void addPortalAdminInExternalCentralAuth(String loginId, String portalAdminRole) throws Exception{
189 if (EPCommonSystemProperties.containsProperty(
190 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
191 name = loginId + SystemProperties
192 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
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();
201 HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
203 SystemProperties.getProperty(
204 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
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());
212 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e);
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;
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);
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);
238 EcompPortalUtils.closeLocalSession(localSession, "deletePortalAdmin");
240 return fieldsValidator;
244 private void deletePortalAdminInExternalCentralAuth(Long userId, String portalAdminRole) throws Exception{
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);
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);
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());
266 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e);
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);
280 private void logQuery(String sql) {
281 logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
284 private boolean isLoggedInUserPortalAdmin(Long userId) {
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;
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) {
300 } catch (Exception e) {
301 logger.error(EELFLoggerDelegate.errorLogger, "isLoggedInUserPortalAdmin failed", e);