3eac97b540307b5008310580fa4eeb563c329499
[portal/sdk.git] /
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal SDK
4  * ===================================================================
5  * Copyright (C) 2017 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.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;
76
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;
81
82 @Service("userApiService")
83 public class UserApiServiceImpl implements UserApiService {
84
85         private static final String PASSCODE = "password";
86
87         private static final String ID = "id";
88
89         private static final String EXTERNAL_AUTH_GET_USER_ROLES_ENDPOINT = "authz/roles/user/";
90
91         private static final String EXTERNAL_AUTH_GET_USER_PERMS_ENDPOINT = "authz/perms/user/";
92
93         private static final String EXTERNAL_AUTH_POST_CREDENTIALS_ENDPOINT = "authn/validate";
94
95         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserApiServiceImpl.class);
96
97         @Autowired
98         private LoginExternalAuthService loginAAFService;
99
100         @Autowired
101         private LdapService ldapService;
102
103         @Autowired
104         private PostSearchService postSearchService;
105
106         @Autowired
107         private DataAccessService dataAccessService;
108
109         RestTemplate template = new RestTemplate();
110
111         @Autowired
112         private AppService appService;
113
114         @Override
115         public User getUser(String orgUserId, HttpServletRequest request) throws UserNotFoundException {
116                 User user = null;
117                 try {
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 {}",
123                                         orgUserId);
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 user app roles from external auth system and body: {}",
132                                                 getResponse.getBody());
133                         }
134                         String userRoles = getResponse.getBody();
135                         ObjectMapper mapper = new ObjectMapper();
136                         List<ExternalAccessUserRoleDetail> userRoleDetailList = setExterbalAccessUserRoles(namespace, userRoles,
137                                         mapper);
138
139                         if (userRoleDetailList.isEmpty()) {
140                                 throw new UserNotFoundException("User roles not found!");
141                         } else {
142                                 user = convertAAFUserRolesToEcompSDKUser(userRoleDetailList, orgUserId, namespace, request);
143                         }
144                 } catch (Exception e) {
145                         logger.error(EELFLoggerDelegate.errorLogger, "getUser: Failed! ", e);
146                 }
147                 return user;
148
149         }
150
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                                         ExternalRoleDescription desc = new ExternalRoleDescription();
167                                         if (role.has(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION) && EcompExternalAuthUtils
168                                                         .isJSONValid(role.getString(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION))) {
169                                                 desc = mapper.readValue(role.getString(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION),
170                                                                 ExternalRoleDescription.class);
171                                         }
172                                         if (role.has(EcompExternalAuthUtils.EXT_FIELD_PERMS)) {
173                                                 JSONArray perms = role.getJSONArray(EcompExternalAuthUtils.EXT_FIELD_PERMS);
174                                                 List<ExternalAccessPerms> permsList = mapper.readValue(perms.toString(), TypeFactory
175                                                                 .defaultInstance().constructCollectionType(List.class, ExternalAccessPerms.class));
176                                                 desc.setPermissions(permsList);
177                                         }
178                                         userRoleDetail = new ExternalAccessUserRoleDetail(
179                                                         role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME), desc);
180                                         userRoleDetailList.add(userRoleDetail);
181                                 }
182                         }
183                 } else {
184                         throw new UserNotFoundException("User roles not found!");
185                 }
186                 return userRoleDetailList;
187         }
188
189         private User convertAAFUserRolesToEcompSDKUser(List<ExternalAccessUserRoleDetail> userRoleDetailList,
190                         String orgUserId, String namespace, HttpServletRequest request) throws Exception {
191                 User user = loginAAFService.findUserWithoutPwd(orgUserId);
192                 PostSearchBean postSearchBean = new PostSearchBean();
193                 if (user == null) {
194                         postSearchBean.setOrgUserId(orgUserId);
195                         postSearchService.process(request, postSearchBean);
196                         postSearchBean.setSearchResult(loadSearchResultData(postSearchBean));
197                         user = (User) postSearchBean.getSearchResult().get(0);
198                         user.setActive(true);
199                         user.setLoginId(orgUserId);
200                         dataAccessService.saveDomainObject(user, null);
201                 }
202                 App app = appService.getApp(1l);
203                 try {
204                         Set userApps = setUserApps(userRoleDetailList, namespace, user, app);
205                         user.setUserApps(userApps);
206                 } catch (Exception e) {
207                         logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
208                         throw e;
209                 }
210
211                 return user;
212         }
213
214         @SuppressWarnings({ "rawtypes", "unchecked" })
215         private Set setUserApps(List<ExternalAccessUserRoleDetail> userRoleDetailList, String namespace, User user,
216                         App app) {
217                 Set userApps = new TreeSet();
218                 for (ExternalAccessUserRoleDetail userRoleDetail : userRoleDetailList) {
219                         ExternalRoleDescription roleDesc = userRoleDetail.getDescription();
220                         UserApp userApp = new UserApp();
221                         Role role = new Role();
222                         Set roleFunctions = new TreeSet<>();
223                         if (roleDesc != null) {
224                                 if (roleDesc.getName() == null) {
225                                         role.setActive(true);
226                                         role.setName(userRoleDetail.getName());
227                                 } else {
228                                         role.setActive(Boolean.valueOf(roleDesc.getActive()));
229                                         role.setId(Long.valueOf(roleDesc.getAppRoleId()));
230                                         role.setName(roleDesc.getName());
231                                         if (!roleDesc.getPriority().equals(EcompExternalAuthUtils.EXT_NULL_VALUE)) {
232                                                 role.setPriority(Integer.valueOf(roleDesc.getPriority()));
233                                         }
234                                 }
235                                 if (roleDesc.getPermissions() != null) {
236                                         for (ExternalAccessPerms extPerm : roleDesc.getPermissions()) {
237                                                 RoleFunction roleFunction = new RoleFunction();
238                                                 roleFunction.setCode(extPerm.getInstance());
239                                                 roleFunction.setAction(extPerm.getAction());
240                                                 if (extPerm.getDescription() != null
241                                                                 && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
242                                                         roleFunction.setName(extPerm.getDescription());
243                                                 } else if (extPerm.getDescription() == null
244                                                                 && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
245                                                         roleFunction.setName(extPerm.getType().substring(namespace.length() + 1) + "|"
246                                                                         + extPerm.getInstance() + "|" + extPerm.getAction());
247                                                 } else if (extPerm.getDescription() == null
248                                                                 && !EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
249                                                         roleFunction.setName(
250                                                                         extPerm.getType() + "|" + extPerm.getInstance() + "|" + extPerm.getAction());
251                                                 }
252                                                 if (EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
253                                                         roleFunction.setType(extPerm.getType().substring(namespace.length() + 1));
254                                                 } else {
255                                                         roleFunction.setType(extPerm.getType());
256                                                 }
257                                                 roleFunctions.add(roleFunction);
258                                         }
259                                 }
260                         }
261                         role.setRoleFunctions(roleFunctions);
262                         userApp.setApp(app);
263                         userApp.setRole(role);
264                         userApp.setUserId(user.getId());
265                         userApps.add(userApp);
266                 }
267                 return userApps;
268         }
269
270         @Override
271         public List<RoleFunction> getRoleFunctions(String orgUserId) throws Exception {
272                 ObjectMapper mapper = new ObjectMapper();
273                 HttpHeaders headers = getBasicAuthHeaders();
274                 HttpEntity<String> entity = new HttpEntity<>(headers);
275                 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFunctions: Connecting to external auth system for user {}",
276                                 orgUserId);
277                 String endPoint = EXTERNAL_AUTH_GET_USER_PERMS_ENDPOINT + orgUserId
278                                 + EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_DOMAIN);
279                 ResponseEntity<String> getResponse = template.exchange(
280                                 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL) + endPoint,
281                                 HttpMethod.GET, entity, String.class);
282                 if (getResponse.getStatusCode().value() == 200) {
283                         logger.debug(EELFLoggerDelegate.debugLogger,
284                                         "getRoleFunctions: Finished GET user perms from external system and body: {}",
285                                         getResponse.getBody());
286                 }
287                 String userPerms = getResponse.getBody();
288                 List<ExternalAccessPerms> extPermsList = convertPermsJSONArrayToExternalAccessPerms(mapper, userPerms);
289                 return convertToRoleFunctionList(extPermsList);
290         }
291
292         private List<ExternalAccessPerms> convertPermsJSONArrayToExternalAccessPerms(ObjectMapper mapper, String userPerms)
293                         throws IOException, JsonParseException, JsonMappingException {
294                 JSONObject userPermsJsonObj = null;
295                 JSONArray userPermsJsonArray = null;
296                 List<ExternalAccessPerms> extPermsList = new ArrayList<>();
297                 if (!userPerms.equals(EcompExternalAuthUtils.EXT_EMPTY_JSON_STRING)) {
298                         userPermsJsonObj = new JSONObject(userPerms);
299                         userPermsJsonArray = userPermsJsonObj.getJSONArray(EcompExternalAuthUtils.EXT_PERM_FIELD);
300                         for (int i = 0; i < userPermsJsonArray.length(); i++) {
301                                 JSONObject permJsonObj = userPermsJsonArray.getJSONObject(i);
302                                 if (!permJsonObj.getString(EcompExternalAuthUtils.EXT_PERM_FIELD_TYPE)
303                                                 .endsWith(EcompExternalAuthUtils.EXT_PERM_ACCESS)) {
304                                         ExternalAccessPerms perm = mapper.readValue(permJsonObj.toString(), ExternalAccessPerms.class);
305                                         extPermsList.add(perm);
306                                 }
307                         }
308                 }
309                 return extPermsList;
310         }
311
312         private ResponseEntity<String> getPermsFromExternalAuthSystem(HttpEntity<String> entity, String endPoint) {
313                 ResponseEntity<String> getResponse = template.exchange(
314                                 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL) + endPoint,
315                                 HttpMethod.GET, entity, String.class);
316                 if (getResponse.getStatusCode().value() == 200) {
317                         logger.debug(EELFLoggerDelegate.debugLogger,
318                                         "getPermsFromExternalAuthSystem: Finished GET user perms from external auth system and body: {}",
319                                         getResponse.getBody());
320                 }
321                 return getResponse;
322         }
323
324         private HttpHeaders getBasicAuthHeaders() throws Exception {
325                 String userName = EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_NAME);
326                 String encryptedPass = EcompExternalAuthProperties
327                                 .getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_PASSWORD);
328                 String decryptedPass = EcompExternalAuthUtils.decryptPass(encryptedPass);
329                 return EcompExternalAuthUtils.base64encodeKeyForAAFBasicAuth(userName, decryptedPass);
330         }
331
332         private List<RoleFunction> convertToRoleFunctionList(List<ExternalAccessPerms> extPermsList) {
333                 List<RoleFunction> roleFunctions = new ArrayList<>();
334                 String namespace = EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_NAMESPACE);
335                 for (ExternalAccessPerms extPerm : extPermsList) {
336                         RoleFunction roleFunction = new RoleFunction();
337                         roleFunction.setCode(extPerm.getInstance());
338                         roleFunction.setAction(extPerm.getAction());
339                         if (extPerm.getDescription() != null
340                                         && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
341                                 roleFunction.setName(extPerm.getDescription());
342                         } else if (extPerm.getDescription() == null
343                                         && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
344                                 roleFunction.setName(extPerm.getType().substring(namespace.length() + 1) + "|" + extPerm.getInstance()
345                                                 + "|" + extPerm.getAction());
346                         } else if (extPerm.getDescription() == null
347                                         && !EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
348                                 roleFunction.setName(extPerm.getType() + "|" + extPerm.getInstance() + "|" + extPerm.getAction());
349                         }
350                         if (EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
351                                 roleFunction.setType(extPerm.getType().substring(namespace.length() + 1));
352                         } else {
353                                 roleFunction.setType(extPerm.getType());
354                         }
355                         roleFunctions.add(roleFunction);
356                 }
357                 return roleFunctions;
358         }
359
360         private SearchResult loadSearchResultData(PostSearchBean searchCriteria) throws NamingException {
361                 return ldapService.searchPost(searchCriteria.getUser(), searchCriteria.getSortBy1(),
362                                 searchCriteria.getSortBy2(), searchCriteria.getSortBy3(), searchCriteria.getPageNo(),
363                                 searchCriteria.getNewDataSize(), 1);
364         }
365
366         @Override
367         public ResponseEntity<String> checkUserExists(String username, String password) throws Exception {
368                 username = changeIfUserDomainNotAppended(username);
369                 HttpHeaders headers = EcompExternalAuthUtils.base64encodeKeyForAAFBasicAuth(username, password);
370                 String appUsername = EcompExternalAuthProperties
371                                 .getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_NAME);
372                 String appPass = EcompExternalAuthUtils.decryptPass(
373                                 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_PASSWORD));
374                 JSONObject credentials = new JSONObject();
375                 credentials.put(ID, appUsername);
376                 credentials.put(PASSCODE, appPass);
377                 HttpEntity<String> entity = new HttpEntity<>(credentials.toString(), headers);
378                 logger.debug(EELFLoggerDelegate.debugLogger, "checkUserExists: Connecting to external auth system for user {}",
379                                 username);
380                 ResponseEntity<String> getResponse = template.exchange(EcompExternalAuthProperties
381                                 .getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL)
382                                 + EXTERNAL_AUTH_POST_CREDENTIALS_ENDPOINT, HttpMethod.POST, entity, String.class);
383                 if (getResponse.getStatusCode().value() == 200) {
384                         logger.debug(EELFLoggerDelegate.debugLogger,
385                                         "checkUserExists: Finished POST from external auth system to validate credentials and status: {}",
386                                         getResponse.getStatusCode().value());
387                 }
388                 return getResponse;
389         }
390
391         private String changeIfUserDomainNotAppended(String username) {
392                 if (!EcompExternalAuthUtils.validate(username)) {
393                         username = username + EcompExternalAuthProperties
394                                         .getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_DOMAIN);
395                 }
396                 return username;
397         }
398
399         @Override
400         public List<ExternalAccessPerms> getIfUserPermsExists(String username) throws Exception {
401                 HttpHeaders headers = getBasicAuthHeaders();
402                 HttpEntity<String> entity = new HttpEntity<>(headers);
403                 logger.debug(EELFLoggerDelegate.debugLogger,
404                                 "getIfUserPermsExists: Connecting to external auth system for user {}", username);
405                 username = changeIfUserDomainNotAppended(username);
406                 String endPoint = EXTERNAL_AUTH_GET_USER_PERMS_ENDPOINT + username;
407                 ResponseEntity<String> getResponse = getPermsFromExternalAuthSystem(entity, endPoint);
408                 return convertPermsJSONArrayToExternalAccessPerms(new ObjectMapper(), getResponse.getBody());
409         }
410
411 }