2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017-2018 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.portalsdk.external.authorization.service;
40 import java.io.IOException;
41 import java.util.ArrayList;
42 import java.util.List;
44 import java.util.TreeSet;
46 import javax.naming.NamingException;
47 import javax.servlet.http.HttpServletRequest;
49 import org.json.JSONArray;
50 import org.json.JSONObject;
51 import org.onap.portalsdk.core.command.PostSearchBean;
52 import org.onap.portalsdk.core.command.support.SearchResult;
53 import org.onap.portalsdk.core.domain.App;
54 import org.onap.portalsdk.core.domain.Role;
55 import org.onap.portalsdk.core.domain.RoleFunction;
56 import org.onap.portalsdk.core.domain.User;
57 import org.onap.portalsdk.core.domain.UserApp;
58 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
59 import org.onap.portalsdk.core.service.AppService;
60 import org.onap.portalsdk.core.service.DataAccessService;
61 import org.onap.portalsdk.core.service.LdapService;
62 import org.onap.portalsdk.core.service.PostSearchService;
63 import org.onap.portalsdk.external.authorization.domain.ExternalAccessPerms;
64 import org.onap.portalsdk.external.authorization.domain.ExternalAccessRole;
65 import org.onap.portalsdk.external.authorization.domain.ExternalAccessRoleDescription;
66 import org.onap.portalsdk.external.authorization.domain.ExternalAccessUserRoleDetail;
67 import org.onap.portalsdk.external.authorization.exception.UserNotFoundException;
68 import org.onap.portalsdk.external.authorization.util.EcompExternalAuthProperties;
69 import org.onap.portalsdk.external.authorization.util.EcompExternalAuthUtils;
70 import org.springframework.beans.factory.annotation.Autowired;
71 import org.springframework.http.HttpEntity;
72 import org.springframework.http.HttpHeaders;
73 import org.springframework.http.HttpMethod;
74 import org.springframework.http.ResponseEntity;
75 import org.springframework.stereotype.Service;
76 import org.springframework.web.client.RestTemplate;
78 import com.fasterxml.jackson.core.JsonParseException;
79 import com.fasterxml.jackson.databind.JsonMappingException;
80 import com.fasterxml.jackson.databind.ObjectMapper;
81 import com.fasterxml.jackson.databind.type.TypeFactory;
83 @Service("userApiService")
84 public class UserApiServiceImpl implements UserApiService {
86 private static final String PASSCODE = "password";
88 private static final String ID = "id";
90 private static final String EXTERNAL_AUTH_GET_USER_ROLES_ENDPOINT = "authz/roles/user/";
92 private static final String EXTERNAL_AUTH_GET_USER_PERMS_ENDPOINT = "authz/perms/user/";
94 private static final String EXTERNAL_AUTH_POST_CREDENTIALS_ENDPOINT = "authn/validate";
96 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserApiServiceImpl.class);
99 private LoginExternalAuthService loginAAFService;
102 private LdapService ldapService;
105 private PostSearchService postSearchService;
108 private DataAccessService dataAccessService;
110 RestTemplate template = new RestTemplate();
113 private AppService appService;
116 public User getUser(String orgUserId, HttpServletRequest request) throws UserNotFoundException {
119 String namespace = EcompExternalAuthProperties
120 .getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_NAMESPACE);
121 HttpHeaders headers = getBasicAuthHeaders();
122 HttpEntity<String> entity = new HttpEntity<>(headers);
123 logger.debug(EELFLoggerDelegate.debugLogger, "getUserRoles: Connecting to external auth system for user {}",
125 String endPoint = EXTERNAL_AUTH_GET_USER_ROLES_ENDPOINT + orgUserId
126 + EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_DOMAIN);
127 ResponseEntity<String> getResponse = template.exchange(
128 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL) + endPoint,
129 HttpMethod.GET, entity, String.class);
130 if (getResponse.getStatusCode().value() == 200) {
131 logger.debug(EELFLoggerDelegate.debugLogger,
132 "getUserRoles: Finished GET user app roles from external auth system and body: {}",
133 getResponse.getBody());
135 String userRoles = getResponse.getBody();
136 ObjectMapper mapper = new ObjectMapper();
137 List<ExternalAccessUserRoleDetail> userRoleDetailList = setExternalAccessUserRoles(namespace, userRoles,
140 if (userRoleDetailList.isEmpty()) {
141 throw new UserNotFoundException("User roles not found!");
143 user = convertAAFUserRolesToEcompSDKUser(userRoleDetailList, orgUserId, namespace, request);
145 } catch (Exception e) {
146 logger.error(EELFLoggerDelegate.errorLogger, "getUser: Failed! ", e);
152 private List<ExternalAccessUserRoleDetail> setExternalAccessUserRoles(String namespace, String userRoles,
153 ObjectMapper mapper) throws IOException, JsonParseException, JsonMappingException, UserNotFoundException {
154 JSONObject userJsonObj;
155 JSONArray userJsonArray;
156 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
157 if (!userRoles.equals(EcompExternalAuthUtils.EXT_EMPTY_JSON_STRING)) {
158 userJsonObj = new JSONObject(userRoles);
159 userJsonArray = userJsonObj.getJSONArray(EcompExternalAuthUtils.EXT_ROLE_FIELD);
160 ExternalAccessUserRoleDetail userRoleDetail = null;
161 for (int i = 0; i < userJsonArray.length(); i++) {
162 JSONObject role = userJsonArray.getJSONObject(i);
163 if (!role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME)
164 .endsWith(EcompExternalAuthUtils.EXT_ROLE_FIELD_ADMIN)
165 && !role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME)
166 .endsWith(EcompExternalAuthUtils.EXT_ROLE_FIELD_OWNER)) {
167 ExternalAccessRoleDescription ecDesc = new ExternalAccessRoleDescription();
168 if (role.has(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION) && EcompExternalAuthUtils
169 .isJSONValid(role.getString(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION))) {
170 ecDesc = mapper.readValue(role.getString(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION),
171 ExternalAccessRoleDescription.class);
173 List<ExternalAccessPerms> ecPerms = new ArrayList<>();
174 if (role.has(EcompExternalAuthUtils.EXT_FIELD_PERMS)) {
175 JSONArray perms = role.getJSONArray(EcompExternalAuthUtils.EXT_FIELD_PERMS);
176 ecPerms = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
177 .constructCollectionType(List.class, ExternalAccessPerms.class));
179 ExternalAccessRole ecRole = new ExternalAccessRole(
180 role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME), ecPerms, ecDesc);
181 userRoleDetail = new ExternalAccessUserRoleDetail(ecRole);
182 userRoleDetailList.add(userRoleDetail);
186 throw new UserNotFoundException("User roles not found!");
188 return userRoleDetailList;
191 private User convertAAFUserRolesToEcompSDKUser(List<ExternalAccessUserRoleDetail> userRoleDetailList,
192 String orgUserId, String namespace, HttpServletRequest request) throws Exception {
193 User user = loginAAFService.findUserWithoutPwd(orgUserId);
194 PostSearchBean postSearchBean = new PostSearchBean();
196 postSearchBean.setOrgUserId(orgUserId);
197 postSearchService.process(request, postSearchBean);
198 postSearchBean.setSearchResult(loadSearchResultData(postSearchBean));
199 user = (User) postSearchBean.getSearchResult().get(0);
200 user.setActive(true);
201 user.setLoginId(orgUserId);
202 dataAccessService.saveDomainObject(user, null);
204 App app = appService.getApp(1l);
206 Set userApps = setUserApps(userRoleDetailList, namespace, user, app);
207 user.setUserApps(userApps);
208 } catch (Exception e) {
209 logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
216 @SuppressWarnings({ "rawtypes", "unchecked" })
217 private Set setUserApps(List<ExternalAccessUserRoleDetail> userRoleDetailList, String namespace, User user,
219 Set userApps = new TreeSet();
220 for (ExternalAccessUserRoleDetail userRoleDetail : userRoleDetailList) {
221 ExternalAccessRole ecRole = userRoleDetail.getRole();
222 ExternalAccessRoleDescription roleDesc = ecRole.getDescription();
223 UserApp userApp = new UserApp();
224 Role role = new Role();
225 Set roleFunctions = new TreeSet<>();
226 if (roleDesc.getName() == null) {
227 role.setActive(true);
228 role.setName(ecRole.getName());
230 role.setActive(Boolean.valueOf(roleDesc.getActive()));
231 role.setId(Long.valueOf(roleDesc.getAppRoleId()));
232 role.setName(roleDesc.getName());
233 if (!roleDesc.getPriority().equals(EcompExternalAuthUtils.EXT_NULL_VALUE)) {
234 role.setPriority(Integer.valueOf(roleDesc.getPriority()));
237 for (ExternalAccessPerms extPerm : ecRole.getPerms()) {
238 RoleFunction roleFunction = new RoleFunction();
239 roleFunction.setCode(extPerm.getInstance());
240 roleFunction.setAction(extPerm.getAction());
241 if (extPerm.getDescription() != null) {
242 roleFunction.setName(extPerm.getDescription());
244 roleFunction.setType(extPerm.getType());
245 roleFunctions.add(roleFunction);
247 role.setRoleFunctions(roleFunctions);
249 userApp.setRole(role);
250 userApp.setUserId(user.getId());
251 userApps.add(userApp);
257 public List<RoleFunction> getRoleFunctions(String orgUserId) throws Exception {
258 ObjectMapper mapper = new ObjectMapper();
259 HttpHeaders headers = getBasicAuthHeaders();
260 HttpEntity<String> entity = new HttpEntity<>(headers);
261 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFunctions: Connecting to external auth system for user {}",
263 String endPoint = EXTERNAL_AUTH_GET_USER_PERMS_ENDPOINT + orgUserId
264 + EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_DOMAIN);
265 ResponseEntity<String> getResponse = template.exchange(
266 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL) + endPoint,
267 HttpMethod.GET, entity, String.class);
268 if (getResponse.getStatusCode().value() == 200) {
269 logger.debug(EELFLoggerDelegate.debugLogger,
270 "getRoleFunctions: Finished GET user perms from external system and body: {}",
271 getResponse.getBody());
273 String userPerms = getResponse.getBody();
274 List<ExternalAccessPerms> extPermsList = convertPermsJSONArrayToExternalAccessPerms(mapper, userPerms);
275 return convertToRoleFunctionList(extPermsList);
278 private List<ExternalAccessPerms> convertPermsJSONArrayToExternalAccessPerms(ObjectMapper mapper, String userPerms)
279 throws IOException, JsonParseException, JsonMappingException {
280 JSONObject userPermsJsonObj = null;
281 JSONArray userPermsJsonArray = null;
282 List<ExternalAccessPerms> extPermsList = new ArrayList<>();
283 if (!userPerms.equals(EcompExternalAuthUtils.EXT_EMPTY_JSON_STRING)) {
284 userPermsJsonObj = new JSONObject(userPerms);
285 userPermsJsonArray = userPermsJsonObj.getJSONArray(EcompExternalAuthUtils.EXT_PERM_FIELD);
286 for (int i = 0; i < userPermsJsonArray.length(); i++) {
287 JSONObject permJsonObj = userPermsJsonArray.getJSONObject(i);
288 if (!permJsonObj.getString(EcompExternalAuthUtils.EXT_PERM_FIELD_TYPE)
289 .endsWith(EcompExternalAuthUtils.EXT_PERM_ACCESS)) {
290 ExternalAccessPerms perm = mapper.readValue(permJsonObj.toString(), ExternalAccessPerms.class);
291 extPermsList.add(perm);
298 private ResponseEntity<String> getPermsFromExternalAuthSystem(HttpEntity<String> entity, String endPoint) {
299 ResponseEntity<String> getResponse = template.exchange(
300 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL) + endPoint,
301 HttpMethod.GET, entity, String.class);
302 if (getResponse.getStatusCode().value() == 200) {
303 logger.debug(EELFLoggerDelegate.debugLogger,
304 "getPermsFromExternalAuthSystem: Finished GET user perms from external auth system and body: {}",
305 getResponse.getBody());
310 private HttpHeaders getBasicAuthHeaders() throws Exception {
311 String userName = EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_NAME);
312 String encryptedPass = EcompExternalAuthProperties
313 .getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_PASSWORD);
314 String decryptedPass = EcompExternalAuthUtils.decryptPass(encryptedPass);
315 return EcompExternalAuthUtils.base64encodeKeyForAAFBasicAuth(userName, decryptedPass);
318 private List<RoleFunction> convertToRoleFunctionList(List<ExternalAccessPerms> extPermsList) {
319 List<RoleFunction> roleFunctions = new ArrayList<>();
320 String namespace = EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_NAMESPACE);
321 for (ExternalAccessPerms extPerm : extPermsList) {
322 RoleFunction roleFunction = new RoleFunction();
323 roleFunction.setCode(extPerm.getInstance());
324 roleFunction.setAction(extPerm.getAction());
325 if (extPerm.getDescription() != null) {
326 roleFunction.setName(extPerm.getDescription());
328 roleFunction.setType(extPerm.getType());
329 roleFunctions.add(roleFunction);
331 return roleFunctions;
334 private SearchResult loadSearchResultData(PostSearchBean searchCriteria) throws NamingException {
335 return ldapService.searchPost(searchCriteria.getUser(), searchCriteria.getSortBy1(),
336 searchCriteria.getSortBy2(), searchCriteria.getSortBy3(), searchCriteria.getPageNo(),
337 searchCriteria.getNewDataSize(), 1);
341 public ResponseEntity<String> checkUserExists(String username, String password) throws Exception {
342 username = changeIfUserDomainNotAppended(username);
343 HttpHeaders headers = EcompExternalAuthUtils.base64encodeKeyForAAFBasicAuth(username, password);
344 String appUsername = EcompExternalAuthProperties
345 .getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_NAME);
346 String appPass = EcompExternalAuthUtils.decryptPass(
347 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_PASSWORD));
348 JSONObject credentials = new JSONObject();
349 credentials.put(ID, appUsername);
350 credentials.put(PASSCODE, appPass);
351 HttpEntity<String> entity = new HttpEntity<>(credentials.toString(), headers);
352 logger.debug(EELFLoggerDelegate.debugLogger, "checkUserExists: Connecting to external auth system for user {}",
354 ResponseEntity<String> getResponse = template
355 .exchange(EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL)
356 + EXTERNAL_AUTH_POST_CREDENTIALS_ENDPOINT, HttpMethod.POST, entity, String.class);
357 if (getResponse.getStatusCode().value() == 200) {
358 logger.debug(EELFLoggerDelegate.debugLogger,
359 "checkUserExists: Finished POST from external auth system to validate credentials and status: {}",
360 getResponse.getStatusCode().value());
365 private String changeIfUserDomainNotAppended(String username) {
366 if (!EcompExternalAuthUtils.validate(username)) {
368 + EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_DOMAIN);
374 public List<ExternalAccessPerms> getIfUserPermsExists(String username) throws Exception {
375 HttpHeaders headers = getBasicAuthHeaders();
376 HttpEntity<String> entity = new HttpEntity<>(headers);
377 logger.debug(EELFLoggerDelegate.debugLogger,
378 "getIfUserPermsExists: Connecting to external auth system for user {}", username);
379 username = changeIfUserDomainNotAppended(username);
380 String endPoint = EXTERNAL_AUTH_GET_USER_PERMS_ENDPOINT + username;
381 ResponseEntity<String> getResponse = getPermsFromExternalAuthSystem(entity, endPoint);
382 return convertPermsJSONArrayToExternalAccessPerms(new ObjectMapper(), getResponse.getBody());