14d8a5e2f4e9d0fe3d62bfe0e8119b5f01ea6e1d
[portal/sdk.git] /
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal SDK
4  * ===================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
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
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
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
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
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.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalsdk.external.authorization.service;
39
40 import java.io.IOException;
41 import java.util.ArrayList;
42 import java.util.List;
43 import java.util.Set;
44 import java.util.TreeSet;
45
46 import javax.naming.NamingException;
47 import javax.servlet.http.HttpServletRequest;
48
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;
77
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;
82
83 @Service("userApiService")
84 public class UserApiServiceImpl implements UserApiService {
85
86         private static final String PASSCODE = "password";
87
88         private static final String ID = "id";
89
90         private static final String EXTERNAL_AUTH_GET_USER_ROLES_ENDPOINT = "authz/roles/user/";
91
92         private static final String EXTERNAL_AUTH_GET_USER_PERMS_ENDPOINT = "authz/perms/user/";
93
94         private static final String EXTERNAL_AUTH_POST_CREDENTIALS_ENDPOINT = "authn/validate";
95
96         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserApiServiceImpl.class);
97
98         @Autowired
99         private LoginExternalAuthService loginAAFService;
100
101         @Autowired
102         private LdapService ldapService;
103
104         @Autowired
105         private PostSearchService postSearchService;
106
107         @Autowired
108         private DataAccessService dataAccessService;
109
110         RestTemplate template = new RestTemplate();
111
112         @Autowired
113         private AppService appService;
114
115         @Override
116         public User getUser(String orgUserId, HttpServletRequest request) throws UserNotFoundException {
117                 User user = null;
118                 try {
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 {}",
124                                         orgUserId);
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());
134                         }
135                         String userRoles = getResponse.getBody();
136                         ObjectMapper mapper = new ObjectMapper();
137                         List<ExternalAccessUserRoleDetail> userRoleDetailList = setExternalAccessUserRoles(namespace, userRoles,
138                                         mapper);
139
140                         if (userRoleDetailList.isEmpty()) {
141                                 throw new UserNotFoundException("User roles not found!");
142                         } else {
143                                 user = convertAAFUserRolesToEcompSDKUser(userRoleDetailList, orgUserId, namespace, request);
144                         }
145                 } catch (Exception e) {
146                         logger.error(EELFLoggerDelegate.errorLogger, "getUser: Failed! ", e);
147                 }
148                 return user;
149
150         }
151
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);
172                                         }
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));
178                                         }
179                                         ExternalAccessRole ecRole = new ExternalAccessRole(
180                                                         role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME), ecPerms, ecDesc);
181                                         userRoleDetail = new ExternalAccessUserRoleDetail(ecRole);
182                                         userRoleDetailList.add(userRoleDetail);
183                                 }
184                         }
185                 } else {
186                         throw new UserNotFoundException("User roles not found!");
187                 }
188                 return userRoleDetailList;
189         }
190
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();
195                 if (user == null) {
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);
203                 }
204                 App app = appService.getApp(1l);
205                 try {
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);
210                         throw e;
211                 }
212
213                 return user;
214         }
215
216         @SuppressWarnings({ "rawtypes", "unchecked" })
217         private Set setUserApps(List<ExternalAccessUserRoleDetail> userRoleDetailList, String namespace, User user,
218                         App app) {
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());
229                         } else {
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()));
235                                 }
236                         }
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());
243                                 }
244                                 roleFunction.setType(extPerm.getType());
245                                 roleFunctions.add(roleFunction);
246                         }
247                         role.setRoleFunctions(roleFunctions);
248                         userApp.setApp(app);
249                         userApp.setRole(role);
250                         userApp.setUserId(user.getId());
251                         userApps.add(userApp);
252                 }
253                 return userApps;
254         }
255
256         @Override
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 {}",
262                                 orgUserId);
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());
272                 }
273                 String userPerms = getResponse.getBody();
274                 List<ExternalAccessPerms> extPermsList = convertPermsJSONArrayToExternalAccessPerms(mapper, userPerms);
275                 return convertToRoleFunctionList(extPermsList);
276         }
277
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);
292                                 }
293                         }
294                 }
295                 return extPermsList;
296         }
297
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());
306                 }
307                 return getResponse;
308         }
309
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);
316         }
317
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());
327                         }
328                         roleFunction.setType(extPerm.getType());
329                         roleFunctions.add(roleFunction);
330                 }
331                 return roleFunctions;
332         }
333
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);
338         }
339
340         @Override
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 {}",
353                                 username);
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());
361                 }
362                 return getResponse;
363         }
364
365         private String changeIfUserDomainNotAppended(String username) {
366                 if (!EcompExternalAuthUtils.validate(username)) {
367                         username = username
368                                         + EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_DOMAIN);
369                 }
370                 return username;
371         }
372
373         @Override
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());
383         }
384
385 }