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