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