Extract AlwaysValidRoleValidator from RoleValidator
[vid.git] / vid-app-common / src / main / java / org / onap / vid / roles / RoleProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2018 - 2019 Nokia. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.vid.roles;
23
24 import com.fasterxml.jackson.core.JsonProcessingException;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import io.joshworks.restclient.http.HttpResponse;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Optional;
32 import java.util.function.Function;
33 import java.util.stream.Collectors;
34 import javax.servlet.http.HttpServletRequest;
35 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
36 import org.onap.portalsdk.core.web.support.UserUtils;
37 import org.onap.vid.aai.exceptions.RoleParsingException;
38 import org.onap.vid.model.ModelConstants;
39 import org.onap.vid.model.Subscriber;
40 import org.onap.vid.model.SubscriberList;
41 import org.onap.vid.services.AaiService;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.stereotype.Component;
44
45
46 /**
47  * Created by Oren on 7/1/17.
48  */
49
50 @Component
51 public class RoleProvider {
52
53     private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(RoleProvider.class);
54     static final String READ_PERMISSION_STRING = "read";
55     private final ObjectMapper om = new ObjectMapper();
56
57     private AaiService aaiService;
58
59     private Function<HttpServletRequest, Integer> getUserIdFunction;
60     private Function<HttpServletRequest, Map> getRolesFunction;
61
62     @Autowired
63     public RoleProvider(AaiService aaiService) {
64         this.aaiService=aaiService;
65         getUserIdFunction = UserUtils::getUserId;
66         getRolesFunction = UserUtils::getRoles;
67     }
68
69     RoleProvider(AaiService aaiService, Function<HttpServletRequest, Integer> getUserIdFunction, Function<HttpServletRequest, Map> getRolesFunction) {
70         this.aaiService = aaiService;
71         this.getRolesFunction = getRolesFunction;
72         this.getUserIdFunction = getUserIdFunction;
73     }
74
75     public List<Role> getUserRoles(HttpServletRequest request) {
76         int userId= getUserIdFunction.apply(request);
77         String logPrefix = "Role Provider (" + userId + ") ==>";
78
79         LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Entering to get user role for user " + userId);
80
81         List<Role> roleList = new ArrayList<>();
82         Map roles = getRolesFunction.apply(request);
83         for (Object role : roles.keySet()) {
84             org.onap.portalsdk.core.domain.Role sdkRol = (org.onap.portalsdk.core.domain.Role) roles.get(role);
85
86             LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Role " + sdkRol.getName() + " is being proccessed");
87             try {
88                 if (sdkRol.getName().contains(READ_PERMISSION_STRING)) {
89                     LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + " Role " + sdkRol.getName() + " contain " + READ_PERMISSION_STRING);
90
91                     continue;
92                 }
93                 String[] roleParts = splitRole((sdkRol.getName()), logPrefix);
94                 roleList.add(createRoleFromStringArr(roleParts, logPrefix));
95                 String msg = String.format("%s User %s got permissions %s", logPrefix, userId, Arrays.toString(roleParts));
96                 LOG.debug(EELFLoggerDelegate.debugLogger, msg);
97             } catch (Exception e) {
98                 LOG.error(logPrefix + " Failed to parse permission");
99
100             }
101         }
102
103         return roleList;
104     }
105
106     public String[] splitRole(String roleAsString, String logPrefix) {
107         LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Spliting role = " + roleAsString + "With delimeter = " + ModelConstants.ROLE_DELIMITER);
108         return roleAsString.split(ModelConstants.ROLE_DELIMITER);
109     }
110
111     public boolean userPermissionIsReadOnly(List<Role> roles) {
112         return roles.isEmpty();
113     }
114
115     public boolean userPermissionIsReadLogs(List<Role> roles){
116         for(Role role: roles){
117             if ( role.getServiceType().equals("LOGS") && role.getTenant().equals("PERMITTED") ) {
118                 return true;
119             }
120         }
121         return false;
122     }
123
124     private String replaceSubscriberNameToGlobalCustomerID(String subscriberName, String logPrefix) {
125         // SubscriberList should be cached by cacheProvider so by calling getFullSubscriberList() method we just gat it from cache
126         HttpResponse<SubscriberList> subscribersResponse = aaiService.getFullSubscriberList();
127         SubscriberList subscribers = subscribersResponse.getBody();
128
129         try {
130             LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "subscribers list size is  " + subscribers.customer.size() + " with the values " + om.writeValueAsString(subscribers.customer));
131         } catch (JsonProcessingException e) {
132             // log subscriberNames without object mapper
133             LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "subscribers list size is  " + subscribers.customer.size()
134                     + " with the values " + subscribers.customer.stream().map(subscriber -> subscriber.subscriberName).collect(Collectors.joining(",")));
135         }
136
137         Optional<Subscriber> s = subscribers.customer.stream().filter(x -> x.subscriberName.equals(subscriberName)).findFirst();
138         //Fixing bug of logging "optional get" before isPresent
139         String replacement = s.isPresent() ? s.get().globalCustomerId : "";
140         LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Subscribername " + subscriberName + " changed to  " + replacement);
141         return replacement;
142     }
143
144     public Role createRoleFromStringArr(String[] roleParts, String rolePrefix) throws RoleParsingException {
145         String globalCustomerID = replaceSubscriberNameToGlobalCustomerID(roleParts[0], rolePrefix);
146         try {
147             if (roleParts.length > 2) {
148                 return new Role(EcompRole.READ, globalCustomerID, roleParts[1], roleParts[2]);
149             } else {
150                 return new Role(EcompRole.READ, globalCustomerID, roleParts[1], null);
151             }
152         } catch (ArrayIndexOutOfBoundsException e) {
153             if (roleParts.length > 0)
154                 LOG.debug(EELFLoggerDelegate.debugLogger, "Could not parse role ", roleParts[0]);
155             else {
156                 LOG.debug(EELFLoggerDelegate.debugLogger, "Got empty role, Could not parse it ");
157
158             }
159             throw new RoleParsingException();
160         }
161
162     }
163
164     public RoleValidator getUserRolesValidator(HttpServletRequest request) {
165         return RoleValidator.by(getUserRoles(request));
166     }
167 }
168