8425f7dacde6926ee5cfce2ca8c5f3b8bfab281a
[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                                                 ExternalRoleDescription desc = new ExternalRoleDescription();
142                                                 if(role.has(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION)
143                                                                 && EcompExternalAuthUtils
144                                                                                 .isJSONValid(role.getString(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION))) {
145                                                         desc = mapper.readValue(role.getString(EcompExternalAuthUtils.EXT_FIELD_DESCRIPTION),
146                                                                         ExternalRoleDescription.class);
147                                                 }
148                                                 if(role.has(EcompExternalAuthUtils.EXT_FIELD_PERMS)) {
149                                                         JSONArray perms = role.getJSONArray(EcompExternalAuthUtils.EXT_FIELD_PERMS);
150                                                         List<ExternalAccessPerms> permsList = mapper.readValue(perms.toString(), TypeFactory
151                                                                         .defaultInstance().constructCollectionType(List.class, ExternalAccessPerms.class));
152                                                         desc.setPermissions(permsList);
153                                                 }
154                                                 userRoleDetail = new ExternalAccessUserRoleDetail(
155                                                                 role.getString(EcompExternalAuthUtils.EXT_ROLE_FIELD_NAME), desc);
156                                                 userRoleDetailList.add(userRoleDetail);
157                                         }
158                                 }
159                         } else {
160                                 throw new UserNotFoundException("User roles not found!");
161                         }
162
163                         if (userRoleDetailList.isEmpty()) {
164                                 throw new UserNotFoundException("User roles not found!");
165                         } else {
166                                 user = convertAAFUserRolesToEcompSDKUser(userRoleDetailList, orgUserId, namespace, request);
167                         }
168                 } catch (Exception e) {
169                         logger.error(EELFLoggerDelegate.errorLogger, "getUser: Failed! ", e);
170                 }
171                 return user;
172
173         }
174
175         @SuppressWarnings({ "rawtypes", "unchecked" })
176         private User convertAAFUserRolesToEcompSDKUser(List<ExternalAccessUserRoleDetail> userRoleDetailList,
177                         String orgUserId, String namespace, HttpServletRequest request)
178                         throws Exception {
179                 User user = loginAAFService.findUserWithoutPwd(orgUserId);
180                 PostSearchBean postSearchBean = new PostSearchBean();
181                 if (user == null) {
182                         postSearchBean.setOrgUserId(orgUserId);
183                         postSearchService.process(request, postSearchBean);
184                         postSearchBean.setSearchResult(loadSearchResultData(postSearchBean));
185                         user = (User) postSearchBean.getSearchResult().get(0);
186                         user.setActive(true);
187                         user.setLoginId(orgUserId);
188                         dataAccessService.saveDomainObject(user, null);
189                 }
190                 App app = appService.getApp(1l);
191                 try {
192                         Set userApps = new TreeSet();
193                         for (ExternalAccessUserRoleDetail userRoleDetail : userRoleDetailList) {
194                                 ExternalRoleDescription roleDesc = userRoleDetail.getDescription();
195                                 UserApp userApp = new UserApp();
196                                 Role role = new Role();
197                                 Set roleFunctions = new TreeSet<>();
198                                 if (roleDesc != null) {
199                                         if (roleDesc.getName() == null) {
200                                                 role.setActive(true);
201                                                 role.setName(userRoleDetail.getName().substring(namespace.length() + 1));
202                                         } else {
203                                                 role.setActive(Boolean.valueOf(roleDesc.getActive()));
204                                                 role.setId(Long.valueOf(roleDesc.getAppRoleId()));
205                                                 role.setName(roleDesc.getName());
206                                                 if (!roleDesc.getPriority().equals(EcompExternalAuthUtils.EXT_NULL_VALUE)) {
207                                                         role.setPriority(Integer.valueOf(roleDesc.getPriority()));
208                                                 }
209                                         }
210                                         for (ExternalAccessPerms extPerm : roleDesc.getPermissions()) {
211                                                 RoleFunction roleFunction = new RoleFunction();
212                                                 roleFunction.setCode(extPerm.getInstance());
213                                                 roleFunction.setAction(extPerm.getAction());
214                                                 if (extPerm.getDescription() != null
215                                                                 && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
216                                                         roleFunction.setName(extPerm.getDescription());
217                                                 } else if (extPerm.getDescription() == null
218                                                                 && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
219                                                         roleFunction.setName(extPerm.getType().substring(namespace.length() + 1) + "|"
220                                                                         + extPerm.getInstance() + "|" + extPerm.getAction());
221                                                 } else if (extPerm.getDescription() == null
222                                                                 && !EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
223                                                         roleFunction.setName(
224                                                                         extPerm.getType() + "|" + extPerm.getInstance() + "|" + extPerm.getAction());
225                                                 }
226                                                 if (EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
227                                                         roleFunction.setType(extPerm.getType().substring(namespace.length() + 1));
228                                                 } else {
229                                                         roleFunction.setType(extPerm.getType());
230                                                 }
231                                                 roleFunctions.add(roleFunction);
232                                         }
233                                 }
234                                 role.setRoleFunctions(roleFunctions);
235                                 userApp.setApp(app);
236                                 userApp.setRole(role);
237                                 userApp.setUserId(user.getId());
238                                 userApps.add(userApp);
239                         }
240                         user.setUserApps(userApps);
241                 } catch (Exception e) {
242                         logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
243                         throw e;
244                 }
245
246                 return user;
247         }
248
249         @Override
250         public List<RoleFunction> getRoleFunctions(String orgUserId) throws Exception {
251                 ObjectMapper mapper = new ObjectMapper();
252                 HttpHeaders headers = EcompExternalAuthUtils.base64encodeKeyForAAFBasicAuth();
253                 HttpEntity<String> entity = new HttpEntity<>(headers);
254                 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFunctions: Connecting to external system for user {}",
255                                 orgUserId);
256                 String endPoint = AAF_GET_USER_PERMS_ENDPOINT + orgUserId
257                                 + EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_DOMAIN);
258                 ResponseEntity<String> getResponse = template.exchange(
259                                 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL) + endPoint, HttpMethod.GET, entity,
260                                 String.class);
261                 if (getResponse.getStatusCode().value() == 200) {
262                         logger.debug(EELFLoggerDelegate.debugLogger,
263                                         "getRoleFunctions: Finished GET user perms from external system and body: {}",
264                                         getResponse.getBody());
265                 }
266                 String userPerms = getResponse.getBody();
267                 JSONObject userPermsJsonObj = null;
268                 JSONArray userPermsJsonArray = null;
269                 List<ExternalAccessPerms> extPermsList = new ArrayList<>();
270                 if (!userPerms.equals(EcompExternalAuthUtils.EXT_EMPTY_JSON_STRING)) {
271                         userPermsJsonObj = new JSONObject(userPerms);
272                         userPermsJsonArray = userPermsJsonObj.getJSONArray(EcompExternalAuthUtils.EXT_PERM_FIELD);
273                         for (int i = 0; i < userPermsJsonArray.length(); i++) {
274                                 JSONObject permJsonObj = userPermsJsonArray.getJSONObject(i);
275                                 if (!permJsonObj.getString(EcompExternalAuthUtils.EXT_PERM_FIELD_TYPE).endsWith(EcompExternalAuthUtils.EXT_PERM_ACCESS)) {
276                                         ExternalAccessPerms perm = mapper.readValue(permJsonObj.toString(), ExternalAccessPerms.class);
277                                         extPermsList.add(perm);
278                                 }
279                         }
280                 }
281                 return convertToRoleFunctionList(extPermsList);
282         }
283
284         private List<RoleFunction> convertToRoleFunctionList(List<ExternalAccessPerms> extPermsList) {
285                 List<RoleFunction> roleFunctions = new ArrayList<>();
286                 String namespace = EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_NAMESPACE);
287                 for (ExternalAccessPerms extPerm : extPermsList) {
288                         RoleFunction roleFunction = new RoleFunction();
289                         roleFunction.setCode(extPerm.getInstance());
290                         roleFunction.setAction(extPerm.getAction());
291                         if (extPerm.getDescription() != null
292                                         && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
293                                 roleFunction.setName(extPerm.getDescription());
294                         } else if (extPerm.getDescription() == null
295                                         && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
296                                 roleFunction.setName(extPerm.getType().substring(namespace.length() + 1) + "|" + extPerm.getInstance()
297                                                 + "|" + extPerm.getAction());
298                         } else if (extPerm.getDescription() == null
299                                         && !EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
300                                 roleFunction.setName(extPerm.getType() + "|" + extPerm.getInstance() + "|" + extPerm.getAction());
301                         }
302                         if (EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
303                                 roleFunction.setType(extPerm.getType().substring(namespace.length() + 1));
304                         } else {
305                                 roleFunction.setType(extPerm.getType());
306                         }
307                         roleFunctions.add(roleFunction);
308                 }
309                 return roleFunctions;
310         }
311
312         private SearchResult loadSearchResultData(PostSearchBean searchCriteria)
313                         throws NamingException {
314                 return ldapService.searchPost(searchCriteria.getUser(), searchCriteria.getSortBy1(),
315                                 searchCriteria.getSortBy2(), searchCriteria.getSortBy3(), searchCriteria.getPageNo(),
316                                 searchCriteria.getNewDataSize(), 1);
317         }
318
319 }