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