fb320c1766e5ce2361864a1812a1b3dd514f098f
[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.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                                         if (roleDesc.getPermissions() != null) {
211                                                 for (ExternalAccessPerms extPerm : roleDesc.getPermissions()) {
212                                                         RoleFunction roleFunction = new RoleFunction();
213                                                         roleFunction.setCode(extPerm.getInstance());
214                                                         roleFunction.setAction(extPerm.getAction());
215                                                         if (extPerm.getDescription() != null
216                                                                         && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
217                                                                 roleFunction.setName(extPerm.getDescription());
218                                                         } else if (extPerm.getDescription() == null
219                                                                         && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
220                                                                 roleFunction.setName(extPerm.getType().substring(namespace.length() + 1) + "|"
221                                                                                 + extPerm.getInstance() + "|" + extPerm.getAction());
222                                                         } else if (extPerm.getDescription() == null
223                                                                         && !EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
224                                                                 roleFunction.setName(
225                                                                                 extPerm.getType() + "|" + extPerm.getInstance() + "|" + extPerm.getAction());
226                                                         }
227                                                         if (EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
228                                                                 roleFunction.setType(extPerm.getType().substring(namespace.length() + 1));
229                                                         } else {
230                                                                 roleFunction.setType(extPerm.getType());
231                                                         }
232                                                         roleFunctions.add(roleFunction);
233                                                 }
234                                         }
235                                 }
236                                 role.setRoleFunctions(roleFunctions);
237                                 userApp.setApp(app);
238                                 userApp.setRole(role);
239                                 userApp.setUserId(user.getId());
240                                 userApps.add(userApp);
241                         }
242                         user.setUserApps(userApps);
243                 } catch (Exception e) {
244                         logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
245                         throw e;
246                 }
247
248                 return user;
249         }
250
251         @Override
252         public List<RoleFunction> getRoleFunctions(String orgUserId) throws Exception {
253                 ObjectMapper mapper = new ObjectMapper();
254                 HttpHeaders headers = EcompExternalAuthUtils.base64encodeKeyForAAFBasicAuth();
255                 HttpEntity<String> entity = new HttpEntity<>(headers);
256                 logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFunctions: Connecting to external system for user {}",
257                                 orgUserId);
258                 String endPoint = AAF_GET_USER_PERMS_ENDPOINT + orgUserId
259                                 + EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_USER_DOMAIN);
260                 ResponseEntity<String> getResponse = template.exchange(
261                                 EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_URL) + endPoint, HttpMethod.GET, entity,
262                                 String.class);
263                 if (getResponse.getStatusCode().value() == 200) {
264                         logger.debug(EELFLoggerDelegate.debugLogger,
265                                         "getRoleFunctions: Finished GET user perms from external system and body: {}",
266                                         getResponse.getBody());
267                 }
268                 String userPerms = getResponse.getBody();
269                 JSONObject userPermsJsonObj = null;
270                 JSONArray userPermsJsonArray = null;
271                 List<ExternalAccessPerms> extPermsList = new ArrayList<>();
272                 if (!userPerms.equals(EcompExternalAuthUtils.EXT_EMPTY_JSON_STRING)) {
273                         userPermsJsonObj = new JSONObject(userPerms);
274                         userPermsJsonArray = userPermsJsonObj.getJSONArray(EcompExternalAuthUtils.EXT_PERM_FIELD);
275                         for (int i = 0; i < userPermsJsonArray.length(); i++) {
276                                 JSONObject permJsonObj = userPermsJsonArray.getJSONObject(i);
277                                 if (!permJsonObj.getString(EcompExternalAuthUtils.EXT_PERM_FIELD_TYPE).endsWith(EcompExternalAuthUtils.EXT_PERM_ACCESS)) {
278                                         ExternalAccessPerms perm = mapper.readValue(permJsonObj.toString(), ExternalAccessPerms.class);
279                                         extPermsList.add(perm);
280                                 }
281                         }
282                 }
283                 return convertToRoleFunctionList(extPermsList);
284         }
285
286         private List<RoleFunction> convertToRoleFunctionList(List<ExternalAccessPerms> extPermsList) {
287                 List<RoleFunction> roleFunctions = new ArrayList<>();
288                 String namespace = EcompExternalAuthProperties.getProperty(EcompExternalAuthProperties.EXTERNAL_AUTH_NAMESPACE);
289                 for (ExternalAccessPerms extPerm : extPermsList) {
290                         RoleFunction roleFunction = new RoleFunction();
291                         roleFunction.setCode(extPerm.getInstance());
292                         roleFunction.setAction(extPerm.getAction());
293                         if (extPerm.getDescription() != null
294                                         && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
295                                 roleFunction.setName(extPerm.getDescription());
296                         } else if (extPerm.getDescription() == null
297                                         && EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
298                                 roleFunction.setName(extPerm.getType().substring(namespace.length() + 1) + "|" + extPerm.getInstance()
299                                                 + "|" + extPerm.getAction());
300                         } else if (extPerm.getDescription() == null
301                                         && !EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
302                                 roleFunction.setName(extPerm.getType() + "|" + extPerm.getInstance() + "|" + extPerm.getAction());
303                         }
304                         if (EcompExternalAuthUtils.checkNameSpaceMatching(extPerm.getType(), namespace)) {
305                                 roleFunction.setType(extPerm.getType().substring(namespace.length() + 1));
306                         } else {
307                                 roleFunction.setType(extPerm.getType());
308                         }
309                         roleFunctions.add(roleFunction);
310                 }
311                 return roleFunctions;
312         }
313
314         private SearchResult loadSearchResultData(PostSearchBean searchCriteria)
315                         throws NamingException {
316                 return ldapService.searchPost(searchCriteria.getUser(), searchCriteria.getSortBy1(),
317                                 searchCriteria.getSortBy2(), searchCriteria.getSortBy3(), searchCriteria.getPageNo(),
318                                 searchCriteria.getNewDataSize(), 1);
319         }
320
321 }