create RoleValidatorFactory component.
[vid.git] / vid-app-common / src / main / java / org / onap / vid / roles / RoleProvider.java
index 45835d4..d9f2fde 100644 (file)
@@ -1,7 +1,36 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2018 - 2019 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
 package org.onap.vid.roles;
 
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import javax.servlet.http.HttpServletRequest;
 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 import org.onap.portalsdk.core.web.support.UserUtils;
 import org.onap.vid.aai.AaiResponse;
@@ -13,10 +42,6 @@ import org.onap.vid.services.AaiService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import javax.servlet.http.HttpServletRequest;
-import java.util.*;
-
-//import org.codehaus.jackson.map.ObjectMapper;
 
 /**
  * Created by Oren on 7/1/17.
@@ -26,52 +51,58 @@ import java.util.*;
 public class RoleProvider {
 
     private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(RoleProvider.class);
-    final String readPermissionString = "read";
-    SubscriberList subscribers;
-    ObjectMapper om = new ObjectMapper();
-    @Autowired
-    private AaiService aaiService;
+    static final String READ_PERMISSION_STRING = "read";
+    private final ObjectMapper om = new ObjectMapper();
 
-    public static List<String> extractRoleFromSession(HttpServletRequest request) {
+    private AaiService aaiService;
 
-        return new ArrayList<String>();
+    private Function<HttpServletRequest, Integer> getUserIdFunction;
+    private Function<HttpServletRequest, Map> getRolesFunction;
+    private final RoleValidatorFactory roleValidatorFactory;
 
+    @Autowired
+    public RoleProvider(AaiService aaiService, RoleValidatorFactory roleValidatorFactory) {
+        this.aaiService=aaiService;
+        this.roleValidatorFactory = roleValidatorFactory;
+        getUserIdFunction = UserUtils::getUserId;
+        getRolesFunction = UserUtils::getRoles;
     }
 
-    public void init() {
-        LOG.debug(EELFLoggerDelegate.debugLogger, "Role provider => init method started");
-        AaiResponse<SubscriberList> subscribersResponse = aaiService.getFullSubscriberList();
-        subscribers = subscribersResponse.getT();
-        LOG.debug(EELFLoggerDelegate.debugLogger, "Role provider => init method finished");
+    RoleProvider(AaiService aaiService, RoleValidatorFactory roleValidatorFactory,
+        Function<HttpServletRequest, Integer> getUserIdFunction, Function<HttpServletRequest, Map> getRolesFunction) {
+        this.aaiService = aaiService;
+        this.roleValidatorFactory = roleValidatorFactory;
+        this.getRolesFunction = getRolesFunction;
+        this.getUserIdFunction = getUserIdFunction;
     }
 
-    public List<Role> getUserRoles(HttpServletRequest request) throws JsonProcessingException {
-        String logPrefix = "Role Provider (" + UserUtils.getUserId(request) + ") ==>";
+    public List<Role> getUserRoles(HttpServletRequest request) {
+        int userId= getUserIdFunction.apply(request);
+        String logPrefix = "Role Provider (" + userId + ") ==>";
 
-        LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Entering to get user role for user " + UserUtils.getUserId(request));
+        LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Entering to get user role for user " + userId);
 
         List<Role> roleList = new ArrayList<>();
-        //Disable roles until AAF integration finishes
-        /*HashMap roles = UserUtils.getRoles(request);
+        Map roles = getRolesFunction.apply(request);
         for (Object role : roles.keySet()) {
-            org.openecomp.portalsdk.core.domain.Role sdkRol = (org.openecomp.portalsdk.core.domain.Role) roles.get(role);
+            org.onap.portalsdk.core.domain.Role sdkRol = (org.onap.portalsdk.core.domain.Role) roles.get(role);
 
             LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Role " + sdkRol.getName() + " is being proccessed");
             try {
-                if (sdkRol.getName().contains(readPermissionString)) {
-                    LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + " Role " + sdkRol.getName() + " contain " + readPermissionString);
+                if (sdkRol.getName().contains(READ_PERMISSION_STRING)) {
+                    LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + " Role " + sdkRol.getName() + " contain " + READ_PERMISSION_STRING);
 
                     continue;
                 }
                 String[] roleParts = splitRole((sdkRol.getName()), logPrefix);
                 roleList.add(createRoleFromStringArr(roleParts, logPrefix));
-                String msg = String.format(logPrefix + " User %s got permissions %s", UserUtils.getUserId(request), Arrays.toString(roleParts));
+                String msg = String.format("%s User %s got permissions %s", logPrefix, userId, Arrays.toString(roleParts));
                 LOG.debug(EELFLoggerDelegate.debugLogger, msg);
-            } catch (RoleParsingException e) {
+            } catch (Exception e) {
                 LOG.error(logPrefix + " Failed to parse permission");
 
             }
-        }*/
+        }
 
         return roleList;
     }
