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.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.ExternalAccessUserRoleDetail;
65 import org.onap.portalsdk.external.authorization.domain.ExternalRoleDescription;
66 import org.onap.portalsdk.external.authorization.exception.UserNotFoundException;
67 import org.onap.portalsdk.external.authorization.util.EcompExternalAuthProperties;
68 import org.onap.portalsdk.external.authorization.util.EcompExternalAuthUtils;
69 import org.springframework.beans.factory.annotation.Autowired;
70 import org.springframework.http.HttpEntity;
71 import org.springframework.http.HttpHeaders;
72 import org.springframework.http.HttpMethod;
73 import org.springframework.http.ResponseEntity;
74 import org.springframework.stereotype.Service;
75 import org.springframework.web.client.RestTemplate;
77 import com.fasterxml.jackson.core.JsonParseException;
78 import com.fasterxml.jackson.databind.JsonMappingException;
79 import com.fasterxml.jackson.databind.ObjectMapper;
80 import com.fasterxml.jackson.databind.type.TypeFactory;
82 @Service("userApiService")
83 public class UserApiServiceImpl implements UserApiService {
85 private static final String PASSCODE = "password";
87 private static final String ID = "id";
89 private static final String EXTERNAL_AUTH_GET_USER_ROLES_ENDPOINT = "authz/roles/user/";
91 private static final String EXTERNAL_AUTH_GET_USER_PERMS_ENDPOINT = "authz/perms/user/";
93 private static final String EXTERNAL_AUTH_POST_CREDENTIALS_ENDPOINT = "authn/validate";
95 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserApiServiceImpl.class);
98 private LoginExternalAuthService loginAAFService;
101 private LdapService ldapService;
104 private PostSearchService postSearchService;
107 private DataAccessService dataAccessService;
109 RestTemplate template = new RestTemplate();
112 private AppService appService;
115 public User getUser(String orgUserId, HttpServletRequest request) throws UserNotFoundException {
118 String namespace = EcompExternalAuthProperties
119 .getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_NAMESPACE);
120 HttpHeaders headers = getBasicAuthHeaders();
121 HttpEntity<String> entity = new HttpEntity<>(headers);
122 logger.debug(EELFLoggerDelegate.debugLogger, "getUserRoles: Connecting to external auth system for user {}",
124 String endPoint = EXTERNAL_AUTH_GET_USER_ROLES_ENDPOINT + orgUserId
125 + EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_DOMAIN);
126 ResponseEntity<String> getResponse = template.exchange(
127 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL) + endPoint,
128 HttpMethod.GET, entity, String.class);
129 if (getResponse.getStatusCode().value() == 200) {
130 logger.debug(EELFLoggerDelegate.debugLogger,
131 "getUserRoles: Finished GET unp ser roles from external auth system and body: {}",
132 getResponse.getBody());
134 String userRoles = getResponse.getBody();
135 ObjectMapper mapper = new ObjectMapper();
136 List<ExternalAccessUserRoleDetail> userRoleDetailList = setExterbalAccessUserRoles(namespace, userRoles,
139 if (userRoleDetailList.isEmpty()) {
140 throw new UserNotFoundException("User roles not found!");
142 user = convertAAFUserRolesToEcompSDKUser(userRoleDetailList, orgUserId, namespace, request);
144 } catch (Exception e) {
145 logger.error(EELFLoggerDelegate.errorLogger, "getUser: Failed! ", e);
151 private List<ExternalAccessUserRoleDetail> setExterbalAccessUserRoles(String namespace, String userRoles,
152 ObjectMapper mapper) throws IOException, JsonParseException, JsonMappingException, UserNotFoundException {
153 JSONObject userJsonObj;
154 JSONArray userJsonArray;
155 List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
156 if (!userRoles.equals(EcompExternalAuthUtils.EXT_EMPTY_JSON_STRING)) {
157 userJsonObj = new JSONObject(userRoles);
158 userJsonArray = userJsonObj.getJSONArray(EcompExternalAuthUtils.EXT_ROLE_FIELD);
159 ExternalAccessUserRoleDetail userRoleDetail = null;
160 for (int i = 0; i < userJsonArray.length(); i++) {
161 JSONObject role = userJsonArray.getJSONObject(i);
162 if (!role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME)
163 .endsWith(EcompExternalAuthUtils.EXT_ROLE_FIELD_ADMIN)
164 && !role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME)
165 .endsWith(EcompExternalAuthUtils.EXT_ROLE_FIELD_OWNER)
166 && EcompExternalAuthUtils.checkNameSpaceMatching(
167 role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME), namespace)) {
168 ExternalRoleDescription desc = new ExternalRoleDescription();
169 if (role.has(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION) && EcompExternalAuthUtils
170 .isJSONValid(role.getString(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION))) {
171 desc = mapper.readValue(role.getString(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION),
172 ExternalRoleDescription.class);
174 if (role.has(EcompExternalAuthUtils.EXT_FIELD_PERMS)) {
175 JSONArray perms = role.getJSONArray(EcompExternalAuthUtils.EXT_FIELD_PERMS);
176 List<ExternalAccessPerms> permsList = mapper.readValue(perms.toString(), TypeFactory
177 .defaultInstance().constructCollectionType(List.class, ExternalAccessPerms.class));
178 desc.setPermissions(permsList);
180 userRoleDetail = new ExternalAccessUserRoleDetail(
181 role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME), desc);
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 ExternalRoleDescription roleDesc = userRoleDetail.getDescription();
222 UserApp userApp = new UserApp();
223 Role role = new Role();
224 Set roleFunctions = new TreeSet<>();
225 if (roleDesc != null) {
226 if (roleDesc.getName() == null) {
227 role.setActive(true);
228 role.setName(userRoleDetail.getName().substring(namespace.length() + 1));
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 if (roleDesc.getPermissions() != null) {
238 for (ExternalAccessPerms extPerm : roleDesc.getPermissions()) {
239 RoleFunction roleFunction = new RoleFunction();
240 roleFunction.setCode(extPerm.getInstance());
241 roleFunction.setAction(extPerm.getAction());
242 if (extPerm.getDescription() != null
243 && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
244 roleFunction.setName(extPerm.getDescription());
245 } else if (extPerm.getDescription() == null
246 && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
247 roleFunction.setName(extPerm.getType().substring(namespace.length() + 1) + "|"
248 + extPerm.getInstance() + "|" + extPerm.getAction());
249 } else if (extPerm.getDescription() == null
250 && !EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
251 roleFunction.setName(
252 extPerm.getType() + "|" + extPerm.getInstance() + "|" + extPerm.getAction());
254 if (EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
255 roleFunction.setType(extPerm.getType().substring(namespace.length() + 1));
257 roleFunction.setType(extPerm.getType());
259 roleFunctions.add(roleFunction);
263 role.setRoleFunctions(roleFunctions);
265 userApp.setRole(role);
266 userApp.setUserId(user.getId());
267 userApps.add(userApp);
273 public List<RoleFunction> getRoleFunctions(String orgUserId) throws Exception {
274 ObjectMapper mapper = new ObjectMapper();
275 HttpHeaders headers = getBasicAuthHeaders();
276 HttpEntity<String> entity = new HttpEntity<>(headers);
277 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFunctions: Connecting to external auth system for user {}",
279 String endPoint = EXTERNAL_AUTH_GET_USER_PERMS_ENDPOINT + orgUserId
280 + EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_DOMAIN);
281 ResponseEntity<String> getResponse = template.exchange(
282 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL) + endPoint,
283 HttpMethod.GET, entity, String.class);
284 if (getResponse.getStatusCode().value() == 200) {
285 logger.debug(EELFLoggerDelegate.debugLogger,
286 "getRoleFunctions: Finished GET user perms from external system and body: {}",
287 getResponse.getBody());
289 String userPerms = getResponse.getBody();
290 List<ExternalAccessPerms> extPermsList = convertPermsJSONArrayToExternalAccessPerms(mapper, userPerms);
291 return convertToRoleFunctionList(extPermsList);
294 private List<ExternalAccessPerms> convertPermsJSONArrayToExternalAccessPerms(ObjectMapper mapper, String userPerms)
295 throws IOException, JsonParseException, JsonMappingException {
296 JSONObject userPermsJsonObj = null;
297 JSONArray userPermsJsonArray = null;
298 List<ExternalAccessPerms> extPermsList = new ArrayList<>();
299 if (!userPerms.equals(EcompExternalAuthUtils.EXT_EMPTY_JSON_STRING)) {
300 userPermsJsonObj = new JSONObject(userPerms);
301 userPermsJsonArray = userPermsJsonObj.getJSONArray(EcompExternalAuthUtils.EXT_PERM_FIELD);
302 for (int i = 0; i < userPermsJsonArray.length(); i++) {
303 JSONObject permJsonObj = userPermsJsonArray.getJSONObject(i);
304 if (!permJsonObj.getString(EcompExternalAuthUtils.EXT_PERM_FIELD_TYPE)
305 .endsWith(EcompExternalAuthUtils.EXT_PERM_ACCESS)) {
306 ExternalAccessPerms perm = mapper.readValue(permJsonObj.toString(), ExternalAccessPerms.class);
307 extPermsList.add(perm);
314 private ResponseEntity<String> getPermsFromExternalAuthSystem(HttpEntity<String> entity, String endPoint) {
315 ResponseEntity<String> getResponse = template.exchange(
316 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL) + endPoint,
317 HttpMethod.GET, entity, String.class);
318 if (getResponse.getStatusCode().value() == 200) {
319 logger.debug(EELFLoggerDelegate.debugLogger,
320 "getPermsFromExternalAuthSystem: Finished GET user perms from external auth system and body: {}",
321 getResponse.getBody());
326 private HttpHeaders getBasicAuthHeaders() throws Exception {
327 String userName = EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_NAME);
328 String encryptedPass = EcompExternalAuthProperties
329 .getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_PASSWORD);
330 String decryptedPass = EcompExternalAuthUtils.decryptPass(encryptedPass);
331 return EcompExternalAuthUtils.base64encodeKeyForAAFBasicAuth(userName, decryptedPass);
334 private List<RoleFunction> convertToRoleFunctionList(List<ExternalAccessPerms> extPermsList) {
335 List<RoleFunction> roleFunctions = new ArrayList<>();
336 String namespace = EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_NAMESPACE);
337 for (ExternalAccessPerms extPerm : extPermsList) {
338 RoleFunction roleFunction = new RoleFunction();
339 roleFunction.setCode(extPerm.getInstance());
340 roleFunction.setAction(extPerm.getAction());
341 if (extPerm.getDescription() != null
342 && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
343 roleFunction.setName(extPerm.getDescription());
344 } else if (extPerm.getDescription() == null
345 && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
346 roleFunction.setName(extPerm.getType().substring(namespace.length() + 1) + "|" + extPerm.getInstance()
347 + "|" + extPerm.getAction());
348 } else if (extPerm.getDescription() == null
349 && !EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
350 roleFunction.setName(extPerm.getType() + "|" + extPerm.getInstance() + "|" + extPerm.getAction());
352 if (EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
353 roleFunction.setType(extPerm.getType().substring(namespace.length() + 1));
355 roleFunction.setType(extPerm.getType());
357 roleFunctions.add(roleFunction);
359 return roleFunctions;
362 private SearchResult loadSearchResultData(PostSearchBean searchCriteria) throws NamingException {
363 return ldapService.searchPost(searchCriteria.getUser(), searchCriteria.getSortBy1(),
364 searchCriteria.getSortBy2(), searchCriteria.getSortBy3(), searchCriteria.getPageNo(),
365 searchCriteria.getNewDataSize(), 1);
369 public ResponseEntity<String> checkUserExists(String username, String password) throws Exception {
370 username = changeIfUserDomainNotAppended(username);
371 HttpHeaders headers = EcompExternalAuthUtils.base64encodeKeyForAAFBasicAuth(username, password);
372 String appUsername = EcompExternalAuthProperties
373 .getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_NAME);
374 String appPass = EcompExternalAuthUtils.decryptPass(
375 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_PASSWORD));
376 JSONObject credentials = new JSONObject();
377 credentials.put(ID, appUsername);
378 credentials.put(PASSCODE, appPass);
379 HttpEntity<String> entity = new HttpEntity<>(credentials.toString(), headers);
380 logger.debug(EELFLoggerDelegate.debugLogger, "checkUserExists: Connecting to external auth system for user {}",
382 ResponseEntity<String> getResponse = template.exchange(EcompExternalAuthProperties
383 .getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL)
384 + EXTERNAL_AUTH_POST_CREDENTIALS_ENDPOINT, HttpMethod.POST, entity, String.class);
385 if (getResponse.getStatusCode().value() == 200) {
386 logger.debug(EELFLoggerDelegate.debugLogger,
387 "checkUserExists: Finished POST from external auth system to validate credentials and status: {}",
388 getResponse.getStatusCode().value());
393 private String changeIfUserDomainNotAppended(String username) {
394 if (!EcompExternalAuthUtils.validate(username)) {
395 username = username + EcompExternalAuthProperties
396 .getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_DOMAIN);
402 public List<ExternalAccessPerms> getIfUserPermsExists(String username) throws Exception {
403 HttpHeaders headers = getBasicAuthHeaders();
404 HttpEntity<String> entity = new HttpEntity<>(headers);
405 logger.debug(EELFLoggerDelegate.debugLogger,
406 "getIfUserPermsExists: Connecting to external auth system for user {}", username);
407 username = changeIfUserDomainNotAppended(username);
408 String endPoint = EXTERNAL_AUTH_GET_USER_PERMS_ENDPOINT + username;
409 ResponseEntity<String> getResponse = getPermsFromExternalAuthSystem(entity, endPoint);
410 return convertPermsJSONArrayToExternalAccessPerms(new ObjectMapper(), getResponse.getBody());