32a7421f18106d7f3d3212b1b1167369c62ff96c
[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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.onap.portalsdk.external.authorization.service;
39
40 import java.util.ArrayList;
41 import java.util.List;
42 import java.util.Set;
43 import java.util.TreeSet;
44
45 import javax.naming.NamingException;
46 import javax.servlet.http.HttpServletRequest;
47
48 import org.json.JSONArray;
49 import org.json.JSONObject;
50 import org.onap.portalsdk.core.command.PostSearchBean;
51 import org.onap.portalsdk.core.command.support.SearchResult;
52 import org.onap.portalsdk.core.domain.App;
53 import org.onap.portalsdk.core.domain.Role;
54 import org.onap.portalsdk.core.domain.RoleFunction;
55 import org.onap.portalsdk.core.domain.User;
56 import org.onap.portalsdk.core.domain.UserApp;
57 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
58 import org.onap.portalsdk.core.service.AppService;
59 import org.onap.portalsdk.core.service.DataAccessService;
60 import org.onap.portalsdk.core.service.LdapService;
61 import org.onap.portalsdk.core.service.PostSearchService;
62 import org.onap.portalsdk.external.authorization.domain.ExternalAccessPerms;
63 import org.onap.portalsdk.external.authorization.domain.ExternalAccessUserRoleDetail;
64 import org.onap.portalsdk.external.authorization.domain.ExternalRoleDescription;
65 import org.onap.portalsdk.external.authorization.exception.UserNotFoundException;
66 import org.onap.portalsdk.external.authorization.util.EcompExternalAuthProperties;
67 import org.onap.portalsdk.external.authorization.util.EcompExternalAuthUtils;
68 import org.springframework.beans.factory.annotation.Autowired;
69 import org.springframework.http.HttpEntity;
70 import org.springframework.http.HttpHeaders;
71 import org.springframework.http.HttpMethod;
72 import org.springframework.http.ResponseEntity;
73 import org.springframework.stereotype.Service;
74 import org.springframework.transaction.annotation.Transactional;
75 import org.springframework.web.client.RestTemplate;
76
77 import com.fasterxml.jackson.databind.ObjectMapper;
78 import com.fasterxml.jackson.databind.type.TypeFactory;
79
80 @Service("userApiService")
81 public class UserApiServiceImpl implements UserApiService {
82
83         private static final String AAF_GET_USER_ROLES_ENDPOINT = "roles/user/";
84
85         private static final String AAF_GET_USER_PERMS_ENDPOINT = "perms/user/";
86
87         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserApiServiceImpl.class);
88
89         @Autowired
90         private LoginExternalAuthService loginAAFService;
91
92         @Autowired
93         private LdapService ldapService;
94
95         @Autowired
96         private PostSearchService postSearchService;
97
98         @Autowired
99         private DataAccessService dataAccessService;
100
101         RestTemplate template = new RestTemplate();
102
103         @Autowired
104         private AppService appService;
105
106         @Override
107         @Transactional
108         public User getUser(String orgUserId, HttpServletRequest request)
109                         throws UserNotFoundException {
110                 User user = null;
111                 try {
112                         String namespace = EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_NAMESPACE);
113                         HttpHeaders headers = EcompExternalAuthUtils.base64encodeKeyForAAFBasicAuth();
114                         HttpEntity<String> entity = new HttpEntity<>(headers);
115                         logger.debug(EELFLoggerDelegate.debugLogger, "getUserRoles: Connecting to external system for user {}",
116                                         orgUserId);
117                         String endPoint = AAF_GET_USER_ROLES_ENDPOINT + orgUserId
118                                         + EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_DOMAIN);
119                         ResponseEntity<String> getResponse = template.exchange(
120                                         EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL) + endPoint, HttpMethod.GET, entity,
121                                         String.class);
122                         if (getResponse.getStatusCode().value() == 200) {
123                                 logger.debug(EELFLoggerDelegate.debugLogger,
124                                                 "getUserRoles: Finished GET unp ser roles from external system and body: {}",
125                                                 getResponse.getBody());
126                         }
127                         String userRoles = getResponse.getBody();
128                         JSONObject userJsonObj = null;
129                         JSONArray userJsonArray = null;
130                         ObjectMapper mapper = new ObjectMapper();
131                         List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
132                         if (!userRoles.equals(EcompExternalAuthUtils.EXT_EMPTY_JSON_STRING)) {
133                                 userJsonObj = new JSONObject(userRoles);
134                                 userJsonArray = userJsonObj.getJSONArray(EcompExternalAuthUtils.EXT_ROLE_FIELD);
135                                 ExternalAccessUserRoleDetail userRoleDetail = null;
136                                 for (int i = 0; i < userJsonArray.length(); i++) {
137                                         JSONObject role = userJsonArray.getJSONObject(i);
138                                         if (!role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME).endsWith(EcompExternalAuthUtils.EXT_ROLE_FIELD_ADMIN)
139                                                         && !role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME)
140                                                                         .endsWith(EcompExternalAuthUtils.EXT_ROLE_FIELD_OWNER)
141                                                         && EcompExternalAuthUtils.checkNameSpaceMatching(role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME),
142                                                                         namespace)) {
143                                                 ExternalRoleDescription desc = new ExternalRoleDescription();
144                                                 if(role.has(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION)
145                                                                 && EcompExternalAuthUtils
146                                                                                 .isJSONValid(role.getString(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION))) {
147                                                         desc = mapper.readValue(role.getString(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION),
148                                                                         ExternalRoleDescription.class);
149                                                 }
150                                                 if(role.has(EcompExternalAuthUtils.EXT_FIELD_PERMS)) {
151                                                         JSONArray perms = role.getJSONArray(EcompExternalAuthUtils.EXT_FIELD_PERMS);
152                                                         List<ExternalAccessPerms> permsList = mapper.readValue(perms.toString(), TypeFactory
153                                                                         .defaultInstance().constructCollectionType(List.class, ExternalAccessPerms.class));
154                                                         desc.setPermissions(permsList);
155                                                 }
156                                                 userRoleDetail = new ExternalAccessUserRoleDetail(
157                                                                 role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME), desc);
158                                                 userRoleDetailList.add(userRoleDetail);
159                                         }
160                                 }
161                         } else {
162                                 throw new UserNotFoundException("User roles not found!");
163                         }
164
165                         if (userRoleDetailList.isEmpty()) {
166                                 throw new UserNotFoundException("User roles not found!");
167                         } else {
168                                 user = convertAAFUserRolesToEcompSDKUser(userRoleDetailList, orgUserId, namespace, request);
169                         }
170                 } catch (Exception e) {
171                         logger.error(EELFLoggerDelegate.errorLogger, "getUser: Failed! ", e);
172                 }
173                 return user;
174
175         }
176
177         @SuppressWarnings({ "rawtypes", "unchecked" })
178         private User convertAAFUserRolesToEcompSDKUser(List<ExternalAccessUserRoleDetail> userRoleDetailList,
179                         String orgUserId, String namespace, HttpServletRequest request)
180                         throws Exception {
181                 User user = loginAAFService.findUserWithoutPwd(orgUserId);
182                 PostSearchBean postSearchBean = new PostSearchBean();
183                 if (user == null) {
184                         postSearchBean.setOrgUserId(orgUserId);
185                         postSearchService.process(request, postSearchBean);
186                         postSearchBean.setSearchResult(loadSearchResultData(postSearchBean));
187                         user = (User) postSearchBean.getSearchResult().get(0);
188                         user.setActive(true);
189                         user.setLoginId(orgUserId);
190                         dataAccessService.saveDomainObject(user, null);
191                 }
192                 App app = appService.getApp(1l);
193                 try {
194                         Set userApps = new TreeSet();
195                         for (ExternalAccessUserRoleDetail userRoleDetail : userRoleDetailList) {
196                                 ExternalRoleDescription roleDesc = userRoleDetail.getDescription();
197                                 UserApp userApp = new UserApp();
198                                 Role role = new Role();
199                                 Set roleFunctions = new TreeSet<>();
200                                 if (roleDesc != null) {
201                                         if (roleDesc.getName() == null) {
202                                                 role.setActive(true);
203                                                 role.setName(userRoleDetail.getName().substring(namespace.length() + 1));
204                                         } else {
205                                                 role.setActive(Boolean.valueOf(roleDesc.getActive()));
206                                                 role.setId(Long.valueOf(roleDesc.getAppRoleId()));
207                                                 role.setName(roleDesc.getName());
208                                                 if (!roleDesc.getPriority().equals(EcompExternalAuthUtils.EXT_NULL_VALUE)) {
209                                                         role.setPriority(Integer.valueOf(roleDesc.getPriority()));
210                                                 }
211                                         }
212                                         if (roleDesc.getPermissions() != null) {
213                                                 for (ExternalAccessPerms extPerm : roleDesc.getPermissions()) {
214                                                         RoleFunction roleFunction = new RoleFunction();
215                                                         roleFunction.setCode(extPerm.getInstance());
216                                                         roleFunction.setAction(extPerm.getAction());
217                                                         if (extPerm.getDescription() != null
218                                                                         && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
219                                                                 roleFunction.setName(extPerm.getDescription());
220                                                         } else if (extPerm.getDescription() == null
221                                                                         && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
222                                                                 roleFunction.setName(extPerm.getType().substring(namespace.length() + 1) + "|"
223                                                                                 + extPerm.getInstance() + "|" + extPerm.getAction());
224                                                         } else if (extPerm.getDescription() == null
225                                                                         && !EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
226                                                                 roleFunction.setName(
227                                                                                 extPerm.getType() + "|" + extPerm.getInstance() + "|" + extPerm.getAction());
228                                                         }
229                                                         if (EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
230                                                                 roleFunction.setType(extPerm.getType().substring(namespace.length() + 1));
231                                                         } else {
232                                                                 roleFunction.setType(extPerm.getType());
233                                                         }
234                                                         roleFunctions.add(roleFunction);
235                                                 }
236                                         }
237                                 }
238                                 role.setRoleFunctions(roleFunctions);
239                                 userApp.setApp(app);
240                                 userApp.setRole(role);
241                                 userApp.setUserId(user.getId());
242                                 userApps.add(userApp);
243                         }
244                         user.setUserApps(userApps);
245                 } catch (Exception e) {
246                         logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
247                         throw e;
248                 }
249
250                 return user;
251         }
252
253         @Override
254         public List<RoleFunction> getRoleFunctions(String orgUserId) throws Exception {
255                 ObjectMapper mapper = new ObjectMapper();
256                 HttpHeaders headers = EcompExternalAuthUtils.base64encodeKeyForAAFBasicAuth();
257                 HttpEntity<String> entity = new HttpEntity<>(headers);
258                 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFunctions: Connecting to external system for user {}",
259                                 orgUserId);
260                 String endPoint = AAF_GET_USER_PERMS_ENDPOINT + orgUserId
261                                 + EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_DOMAIN);
262                 ResponseEntity<String> getResponse = template.exchange(
263                                 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL) + endPoint, HttpMethod.GET, entity,
264                                 String.class);
265                 if (getResponse.getStatusCode().value() == 200) {
266                         logger.debug(EELFLoggerDelegate.debugLogger,
267                                         "getRoleFunctions: Finished GET user perms from external system and body: {}",
268                                         getResponse.getBody());
269                 }
270                 String userPerms = getResponse.getBody();
271                 JSONObject userPermsJsonObj = null;
272                 JSONArray userPermsJsonArray = null;
273                 List<ExternalAccessPerms> extPermsList = new ArrayList<>();
274                 if (!userPerms.equals(EcompExternalAuthUtils.EXT_EMPTY_JSON_STRING)) {
275                         userPermsJsonObj = new JSONObject(userPerms);
276                         userPermsJsonArray = userPermsJsonObj.getJSONArray(EcompExternalAuthUtils.EXT_PERM_FIELD);
277                         for (int i = 0; i < userPermsJsonArray.length(); i++) {
278                                 JSONObject permJsonObj = userPermsJsonArray.getJSONObject(i);
279                                 if (!permJsonObj.getString(EcompExternalAuthUtils.EXT_PERM_FIELD_TYPE).endsWith(EcompExternalAuthUtils.EXT_PERM_ACCESS)) {
280                                         ExternalAccessPerms perm = mapper.readValue(permJsonObj.toString(), ExternalAccessPerms.class);
281                                         extPermsList.add(perm);
282                                 }
283                         }
284                 }
285                 return convertToRoleFunctionList(extPermsList);
286         }
287
288         private List<RoleFunction> convertToRoleFunctionList(List<ExternalAccessPerms> extPermsList) {
289                 List<RoleFunction> roleFunctions = new ArrayList<>();
290                 String namespace = EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_NAMESPACE);
291                 for (ExternalAccessPerms extPerm : extPermsList) {
292                         RoleFunction roleFunction = new RoleFunction();
293                         roleFunction.setCode(extPerm.getInstance());
294                         roleFunction.setAction(extPerm.getAction());
295                         if (extPerm.getDescription() != null
296                                         && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
297                                 roleFunction.setName(extPerm.getDescription());
298                         } else if (extPerm.getDescription() == null
299                                         && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
300                                 roleFunction.setName(extPerm.getType().substring(namespace.length() + 1) + "|" + extPerm.getInstance()
301                                                 + "|" + extPerm.getAction());
302                         } else if (extPerm.getDescription() == null
303                                         && !EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
304                                 roleFunction.setName(extPerm.getType() + "|" + extPerm.getInstance() + "|" + extPerm.getAction());
305                         }
306                         if (EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
307                                 roleFunction.setType(extPerm.getType().substring(namespace.length() + 1));
308                         } else {
309                                 roleFunction.setType(extPerm.getType());
310                         }
311                         roleFunctions.add(roleFunction);
312                 }
313                 return roleFunctions;
314         }
315
316         private SearchResult loadSearchResultData(PostSearchBean searchCriteria)
317                         throws NamingException {
318                 return ldapService.searchPost(searchCriteria.getUser(), searchCriteria.getSortBy1(),
319                                 searchCriteria.getSortBy2(), searchCriteria.getSortBy3(), searchCriteria.getPageNo(),
320                                 searchCriteria.getNewDataSize(), 1);
321         }
322
323 }