d9f2fdedfb54b966d6c068847e3e9d3732823d5e
[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 java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Optional;
31 import java.util.function.Function;
32 import java.util.stream.Collectors;
33 import javax.servlet.http.HttpServletRequest;
34 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
35 import org.onap.portalsdk.core.web.support.UserUtils;
36 import org.onap.vid.aai.AaiResponse;
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     private final RoleValidatorFactory roleValidatorFactory;
62
63     @Autowired
64     public RoleProvider(AaiService aaiService, RoleValidatorFactory roleValidatorFactory) {
65         this.aaiService=aaiService;
66         this.roleValidatorFactory = roleValidatorFactory;
67         getUserIdFunction = UserUtils::getUserId;
68         getRolesFunction = UserUtils::getRoles;
69     }
70
71     RoleProvider(AaiService aaiService, RoleValidatorFactory roleValidatorFactory,
72         Function<HttpServletRequest, Integer> getUserIdFunction, Function<HttpServletRequest, Map> getRolesFunction) {
73         this.aaiService = aaiService;
74         this.roleValidatorFactory = roleValidatorFactory;
75         this.getRolesFunction = getRolesFunction;
76         this.getUserIdFunction = getUserIdFunction;
77     }
78
79     public List<Role> getUserRoles(HttpServletRequest request) {
80         int userId= getUserIdFunction.apply(request);
81         String logPrefix = "Role Provider (" + userId + ") ==>";
82
83         LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Entering to get user role for user " + userId);
84
85         List<Role> roleList = new ArrayList<>();
86         Map roles = getRolesFunction.apply(request);
87         for (Object role : roles.keySet()) {
88             org.onap.portalsdk.core.domain.Role sdkRol = (org.onap.portalsdk.core.domain.Role) roles.get(role);
89
90             LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Role " + sdkRol.getName() + " is being proccessed");
91             try {
92                 if (sdkRol.getName().contains(READ_PERMISSION_STRING)) {
93                     LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + " Role " + sdkRol.getName() + " contain " + READ_PERMISSION_STRING);
94
95                     continue;
96                 }
97                 String[] roleParts = splitRole((sdkRol.getName()), logPrefix);
98                 roleList.add(createRoleFromStringArr(roleParts, logPrefix));
99                 String msg = String.format("%s User %s got permissions %s", logPrefix, userId, Arrays.toString(roleParts));
100                 LOG.debug(EELFLoggerDelegate.debugLogger, msg);
101             } catch (Exception e) {
102                 LOG.error(logPrefix + " Failed to parse permission");
103
104             }
105         }
106
107         return roleList;
108     }
109
110     public String[] splitRole(String roleAsString, String logPrefix) {
111         LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Spliting role = " + roleAsString + "With delimeter = " + ModelConstants.ROLE_DELIMITER);
112         return roleAsString.split(ModelConstants.ROLE_DELIMITER);
113     }
114
115     public boolean userPermissionIsReadOnly(List<Role> roles) {
116         return roles.isEmpty();
117     }
118
119     public boolean userPermissionIsReadLogs(List<Role> roles){
120         for(Role role: roles){
121             if ( role.getServiceType().equals("LOGS") && role.getTenant().equals("PERMITTED") ) {
122                 return true;
123             }
124         }
125         return false;
126     }
127
128     private String replaceSubscriberNameToGlobalCustomerID(String subscriberName, String logPrefix) {
129         // SubscriberList should be cached by cacheProvider so by calling getFullSubscriberList() method we just gat it from cache
130         AaiResponse<SubscriberList> subscribersResponse = aaiService.getFullSubscriberList();
131         SubscriberList subscribers = subscribersResponse.getT();
132
133         try {
134             LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "subscribers list size is  " + subscribers.customer.size() + " with the values " + om.writeValueAsString(subscribers.customer));
135         } catch (JsonProcessingException e) {
136             // log subscriberNames without object mapper
137             LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "subscribers list size is  " + subscribers.customer.size()
138                     + " with the values " + subscribers.customer.stream().map(subscriber -> subscriber.subscriberName).collect(Collectors.joining(",")));
139         }
140
141         Optional<Subscriber> s = subscribers.customer.stream().filter(x -> x.subscriberName.equals(subscriberName)).findFirst();
142         //Fixing bug of logging "optional get" before isPresent
143         String replacement = s.isPresent() ? s.get().globalCustomerId : "";
144         LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Subscribername " + subscriberName + " changed to  " + replacement);
145         return replacement;
146     }
147
148     public Role createRoleFromStringArr(String[] roleParts, String rolePrefix) throws RoleParsingException {
149         String globalCustomerID = replaceSubscriberNameToGlobalCustomerID(roleParts[0], rolePrefix);
150         try {
151             if (roleParts.length > 2) {
152                 return new Role(EcompRole.READ, globalCustomerID, roleParts[1], roleParts[2]);
153             } else {
154                 return new Role(EcompRole.READ, globalCustomerID, roleParts[1], null);
155             }
156         } catch (ArrayIndexOutOfBoundsException e) {
157             if (roleParts.length > 0)
158                 LOG.debug(EELFLoggerDelegate.debugLogger, "Could not parse role ", roleParts[0]);
159             else {
160                 LOG.debug(EELFLoggerDelegate.debugLogger, "Got empty role, Could not parse it ");
161
162             }
163             throw new RoleParsingException();
164         }
165
166     }
167
168     public RoleValidator getUserRolesValidator(HttpServletRequest request) {
169         return roleValidatorFactory.by(getUserRoles(request));
170     }
171 }
172