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