@@ -82,29 +113,30 @@ public class RoleProvider {
     }
 
     public boolean userPermissionIsReadOnly(List<Role> roles) {
-
-        return (!(roles.size() > 0));
+        return roles.isEmpty();
     }
 
     public boolean userPermissionIsReadLogs(List<Role> roles){
         for(Role role: roles){
-            if(role.getServiceType().equals("LOGS")){
-                if(role.getTenant().equals("PERMITTED")){
-                    return true;
-                }
+            if ( role.getServiceType().equals("LOGS") && role.getTenant().equals("PERMITTED") ) {
+                return true;
             }
         }
         return false;
     }
 
-    private String replaceSubscriberNameToGlobalCustomerID(String subscriberName, String logPrefix) throws JsonProcessingException {
-        if (subscribers == null) {
-            LOG.debug(EELFLoggerDelegate.debugLogger, "replaceSubscriberNameToGlobalCustomerID calling init method");
-            init();
-        }
-        LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "subscribers list size is  " + subscribers.customer.size() + " with the values " + om.writeValueAsString(subscribers.customer));
-        LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "subscribers list size is  " + subscribers.customer.size() + " with the values " + om.writeValueAsString(subscribers.customer));
+    private String replaceSubscriberNameToGlobalCustomerID(String subscriberName, String logPrefix) {
+        // SubscriberList should be cached by cacheProvider so by calling getFullSubscriberList() method we just gat it from cache
+        AaiResponse<SubscriberList> subscribersResponse = aaiService.getFullSubscriberList();
+        SubscriberList subscribers = subscribersResponse.getT();
 
+        try {
+            LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "subscribers list size is  " + subscribers.customer.size() + " with the values " + om.writeValueAsString(subscribers.customer));
+        } catch (JsonProcessingException e) {
+            // log subscriberNames without object mapper
+            LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "subscribers list size is  " + subscribers.customer.size()
+                    + " with the values " + subscribers.customer.stream().map(subscriber -> subscriber.subscriberName).collect(Collectors.joining(",")));
+        }
 
         Optional<Subscriber> s = subscribers.customer.stream().filter(x -> x.subscriberName.equals(subscriberName)).findFirst();
         //Fixing bug of logging "optional get" before isPresent
@@ -113,7 +145,7 @@ public class RoleProvider {
         return replacement;
     }
 
-    public Role createRoleFromStringArr(String[] roleParts, String rolePrefix) throws JsonProcessingException, RoleParsingException {
+    public Role createRoleFromStringArr(String[] roleParts, String rolePrefix) throws RoleParsingException {
         String globalCustomerID = replaceSubscriberNameToGlobalCustomerID(roleParts[0], rolePrefix);
         try {
             if (roleParts.length > 2) {
@@ -133,5 +165,8 @@ public class RoleProvider {
 
     }
 
+    public RoleValidator getUserRolesValidator(HttpServletRequest request) {
+        return roleValidatorFactory.by(getUserRoles(request));
+    }
 }