Remove need for USER_ID header
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / filters / ThreadLocalUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.sdc.be.filters;
21
22 import java.util.Arrays;
23 import java.util.HashSet;
24 import java.util.List;
25 import java.util.Optional;
26 import java.util.Set;
27 import javax.servlet.http.HttpServletRequest;
28
29 import org.apache.commons.lang3.StringUtils;
30 import org.onap.sdc.security.AuthenticationCookie;
31 import org.onap.sdc.security.IUsersThreadLocalHolder;
32 import org.onap.sdc.security.PortalClient;
33 import org.onap.sdc.security.RestrictionAccessFilterException;
34 import org.openecomp.sdc.be.config.Configuration;
35 import org.openecomp.sdc.be.config.ConfigurationManager;
36 import org.openecomp.sdc.be.model.User;
37 import org.openecomp.sdc.be.user.UserBusinessLogic;
38 import org.openecomp.sdc.common.api.Constants;
39 import org.openecomp.sdc.common.datastructure.UserContext;
40 import org.openecomp.sdc.common.log.wrappers.Logger;
41 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
42 import org.springframework.beans.factory.annotation.Autowired;
43
44 public class ThreadLocalUtils implements IUsersThreadLocalHolder {
45
46     private static final Logger log = Logger.getLogger(ThreadLocalUtils.class);
47     @Autowired
48     private PortalClient portalClient;
49     @Autowired
50     private UserBusinessLogic userBusinessLogic;
51
52     @Override
53     public void setUserContext(AuthenticationCookie authenticationCookie) {
54         UserContext userContext;
55         userContext = new UserContext(authenticationCookie.getUserID(), authenticationCookie.getRoles(), authenticationCookie.getFirstName(),
56                 authenticationCookie.getLastName());
57         ThreadLocalsHolder.setUserContext(userContext);
58     }
59
60     protected void setUserContext(HttpServletRequest httpRequest) {
61         final String userId = httpRequest.getHeader(Constants.USER_ID_HEADER);
62         if (userId != null) {
63             Set<String> roles = null;
64             try {
65                 final Optional<String> userRolesFromPortalOptional = portalClient.fetchUserRolesFromPortal(userId);
66                 if (userRolesFromPortalOptional.isPresent()) {
67                     roles = new HashSet<>(List.of(userRolesFromPortalOptional.get()));
68                 }
69             } catch (RestrictionAccessFilterException e) {
70                 log.debug("Failed to fetch user ID - {} from portal", userId);
71                 log.debug(e.getMessage());
72             }
73             final UserContext userContext = new UserContext(userId, roles, null, null);
74             ThreadLocalsHolder.setUserContext(userContext);
75         } else {
76             log.debug("user_id value in req header is null, userContext will not be initialized");
77         }
78     }
79
80     protected void setUserContextFromDB(HttpServletRequest httpRequest) {
81         String userId = httpRequest.getHeader(Constants.USER_ID_HEADER);
82         final Configuration.BasicAuthConfig basicAuthConf = ConfigurationManager.getConfigurationManager().getConfiguration().getBasicAuth();
83         if (StringUtils.isBlank(userId)) {
84             final String excludedUrls = basicAuthConf.getExcludedUrls();
85             //there are some internal request that have no user_id header e.g. healthcheck
86             if (StringUtils.isBlank(excludedUrls) || !checkForExclusion(excludedUrls, httpRequest.getPathInfo())) {
87                 log.info("UserId is empty");
88                 userId = "cs0008";
89             } else {
90                 log.debug("user_id value in req header is null, userContext will not be initialized");
91                 return;
92             }
93         }
94         updateUserContext(userId);
95     }
96
97     private boolean checkForExclusion(final String excludedUrls, final String pathInfo) {
98         return Arrays.stream(excludedUrls.split(";")).anyMatch(s -> s.endsWith(pathInfo));
99     }
100
101     private void updateUserContext(String userId) {
102         User user = userBusinessLogic.getUser(userId, false);
103         Set<String> roles = new HashSet<>(Arrays.asList(user.getRole()));
104         UserContext userContext = new UserContext(user.getUserId(), roles, user.getFirstName(), user.getLastName());
105         ThreadLocalsHolder.setUserContext(userContext);
106     }
107 }