Repository: ranger
Updated Branches:
  refs/heads/master 0878d19e9 -> 9f5721bbe


RANGER-1491 : Automatically map group of external users to Administrator Role

Signed-off-by: Gautam Borad <gau...@apache.org>


Project: http://git-wip-us.apache.org/repos/asf/ranger/repo
Commit: http://git-wip-us.apache.org/repos/asf/ranger/commit/9f5721bb
Tree: http://git-wip-us.apache.org/repos/asf/ranger/tree/9f5721bb
Diff: http://git-wip-us.apache.org/repos/asf/ranger/diff/9f5721bb

Branch: refs/heads/master
Commit: 9f5721bbed8057586e63a5ea5552ddecf5cc67ca
Parents: 0878d19
Author: Bhavik Patel <bhavikpatel...@gmail.com>
Authored: Mon Aug 7 15:47:00 2017 +0530
Committer: Gautam Borad <gau...@apache.org>
Committed: Fri Aug 11 12:12:57 2017 +0530

----------------------------------------------------------------------
 .../java/org/apache/ranger/biz/UserMgr.java     |  96 +++++--
 .../java/org/apache/ranger/biz/XUserMgr.java    | 169 +++++++----
 .../org/apache/ranger/service/XUserService.java |   8 +-
 .../java/org/apache/ranger/view/VXUser.java     |   1 +
 .../java/org/apache/ranger/biz/TestUserMgr.java |   4 +-
 .../org/apache/ranger/biz/TestXUserMgr.java     | 141 ++++++----
 .../process/LdapPolicyMgrUserGroupBuilder.java  | 156 ++++++++--
 .../config/UserGroupSyncConfig.java             |  53 ++++
 .../ranger/unixusersync/model/XUserInfo.java    |  20 +-
 .../process/PolicyMgrUserGroupBuilder.java      | 281 ++++++++++++++++---
 unixauthservice/scripts/install.properties      |  16 ++
 unixauthservice/scripts/setup.py                |  18 ++
 .../templates/installprop2xml.properties        |   4 +
 .../templates/ranger-ugsync-template.xml        |  16 ++
 14 files changed, 777 insertions(+), 206 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java 
b/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java
index 6f77832..c1145e7 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java
@@ -142,6 +142,7 @@ public class UserMgr {
                        Collection<String> userRoleList) {
                XXPortalUser user = mapVXPortalUserToXXPortalUser(userProfile);
                checkAdminAccess();
+        xUserMgr.checkAccessRoles((List<String>) userRoleList);
                user = createUser(user, userStatus, userRoleList);
 
                return user;
@@ -174,9 +175,13 @@ public class UserMgr {
                ArrayList<String> roleList = new ArrayList<String>();
                Collection<String> reqRoleList = userProfile.getUserRoleList();
                if (reqRoleList != null && reqRoleList.size() > 0) {
-                       for (String role : reqRoleList) {
-                               roleList.add(role);
-                       }
+            for (String role : reqRoleList) {
+                if (role != null) {
+                    roleList.add(role);
+                } else {
+                    roleList.add(RangerConstants.ROLE_USER);
+                }
+            }
                } else {
                        roleList.add(RangerConstants.ROLE_USER);
                }
@@ -1104,16 +1109,18 @@ public class UserMgr {
                checkAdminAccess();
                logger.info("create:" + userProfile.getLoginId());
                XXPortalUser xXPortalUser = null;
+                Collection<String> existingRoleList = null;
+                Collection<String> reqRoleList = null;
                String loginId = userProfile.getLoginId();
                String emailAddress = userProfile.getEmailAddress();
 
-               if (loginId != null && !loginId.isEmpty()) {
+                if (loginId != null && !loginId.isEmpty()) {
                        xXPortalUser = this.findByLoginId(loginId);
                        if (xXPortalUser == null) {
                                if (!stringUtil.isEmpty(emailAddress)) {
                                        xXPortalUser = 
this.findByEmailAddress(emailAddress);
                                        if (xXPortalUser == null) {
-                                               xXPortalUser = 
this.createUser(userProfile,
+                                            xXPortalUser = 
this.createUser(userProfile,
                                                                
RangerCommonEnums.STATUS_ENABLED);
                                        } else {
                                                throw restErrorUtil
@@ -1125,9 +1132,9 @@ public class UserMgr {
                                                                                
MessageEnums.OPER_NOT_ALLOWED_FOR_STATE);
                                        }
                                } else {
-                                       userProfile.setEmailAddress(null);
-                                       xXPortalUser = 
this.createUser(userProfile,
-                                                       
RangerCommonEnums.STATUS_ENABLED);
+                        userProfile.setEmailAddress(null);
+                        xXPortalUser = this.createUser(userProfile,
+                                RangerCommonEnums.STATUS_ENABLED);
                                }
                        } else { //NOPMD
                                /*
@@ -1137,16 +1144,71 @@ public class UserMgr {
                                 * + "login id.", 
MessageEnums.OPER_NOT_ALLOWED_FOR_STATE);
                                 */
                        }
-               }
-               if (xXPortalUser != null) {
-                       return 
mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser);
-               } else {
-                       return null;
-               }
-       }
+        }
+        VXPortalUser userProfileRes = null;
+        if (xXPortalUser != null) {
+            userProfileRes = 
mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser);
+            if (userProfile.getUserRoleList() != null
+                    && userProfile.getUserRoleList().size() > 0
+                    && ((List<String>) userProfile.getUserRoleList()).get(0) 
!= null) {
+                reqRoleList = userProfile.getUserRoleList();
+                existingRoleList = this.getRolesByLoginId(loginId);
+                XXPortalUser xxPortalUser = daoManager.getXXPortalUser()
+                        .findByLoginId(userProfile.getLoginId());
+                if (xxPortalUser != null
+                        && xxPortalUser.getUserSource() == 
RangerCommonEnums.USER_EXTERNAL) {
+                    userProfileRes = updateRoleForExternalUsers(reqRoleList,
+                            existingRoleList, userProfileRes);
+                }
+            }
+        }
+        return userProfileRes;
+        }
+
+    protected VXPortalUser updateRoleForExternalUsers(
+            Collection<String> reqRoleList,
+            Collection<String> existingRoleList, VXPortalUser userProfileRes) {
+        UserSessionBase session = ContextUtil.getCurrentUserSession();
+        if ("rangerusersync".equals(session.getXXPortalUser().getLoginId())
+                && reqRoleList != null && !reqRoleList.isEmpty()
+                && existingRoleList != null && !existingRoleList.isEmpty()) {
+            if (!reqRoleList.equals(existingRoleList)) {
+                userProfileRes.setUserRoleList(reqRoleList);
+                userProfileRes.setUserSource(RangerCommonEnums.USER_EXTERNAL);
+                List<XXUserPermission> xuserPermissionList = daoManager
+                        .getXXUserPermission().findByUserPermissionId(
+                                userProfileRes.getId());
+                if (xuserPermissionList != null
+                        && xuserPermissionList.size() > 0) {
+                    for (XXUserPermission xXUserPermission : 
xuserPermissionList) {
+                        if (xXUserPermission != null) {
+                            try {
+                                xUserPermissionService
+                                        .deleteResource(xXUserPermission
+                                                .getId());
+                            } catch (Exception e) {
+                                logger.error(e.getMessage());
+                            }
+                        }
+
+                    }
+                }
+                updateUser(userProfileRes);
+            }
+        } else {
+            if (logger.isDebugEnabled()) {
+                logger.debug("Permission"
+                        + " denied. LoggedInUser="
+                        + (session != null ? session.getXXPortalUser().getId()
+                                : "")
+                        + " isn't permitted to perform the action.");
+            }
+        }
+        return userProfileRes;
+    }
 
-       protected VXPortalUser mapXXPortalUserToVXPortalUserForDefaultAccount(
-                       XXPortalUser user) {
+        protected VXPortalUser mapXXPortalUserToVXPortalUserForDefaultAccount(
+                        XXPortalUser user) {
 
                VXPortalUser userProfile = new VXPortalUser();
 

http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java 
b/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java
index ca06805..5a5335a 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java
@@ -156,6 +156,9 @@ public class XUserMgr extends XUserMgrBase {
        @Autowired
        GUIDUtil guidUtil;
 
+    @Autowired
+    UserMgr userManager;
+
        static final Logger logger = Logger.getLogger(XUserMgr.class);
 
 
@@ -514,33 +517,36 @@ public class XUserMgr extends XUserMgrBase {
                return vXUser;
        }
 
-       public VXUserGroupInfo createXUserGroupFromMap(
-                       VXUserGroupInfo vXUserGroupInfo) {
+        public VXUserGroupInfo createXUserGroupFromMap(VXUserGroupInfo 
vXUserGroupInfo) {
                checkAdminAccess();
                VXUserGroupInfo vxUGInfo = new VXUserGroupInfo();
-
-               VXUser vXUser = vXUserGroupInfo.getXuserInfo();
-
-               vXUser = xUserService.createXUserWithOutLogin(vXUser);
-
-               vxUGInfo.setXuserInfo(vXUser);
-
-               List<VXGroup> vxg = new ArrayList<VXGroup>();
-
-               for (VXGroup vXGroup : vXUserGroupInfo.getXgroupInfo()) {
-                       VXGroup VvXGroup = 
xGroupService.createXGroupWithOutLogin(vXGroup);
-                       vxg.add(VvXGroup);
-                       VXGroupUser vXGroupUser = new VXGroupUser();
-                       vXGroupUser.setUserId(vXUser.getId());
-                       vXGroupUser.setName(VvXGroup.getName());
-                       vXGroupUser = xGroupUserService
-                                       
.createXGroupUserWithOutLogin(vXGroupUser);
-               }
-               VXPortalUser vXPortalUser = 
userMgr.getUserProfileByLoginId(vXUser
-                               .getName());
-               if(vXPortalUser!=null){
-                       assignPermissionToUser(vXPortalUser, true);
-               }
+        VXUser vXUser = vXUserGroupInfo.getXuserInfo();
+        VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(vXUser
+                .getName());
+        XXPortalUser xxPortalUser = daoManager.getXXPortalUser().findByLoginId(
+                vXUser.getName());
+        Collection<String> reqRoleList = vXUser.getUserRoleList();
+        List<String> existingRole = daoManager.getXXPortalUserRole()
+                .findXPortalUserRolebyXPortalUserId(xxPortalUser.getId());
+        if (xxPortalUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) {
+            vXPortalUser = userManager.updateRoleForExternalUsers(reqRoleList,
+                    existingRole, vXPortalUser);
+        }
+        vXUser = xUserService.createXUserWithOutLogin(vXUser);
+        vxUGInfo.setXuserInfo(vXUser);
+        List<VXGroup> vxg = new ArrayList<VXGroup>();
+        for (VXGroup vXGroup : vXUserGroupInfo.getXgroupInfo()) {
+            VXGroup VvXGroup = xGroupService.createXGroupWithOutLogin(vXGroup);
+            vxg.add(VvXGroup);
+            VXGroupUser vXGroupUser = new VXGroupUser();
+            vXGroupUser.setUserId(vXUser.getId());
+            vXGroupUser.setName(VvXGroup.getName());
+            vXGroupUser = xGroupUserService
+                    .createXGroupUserWithOutLogin(vXGroupUser);
+        }
+        if (vXPortalUser != null) {
+            assignPermissionToUser(vXPortalUser, true);
+        }
                vxUGInfo.setXgroupInfo(vxg);
 
                return vxUGInfo;
@@ -560,10 +566,12 @@ public class XUserMgr extends XUserMgrBase {
                }*/
 
                List<VXUser> vxu = new ArrayList<VXUser>();
-
-               for (VXUser vXUser : vXGroupUserInfo.getXuserInfo()) {
-                       XXUser xUser = 
daoManager.getXXUser().findByUserName(vXUser.getName());
-                       if (xUser != null) {
+        for (VXUser vXUser : vXGroupUserInfo.getXuserInfo()) {
+            XXUser xUser = daoManager.getXXUser().findByUserName(
+                    vXUser.getName());
+            XXPortalUser xXPortalUser = daoManager.getXXPortalUser()
+                    .findByLoginId(vXUser.getName());
+            if (xUser != null) {
                                // Add or update group user mapping only if the 
user already exists in x_user table.
                                vXGroup = 
xGroupService.createXGroupWithOutLogin(vXGroup);
                                vxGUInfo.setXgroupInfo(vXGroup);
@@ -571,8 +579,24 @@ public class XUserMgr extends XUserMgrBase {
                                VXGroupUser vXGroupUser = new VXGroupUser();
                                vXGroupUser.setUserId(xUser.getId());
                                vXGroupUser.setName(vXGroup.getName());
-                               vXGroupUser = xGroupUserService
-                                               
.createXGroupUserWithOutLogin(vXGroupUser);
+                if (xXPortalUser.getUserSource() == 
RangerCommonEnums.USER_EXTERNAL) {
+                    vXGroupUser = xGroupUserService
+                            .createXGroupUserWithOutLogin(vXGroupUser);
+                }
+                Collection<String> reqRoleList = vXUser.getUserRoleList();
+
+                XXPortalUser xxPortalUser = daoManager.getXXPortalUser()
+                        .findByLoginId(vXUser.getName());
+                List<String> existingRole = daoManager.getXXPortalUserRole()
+                        .findXPortalUserRolebyXPortalUserId(
+                                xxPortalUser.getId());
+                VXPortalUser vxPortalUser = userManager
+                        
.mapXXPortalUserToVXPortalUserForDefaultAccount(xxPortalUser);
+                if (xxPortalUser.getUserSource() == 
RangerCommonEnums.USER_EXTERNAL) {
+                    vxPortalUser = userManager.updateRoleForExternalUsers(
+                            reqRoleList, existingRole, vxPortalUser);
+                    assignPermissionToUser(vxPortalUser, true);
+                }
                        }
                }
 
@@ -605,6 +629,17 @@ public class XUserMgr extends XUserMgrBase {
                        if (xUser != null) {
                                VXUser vxUser = new VXUser();
                                vxUser.setName(xUser.getName());
+                XXPortalUser xXPortalUser = daoManager.getXXPortalUser()
+                        .findByLoginId(xUser.getName());
+                if (xXPortalUser != null) {
+                    List<String> existingRole = daoManager
+                            .getXXPortalUserRole()
+                            .findXPortalUserRolebyXPortalUserId(
+                                    xXPortalUser.getId());
+                    if (existingRole != null) {
+                        vxUser.setUserRoleList(existingRole);
+                    }
+                }
                                vxu.add(vxUser);
                        }
                        
@@ -1270,36 +1305,48 @@ public class XUserMgr extends XUserMgrBase {
        }
 
        public void checkAccessRoles(List<String> stringRolesList) {
-               UserSessionBase session = ContextUtil.getCurrentUserSession();
-               if (session != null && stringRolesList!=null) {
-                       if (!session.isUserAdmin() && !session.isKeyAdmin()) {
-                               throw 
restErrorUtil.create403RESTException("Permission"
-                                               + " denied. LoggedInUser="
-                                               + (session != null ? 
session.getXXPortalUser().getId()
-                                                               : "Not Logged 
In")
-                                               + " ,isn't permitted to perform 
the action.");
-                       }else{
-                               if (session.isUserAdmin() && 
stringRolesList.contains(RangerConstants.ROLE_KEY_ADMIN)) {
-                                       throw 
restErrorUtil.create403RESTException("Permission"
-                                                       + " denied. 
LoggedInUser="
-                                                       + (session != null ? 
session.getXXPortalUser().getId()
-                                                                       : "")
-                                                       + " isn't permitted to 
perform the action.");
-                               }
-                               if (session.isKeyAdmin() && 
stringRolesList.contains(RangerConstants.ROLE_SYS_ADMIN)) {
-                                       throw 
restErrorUtil.create403RESTException("Permission"
-                                                       + " denied. 
LoggedInUser="
-                                                       + (session != null ? 
session.getXXPortalUser().getId()
-                                                                       : "")
-                                                       + " isn't permitted to 
perform the action.");
-                               }
-                       }
-               }else{
-                       VXResponse vXResponse = new VXResponse();
-                       
vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
-                       vXResponse.setMsgDesc("Bad Credentials");
-                       throw restErrorUtil.generateRESTException(vXResponse);
-               }
+        UserSessionBase session = ContextUtil.getCurrentUserSession();
+        if (session != null && stringRolesList != null) {
+            if (!session.isUserAdmin() && !session.isKeyAdmin()) {
+                throw restErrorUtil.create403RESTException("Permission"
+                        + " denied. LoggedInUser="
+                        + (session != null ? session.getXXPortalUser().getId()
+                                : "Not Logged In")
+                        + " ,isn't permitted to perform the action.");
+            } else {
+                if (!"rangerusersync".equals(session.getXXPortalUser()
+                        .getLoginId())) {// new logic for rangerusersync user
+                    if (session.isUserAdmin()
+                            && stringRolesList
+                                    .contains(RangerConstants.ROLE_KEY_ADMIN)) 
{
+                        throw restErrorUtil.create403RESTException("Permission"
+                                + " denied. LoggedInUser="
+                                + (session != null ? session.getXXPortalUser()
+                                        .getId() : "")
+                                + " isn't permitted to perform the action.");
+                    }
+                    if (session.isKeyAdmin()
+                            && stringRolesList
+                                    .contains(RangerConstants.ROLE_SYS_ADMIN)) 
{
+                        throw restErrorUtil.create403RESTException("Permission"
+                                + " denied. LoggedInUser="
+                                + (session != null ? session.getXXPortalUser()
+                                        .getId() : "")
+                                + " isn't permitted to perform the action.");
+                    }
+                } else {
+                    logger.info("LoggedInUser="
+                            + (session != null ? session.getXXPortalUser()
+                                    .getId()
+                                    : " is permitted to perform the action"));
+                }
+            }
+        } else {
+            VXResponse vXResponse = new VXResponse();
+            vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
+            vXResponse.setMsgDesc("Bad Credentials");
+            throw restErrorUtil.generateRESTException(vXResponse);
+        }
        }
 
        public VXStringList setUserRolesByExternalID(Long userId, 
List<VXString> vStringRolesList) {

http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/security-admin/src/main/java/org/apache/ranger/service/XUserService.java
----------------------------------------------------------------------
diff --git 
a/security-admin/src/main/java/org/apache/ranger/service/XUserService.java 
b/security-admin/src/main/java/org/apache/ranger/service/XUserService.java
index de95138..294223b 100644
--- a/security-admin/src/main/java/org/apache/ranger/service/XUserService.java
+++ b/security-admin/src/main/java/org/apache/ranger/service/XUserService.java
@@ -31,6 +31,7 @@ import org.apache.ranger.biz.RangerBizUtil;
 import org.apache.ranger.common.AppConstants;
 import org.apache.ranger.common.MessageEnums;
 import org.apache.ranger.common.PropertiesUtil;
+import org.apache.ranger.common.RangerCommonEnums;
 import org.apache.ranger.common.RangerConstants;
 import org.apache.ranger.common.SearchField;
 import org.apache.ranger.common.SortField;
@@ -167,7 +168,12 @@ public class XUserService extends XUserServiceBase<XXUser, 
VXUser> {
                        xxUser = new XXUser();
                        userExists = false;
                }
-
+        XXPortalUser xxPortalUser = daoManager.getXXPortalUser().findByLoginId(
+                vxUser.getName());
+        if (xxPortalUser != null
+                && xxPortalUser.getUserSource() == 
RangerCommonEnums.USER_EXTERNAL) {
+            vxUser.setIsVisible(xxUser.getIsVisible());
+        }
                xxUser = mapViewToEntityBean(vxUser, xxUser, 0);
                XXPortalUser xXPortalUser = 
daoManager.getXXPortalUser().getById(createdByUserId);
                if (xXPortalUser != null) {

http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/security-admin/src/main/java/org/apache/ranger/view/VXUser.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXUser.java 
b/security-admin/src/main/java/org/apache/ranger/view/VXUser.java
index ecfd1ac..1c01219 100644
--- a/security-admin/src/main/java/org/apache/ranger/view/VXUser.java
+++ b/security-admin/src/main/java/org/apache/ranger/view/VXUser.java
@@ -300,6 +300,7 @@ public class VXUser extends VXDataObject implements 
java.io.Serializable {
                str += "isVisible={" + isVisible + "} ";
                str += "groupIdList={" + groupIdList + "} ";
                str += "groupNameList={" + groupNameList + "} ";
+        str += "roleList={" + userRoleList + "} ";
                str += "}";
                return str;
        }

http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/security-admin/src/test/java/org/apache/ranger/biz/TestUserMgr.java
----------------------------------------------------------------------
diff --git 
a/security-admin/src/test/java/org/apache/ranger/biz/TestUserMgr.java 
b/security-admin/src/test/java/org/apache/ranger/biz/TestUserMgr.java
index 5e0ca20..4a8d88f 100644
--- a/security-admin/src/test/java/org/apache/ranger/biz/TestUserMgr.java
+++ b/security-admin/src/test/java/org/apache/ranger/biz/TestUserMgr.java
@@ -757,8 +757,8 @@ public class TestUserMgr {
                                dbVXPortalUser.getEmailAddress());
                Assert.assertEquals(user.getPassword(), 
dbVXPortalUser.getPassword());
 
-               Mockito.verify(daoManager).getXXPortalUser();
-               Mockito.verify(daoManager).getXXPortalUserRole();
+        Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser();
+        Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUserRole();
        }
 
        @Test

http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/security-admin/src/test/java/org/apache/ranger/biz/TestXUserMgr.java
----------------------------------------------------------------------
diff --git 
a/security-admin/src/test/java/org/apache/ranger/biz/TestXUserMgr.java 
b/security-admin/src/test/java/org/apache/ranger/biz/TestXUserMgr.java
index 9846f67..601af14 100644
--- a/security-admin/src/test/java/org/apache/ranger/biz/TestXUserMgr.java
+++ b/security-admin/src/test/java/org/apache/ranger/biz/TestXUserMgr.java
@@ -26,6 +26,8 @@ import java.util.Set;
 
 import org.apache.ranger.common.ContextUtil;
 import org.apache.ranger.common.RESTErrorUtil;
+import org.apache.ranger.common.RangerCommonEnums;
+import org.apache.ranger.common.RangerConstants;
 import org.apache.ranger.common.SearchCriteria;
 import org.apache.ranger.common.StringUtil;
 import org.apache.ranger.common.UserSessionBase;
@@ -172,6 +174,10 @@ public class TestXUserMgr {
                UserSessionBase currentUserSession = ContextUtil
                                .getCurrentUserSession();
                currentUserSession.setUserAdmin(true);
+        XXPortalUser gjUser = new XXPortalUser();
+        gjUser.setLoginId("test");
+        gjUser.setId(1L);
+        currentUserSession.setXXPortalUser(gjUser);
        }
 
        private VXUser vxUser() {
@@ -588,6 +594,8 @@ public class TestXUserMgr {
 
                
Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(
                                vxUser);
+        XXModuleDefDao xxModuleDefDao = Mockito.mock(XXModuleDefDao.class);
+        Mockito.when(daoManager.getXXModuleDef()).thenReturn(xxModuleDefDao);
 
                VXUser dbVXUser = xUserMgr.getXUserByUserName(userName);
                Assert.assertNotNull(dbVXUser);
@@ -595,7 +603,8 @@ public class TestXUserMgr {
                Assert.assertEquals(userId, dbVXUser.getId());
                Assert.assertEquals(dbVXUser.getName(), vxUser.getName());
                Assert.assertEquals(dbVXUser.getOwner(), vxUser.getOwner());
-               Mockito.verify(xUserService).getXUserByUserName(userName);
+        Mockito.verify(xUserService, Mockito.atLeast(2)).getXUserByUserName(
+                userName);
        }
 
        @Test
@@ -785,51 +794,66 @@ public class TestXUserMgr {
 
        @Test
        public void test30CreateVXUserGroupInfo() {
-               setup();
-               VXUserGroupInfo vXUserGroupInfo = new VXUserGroupInfo();
-               VXUser vXUser = new VXUser();
-               vXUser.setName("user1");
-               vXUser.setDescription("testuser1 -added for unit testing");
-                vXUser.setPassword("usertest123");
-               List<VXGroupUser> vXGroupUserList = new 
ArrayList<VXGroupUser>();
-               List<VXGroup> vXGroupList = new ArrayList<VXGroup>();
-
-               final VXGroup vXGroup1 = new VXGroup();
-               vXGroup1.setName("users");
-               vXGroup1.setDescription("users -added for unit testing");
-               vXGroupList.add(vXGroup1);
-
-               VXGroupUser vXGroupUser1 = new VXGroupUser();
-               vXGroupUser1.setName("users");
-               vXGroupUserList.add(vXGroupUser1);
-
-               final VXGroup vXGroup2 = new VXGroup();
-               vXGroup2.setName("user1");
-               vXGroup2.setDescription("user1 -added for unit testing");
-               vXGroupList.add(vXGroup2);
-
-               VXGroupUser vXGroupUser2 = new VXGroupUser();
-               vXGroupUser2.setName("user1");
-               vXGroupUserList.add(vXGroupUser2);
-
-               vXUserGroupInfo.setXuserInfo(vXUser);
-               vXUserGroupInfo.setXgroupInfo(vXGroupList);
-
-               
Mockito.when(xUserService.createXUserWithOutLogin(vXUser)).thenReturn(
-                               vXUser);
-               Mockito.when(xGroupService.createXGroupWithOutLogin(vXGroup1))
-                               .thenReturn(vXGroup1);
-               Mockito.when(xGroupService.createXGroupWithOutLogin(vXGroup2))
-                               .thenReturn(vXGroup2);
-
-               VXUserGroupInfo vxUserGroupTest = xUserMgr
-                               .createXUserGroupFromMap(vXUserGroupInfo);
-               Assert.assertEquals("user1", 
vxUserGroupTest.getXuserInfo().getName());
-               List<VXGroup> result = vxUserGroupTest.getXgroupInfo();
-               List<VXGroup> expected = new ArrayList<VXGroup>();
-               expected.add(vXGroup1);
-               expected.add(vXGroup2);
-               Assert.assertTrue(result.containsAll(expected));
+        setup();
+        VXUserGroupInfo vXUserGroupInfo = new VXUserGroupInfo();
+        VXUser vXUser = new VXUser();
+        vXUser.setName("user1");
+        vXUser.setDescription("testuser1 -added for unit testing");
+        vXUser.setPassword("usertest123");
+        List<VXGroupUser> vXGroupUserList = new ArrayList<VXGroupUser>();
+        List<VXGroup> vXGroupList = new ArrayList<VXGroup>();
+
+        final VXGroup vXGroup1 = new VXGroup();
+        vXGroup1.setName("users");
+        vXGroup1.setDescription("users -added for unit testing");
+        vXGroupList.add(vXGroup1);
+
+        VXGroupUser vXGroupUser1 = new VXGroupUser();
+        vXGroupUser1.setName("users");
+        vXGroupUserList.add(vXGroupUser1);
+
+        final VXGroup vXGroup2 = new VXGroup();
+        vXGroup2.setName("user1");
+        vXGroup2.setDescription("user1 -added for unit testing");
+        vXGroupList.add(vXGroup2);
+
+        VXGroupUser vXGroupUser2 = new VXGroupUser();
+        vXGroupUser2.setName("user1");
+        vXGroupUserList.add(vXGroupUser2);
+
+        vXUserGroupInfo.setXuserInfo(vXUser);
+        vXUserGroupInfo.setXgroupInfo(vXGroupList);
+
+        
Mockito.when(xUserService.createXUserWithOutLogin(vXUser)).thenReturn(vXUser);
+        
Mockito.when(xGroupService.createXGroupWithOutLogin(vXGroup1)).thenReturn(vXGroup1);
+        
Mockito.when(xGroupService.createXGroupWithOutLogin(vXGroup2)).thenReturn(vXGroup2);
+
+        XXPortalUserDao portalUser = Mockito.mock(XXPortalUserDao.class);
+        Mockito.when(daoManager.getXXPortalUser()).thenReturn(portalUser);
+        XXPortalUser user = new XXPortalUser();
+        user.setId(1L);
+        user.setUserSource(RangerCommonEnums.USER_APP);
+        
Mockito.when(portalUser.findByLoginId(vXUser.getName())).thenReturn(user);
+
+        XXPortalUserRoleDao userDao = Mockito.mock(XXPortalUserRoleDao.class);
+        Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(userDao);
+        List<String> lstRole = new ArrayList<String>();
+        lstRole.add(RangerConstants.ROLE_SYS_ADMIN);
+        
Mockito.when(userDao.findXPortalUserRolebyXPortalUserId(Mockito.anyLong())).thenReturn(lstRole);
+
+        VXUserGroupInfo vxUserGroupTest = 
xUserMgr.createXUserGroupFromMap(vXUserGroupInfo);
+        Assert.assertEquals("user1", vxUserGroupTest.getXuserInfo().getName());
+        List<VXGroup> result = vxUserGroupTest.getXgroupInfo();
+        List<VXGroup> expected = new ArrayList<VXGroup>();
+        expected.add(vXGroup1);
+        expected.add(vXGroup2);
+        Assert.assertTrue(result.containsAll(expected));
+        Mockito.verify(daoManager).getXXPortalUser();
+        Mockito.verify(portalUser).findByLoginId(vXUser.getName());
+        Mockito.verify(daoManager).getXXPortalUserRole();
+        Mockito.verify(userDao).findXPortalUserRolebyXPortalUserId(
+        Mockito.anyLong());
+
        }
 
        // Module permission
@@ -1237,14 +1261,23 @@ public class TestXUserMgr {
 
        @Test
        public void test44getGroupsForUser() {
-               VXUser vxUser = vxUser();
-               String userName = "test";
-               
Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(
-                               vxUser);
-               Set<String> list = xUserMgr.getGroupsForUser(userName);
-               Assert.assertNotNull(list);
-               Mockito.verify(xUserService).getXUserByUserName(userName);
-       }
+        VXUser vxUser = vxUser();
+        String userName = "test";
+        
Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(vxUser);
+
+        XXModuleDefDao modDef = Mockito.mock(XXModuleDefDao.class);
+        Mockito.when(daoManager.getXXModuleDef()).thenReturn(modDef);
+        List<String> lstModule = new ArrayList<String>();
+        lstModule.add(RangerConstants.MODULE_USER_GROUPS);
+        Mockito.when(modDef.findAccessibleModulesByUserId(Mockito.anyLong(),
+                        Mockito.anyLong())).thenReturn(lstModule);
+
+        Set<String> list = xUserMgr.getGroupsForUser(userName);
+        Assert.assertNotNull(list);
+        Mockito.verify(xUserService, 
Mockito.atLeast(2)).getXUserByUserName(userName);
+        Mockito.verify(daoManager).getXXModuleDef();
+        
Mockito.verify(modDef).findAccessibleModulesByUserId(Mockito.anyLong(),Mockito.anyLong());
+    }
 
        @Test
        public void test45setUserRolesByExternalID() {

http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/ugsync/src/main/java/org/apache/ranger/ldapusersync/process/LdapPolicyMgrUserGroupBuilder.java
----------------------------------------------------------------------
diff --git 
a/ugsync/src/main/java/org/apache/ranger/ldapusersync/process/LdapPolicyMgrUserGroupBuilder.java
 
b/ugsync/src/main/java/org/apache/ranger/ldapusersync/process/LdapPolicyMgrUserGroupBuilder.java
index 428ad30..c39cc57 100644
--- 
a/ugsync/src/main/java/org/apache/ranger/ldapusersync/process/LdapPolicyMgrUserGroupBuilder.java
+++ 
b/ugsync/src/main/java/org/apache/ranger/ldapusersync/process/LdapPolicyMgrUserGroupBuilder.java
@@ -29,7 +29,11 @@ import java.security.KeyStore;
 import java.security.PrivilegedAction;
 import java.security.SecureRandom;
 import java.util.ArrayList;
+import java.util.LinkedHashMap;
 import java.util.List;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.StringTokenizer;
 import java.util.regex.Pattern;
 
 import javax.net.ssl.HostnameVerifier;
@@ -116,7 +120,9 @@ private static final Logger LOG = 
Logger.getLogger(LdapPolicyMgrUserGroupBuilder
        String principal;
        String keytab;
        String nameRules;
-       
+    Map<String, String> userMap = new LinkedHashMap<String, String>();
+    Map<String, String> groupMap = new LinkedHashMap<String, String>();
+
        static {
                try {
                        LOCAL_HOSTNAME = 
java.net.InetAddress.getLocalHost().getCanonicalHostName();
@@ -147,8 +153,11 @@ private static final Logger LOG = 
Logger.getLogger(LdapPolicyMgrUserGroupBuilder
                }
                keytab = config.getProperty(KEYTAB,"");
                nameRules = config.getProperty(NAME_RULE,"DEFAULT");
-
-       }
+        String userGroupRoles = config.getGroupRoleRules();
+        if (userGroupRoles != null && !userGroupRoles.isEmpty()) {
+            getRoleForUserGroups(userGroupRoles);
+        }
+    }
 
        @Override
        public void addOrUpdateUser(String userName, List<String> groups) 
throws Throwable {
@@ -331,7 +340,11 @@ private static final Logger LOG = 
Logger.getLogger(LdapPolicyMgrUserGroupBuilder
                xuserInfo.setName(aUserName);
                
                xuserInfo.setDescription(aUserName + " - add from Unix box");
-               
+        if (userMap.containsKey(aUserName)) {
+            List<String> roleList = new ArrayList<String>();
+            roleList.add(userMap.get(aUserName));
+            xuserInfo.setUserRoleList(roleList);
+        }
                usergroupInfo.setXuserInfo(xuserInfo);
                
                return xuserInfo;
@@ -413,12 +426,14 @@ private static final Logger LOG = 
Logger.getLogger(LdapPolicyMgrUserGroupBuilder
                        groupUserInfo = getGroupUserInfo(groupName);
                }       
                
-               List<String> oldUsers = new ArrayList<String>();
-               if (groupUserInfo != null && groupUserInfo.getXuserInfo() != 
null) {
-                       for (XUserInfo xUserInfo : 
groupUserInfo.getXuserInfo()) {
-                               oldUsers.add(xUserInfo.getName());
-                       }
-                       LOG.debug("Returned users for group " + 
groupUserInfo.getXgroupInfo().getName() + " are: " + oldUsers);
+        List<String> oldUsers = new ArrayList<String>();
+        Map<String, List<String>> oldUserMap = new HashMap<String, 
List<String>>();
+        if (groupUserInfo != null && groupUserInfo.getXuserInfo() != null) {
+            for (XUserInfo xUserInfo : groupUserInfo.getXuserInfo()) {
+                oldUsers.add(xUserInfo.getName());
+                oldUserMap.put(xUserInfo.getName(), 
xUserInfo.getUserRoleList());
+            }
+        LOG.debug("Returned users for group " + 
groupUserInfo.getXgroupInfo().getName() + " are: " + oldUsers);
                }
                
                List<String> addUsers = new ArrayList<String>();
@@ -432,10 +447,10 @@ private static final Logger LOG = 
Logger.getLogger(LdapPolicyMgrUserGroupBuilder
                if (oldUsers.isEmpty()) {
                        addUsers = users;
                } else {
-                       for (String user : users) {
-                               if (!oldUsers.contains(user)) {
-                                       addUsers.add(user);
-                               }
+            for (String user : users) {
+                if (!oldUsers.contains(user)|| 
!(oldUserMap.get(user).equals(groupMap.get(groupName)))) {
+                    addUsers.add(user);
+                }
                        }
                }
                
@@ -568,10 +583,32 @@ private static final Logger LOG = 
Logger.getLogger(LdapPolicyMgrUserGroupBuilder
                
                WebResource r = c.resource(getURL(PM_ADD_GROUP_USER_INFO_URI));
                
-               Gson gson = new GsonBuilder().create();
-               
-               String jsonString = gson.toJson(groupuserInfo);
-               
+        Gson gson = new GsonBuilder().create();
+        if (groupuserInfo != null
+                && groupuserInfo.getXgroupInfo() != null
+                && groupuserInfo.getXuserInfo() != null
+                && groupMap
+                        .containsKey(groupuserInfo.getXgroupInfo().getName())
+                && groupuserInfo.getXuserInfo().size() > 0) {
+            List<String> userRoleList = new ArrayList<String>();
+            userRoleList.add(groupMap.get(groupuserInfo.getXgroupInfo()
+                    .getName()));
+            int i = groupuserInfo.getXuserInfo().size();
+            for (int j = 0; j < i; j++) {
+                if (userMap.containsKey(groupuserInfo.getXuserInfo().get(j)
+                        .getName())) {
+                    List<String> userRole = new ArrayList<String>();
+                    userRole.add(userMap.get(groupuserInfo.getXuserInfo()
+                            .get(j).getName()));
+                    groupuserInfo.getXuserInfo().get(j)
+                            .setUserRoleList(userRole);
+                } else {
+                    groupuserInfo.getXuserInfo().get(j)
+                            .setUserRoleList(userRoleList);
+                }
+            }
+        }
+        String jsonString = gson.toJson(groupuserInfo);
                LOG.debug("GROUP USER MAPPING" + jsonString);
                
                String response = 
r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class,
 jsonString);
@@ -590,10 +627,17 @@ private static final Logger LOG = 
Logger.getLogger(LdapPolicyMgrUserGroupBuilder
 
                userInfo.setLoginId(aUserName);
                userInfo.setFirstName(aUserName);
-               userInfo.setLastName(aUserName);
-
-               if (authenticationType != null && 
AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && 
SecureClientLogin.isKerberosCredentialExists(principal, keytab)) {
-                       try {
+        userInfo.setLastName(aUserName);
+        String str[] = new String[1];
+        if (userMap.containsKey(aUserName)) {
+            str[0] = userMap.get(aUserName);
+        }
+        userInfo.setUserRoleList(str);
+        if (authenticationType != null
+                && AUTH_KERBEROS.equalsIgnoreCase(authenticationType)
+                && SecureClientLogin.isKerberosCredentialExists(principal,
+                        keytab)) {
+            try {
                                Subject sub = 
SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules);
                                final MUserInfo result = ret;
                                final MUserInfo userInfoFinal = userInfo;
@@ -804,4 +848,72 @@ private static final Logger LOG = 
Logger.getLogger(LdapPolicyMgrUserGroupBuilder
                return ret;
        }
 
+    private void getRoleForUserGroups(String userGroupRolesData) {
+        String roleDelimiter = config.getRoleDelimiter();
+        String userGroupDelimiter = config.getUserGroupDelimiter();
+        String userNameDelimiter = config.getUserGroupNameDelimiter();
+        if (roleDelimiter == null || roleDelimiter.isEmpty()) {
+            roleDelimiter = "&";
+        }
+        if (userGroupDelimiter == null || userGroupDelimiter.isEmpty()) {
+            userGroupDelimiter = ":";
+        }
+        if (userNameDelimiter == null || userNameDelimiter.isEmpty()) {
+            userNameDelimiter = ",";
+        }
+        StringTokenizer str = new StringTokenizer(userGroupRolesData,
+                roleDelimiter);
+        int flag = 0;
+        String userGroupCheck = null;
+        String roleName = null;
+        while (str.hasMoreTokens()) {
+            flag = 0;
+            String tokens = str.nextToken();
+            if (tokens != null && !tokens.isEmpty()) {
+                StringTokenizer userGroupRoles = new StringTokenizer(tokens,
+                        userGroupDelimiter);
+                if (userGroupRoles != null) {
+                    while (userGroupRoles.hasMoreElements()) {
+                        String userGroupRolesTokens = userGroupRoles
+                                .nextToken();
+                        if (userGroupRolesTokens != null
+                                && !userGroupRolesTokens.isEmpty()) {
+                            flag++;
+                            switch (flag) {
+                            case 1:
+                                roleName = userGroupRolesTokens;
+                                break;
+                            case 2:
+                                userGroupCheck = userGroupRolesTokens;
+                                break;
+                            case 3:
+                                StringTokenizer userGroupNames = new 
StringTokenizer(
+                                        userGroupRolesTokens, 
userNameDelimiter);
+                                if (userGroupNames != null) {
+                                    while (userGroupNames.hasMoreElements()) {
+                                        String userGroup = userGroupNames
+                                                .nextToken();
+                                        if (userGroup != null
+                                                && !userGroup.isEmpty()) {
+                                            if 
(userGroupCheck.trim().equalsIgnoreCase("u")) {
+                                                userMap.put(userGroup.trim(), 
roleName.trim());
+                                            } else if 
(userGroupCheck.trim().equalsIgnoreCase("g")) {
+                                                groupMap.put(userGroup.trim(),
+                                                        roleName.trim());
+                                            }
+                                        }
+                                    }
+                                }
+                                break;
+                            default:
+                                userMap.clear();
+                                groupMap.clear();
+                                break;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java
----------------------------------------------------------------------
diff --git 
a/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java
 
b/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java
index 19343b2..33705a3 100644
--- 
a/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java
+++ 
b/ugsync/src/main/java/org/apache/ranger/unixusersync/config/UserGroupSyncConfig.java
@@ -223,6 +223,13 @@ public class UserGroupSyncConfig  {
        private static final String SYNC_MAPPING_GROUPNAME_HANDLER = 
"ranger.usersync.mapping.groupname.handler";
        private static final String DEFAULT_SYNC_MAPPING_GROUPNAME_HANDLER = 
"org.apache.ranger.usergroupsync.RegEx";
 
+    private static final String ROLE_ASSIGNMENT_LIST_DELIMITER = 
"ranger.usersync.role.assignment.list.delimiter";
+
+    private static final String USERS_GROUPS_ASSIGNMENT_LIST_DELIMITER = 
"ranger.usersync.users.groups.assignment.list.delimiter";
+
+    private static final String USERNAME_GROUPNAME_ASSIGNMENT_LIST_DELIMITER = 
"ranger.usersync.username.groupname.assignment.list.delimiter";
+
+    private static final String GROUP_BASED_ROLE_ASSIGNMENT_RULES = 
"ranger.usersync.group.based.role.assignment.rules";
        private Properties prop = new Properties();
 
        private static volatile UserGroupSyncConfig me = null;
@@ -868,6 +875,52 @@ public class UserGroupSyncConfig  {
                return val;
        }
 
+    public String getGroupRoleRules() {
+        if (prop != null && 
prop.containsKey(GROUP_BASED_ROLE_ASSIGNMENT_RULES)) {
+            String GroupRoleRules = prop
+                    .getProperty(GROUP_BASED_ROLE_ASSIGNMENT_RULES);
+            if (GroupRoleRules != null && !GroupRoleRules.isEmpty()) {
+                return GroupRoleRules.trim();
+            }
+        }
+        return null;
+    }
+
+    public String getUserGroupDelimiter() {
+        if (prop != null
+                && prop.containsKey(USERS_GROUPS_ASSIGNMENT_LIST_DELIMITER)) {
+            String UserGroupDelimiter = prop
+                    .getProperty(USERS_GROUPS_ASSIGNMENT_LIST_DELIMITER);
+            if (UserGroupDelimiter != null && !UserGroupDelimiter.isEmpty()) {
+                return UserGroupDelimiter;
+            }
+        }
+        return null;
+    }
+
+    public String getUserGroupNameDelimiter() {
+        if (prop != null
+                && 
prop.containsKey(USERNAME_GROUPNAME_ASSIGNMENT_LIST_DELIMITER)) {
+            String UserGroupNameDelimiter = prop
+                    .getProperty(USERNAME_GROUPNAME_ASSIGNMENT_LIST_DELIMITER);
+            if (UserGroupNameDelimiter != null
+                    && !UserGroupNameDelimiter.isEmpty()) {
+                return UserGroupNameDelimiter;
+            }
+        }
+        return null;
+    }
+
+    public String getRoleDelimiter() {
+        if (prop != null && prop.containsKey(ROLE_ASSIGNMENT_LIST_DELIMITER)) {
+            String roleDelimiter = prop
+                    .getProperty(ROLE_ASSIGNMENT_LIST_DELIMITER);
+            if (roleDelimiter != null && !roleDelimiter.isEmpty()) {
+                return roleDelimiter;
+            }
+        }
+        return null;
+    }
        public boolean isStartTlsEnabled() {
                boolean starttlsEnabled;
                String val = prop.getProperty(LGSYNC_LDAP_STARTTLS_ENABLED);

http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/ugsync/src/main/java/org/apache/ranger/unixusersync/model/XUserInfo.java
----------------------------------------------------------------------
diff --git 
a/ugsync/src/main/java/org/apache/ranger/unixusersync/model/XUserInfo.java 
b/ugsync/src/main/java/org/apache/ranger/unixusersync/model/XUserInfo.java
index 7d636fd..4f6ac46 100644
--- a/ugsync/src/main/java/org/apache/ranger/unixusersync/model/XUserInfo.java
+++ b/ugsync/src/main/java/org/apache/ranger/unixusersync/model/XUserInfo.java
@@ -26,8 +26,8 @@ public class XUserInfo {
        private String id;
        private String name;
        private String  description;
-       
-       private List<String>    groupNameList = new ArrayList<String>();
+    private List<String> groupNameList = new ArrayList<String>();
+    private List<String> userRoleList = new ArrayList<String>();
        
        public String getId() {
                return id;
@@ -59,5 +59,19 @@ public class XUserInfo {
        public List<String> getGroups() {
                return groupNameList;
        }
-       
+
+    public List<String> getUserRoleList() {
+        return userRoleList;
+    }
+
+    public void setUserRoleList(List<String> userRoleList) {
+        this.userRoleList = userRoleList;
+    }
+
+    @Override
+    public String toString() {
+        return "XUserInfo [id=" + id + ", name=" + name + ", description="
+                + description + ", groupNameList=" + groupNameList
+                + ", userRoleList=" + userRoleList + "]";
+    }
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/ugsync/src/main/java/org/apache/ranger/unixusersync/process/PolicyMgrUserGroupBuilder.java
----------------------------------------------------------------------
diff --git 
a/ugsync/src/main/java/org/apache/ranger/unixusersync/process/PolicyMgrUserGroupBuilder.java
 
b/ugsync/src/main/java/org/apache/ranger/unixusersync/process/PolicyMgrUserGroupBuilder.java
index 9ce4abf..ade2ee7 100644
--- 
a/ugsync/src/main/java/org/apache/ranger/unixusersync/process/PolicyMgrUserGroupBuilder.java
+++ 
b/ugsync/src/main/java/org/apache/ranger/unixusersync/process/PolicyMgrUserGroupBuilder.java
@@ -31,6 +31,9 @@ import java.security.SecureRandom;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.StringTokenizer;
 import java.util.regex.Pattern;
 
 import javax.net.ssl.HostnameVerifier;
@@ -121,7 +124,8 @@ public class PolicyMgrUserGroupBuilder implements 
UserGroupSink {
        String principal;
        String keytab;
        String nameRules;
-       
+    Map<String, String> userMap = new LinkedHashMap<String, String>();
+    Map<String, String> groupMap = new LinkedHashMap<String, String>();
        static {
                try {
                        LOCAL_HOSTNAME = 
java.net.InetAddress.getLocalHost().getCanonicalHostName();
@@ -160,6 +164,10 @@ public class PolicyMgrUserGroupBuilder implements 
UserGroupSink {
                }
                keytab = config.getProperty(KEYTAB,"");
                nameRules = config.getProperty(NAME_RULE,"DEFAULT");
+        String userGroupRoles = config.getGroupRoleRules();
+        if (userGroupRoles != null && !userGroupRoles.isEmpty()) {
+            getRoleForUserGroups(userGroupRoles);
+        }
                buildUserGroupInfo();
        }
        
@@ -364,26 +372,50 @@ public class PolicyMgrUserGroupBuilder implements 
UserGroupSink {
                        for(String g : addGroups) {
                                LOG.debug("INFO: addPMXAGroupToUser(" + 
userName + "," + g + ")" );
                        }
-                       if (! isMockRun) {
-                               if (!addGroups.isEmpty()){
-                                       
ugInfo.setXuserInfo(addXUserInfo(userName));
-                                   
ugInfo.setXgroupInfo(getXGroupInfoList(addGroups));
-                                       try{
-                                               // If the rest call to ranger 
admin fails, 
-                                               // propagate the failure to the 
caller for retry in next sync cycle.
-                                               if (addUserGroupInfo(ugInfo) == 
null) {
-                                                       String msg = "Failed to 
add user group info";
-                                                       LOG.error(msg);
-                                                       throw new 
Exception(msg);
-                                               }
-                                       }catch(Throwable t){
-                                               
LOG.error("PolicyMgrUserGroupBuilder.addUserGroupInfo failed with exception: " 
+ t.getMessage()
-                                               + ", for user-group entry: " + 
ugInfo);
-                                       }
-                               }
-                               addXUserGroupInfo(user, addGroups);
-                       }
-                       
+            if (!isMockRun) {
+                if (!addGroups.isEmpty()) {
+                    XUserInfo obj = addXUserInfo(userName);
+                    if (obj != null) {
+                        for (int i = 0; i < addGroups.size(); i++) {
+                            if (groupMap.containsKey(addGroups.get(i))) {
+                                List<String> userRoleList = new 
ArrayList<String>();
+                                userRoleList
+                                        .add(groupMap.get(addGroups.get(i)));
+                                if (userMap.containsKey(obj.getName())) {
+                                    List<String> userRole = new 
ArrayList<String>();
+                                    userRole.add(userMap.get(obj.getName()));
+                                    if 
(!obj.getUserRoleList().equals(userRole)) {
+                                        obj.setUserRoleList(userRole);
+
+                                    }
+                                } else if (!obj.getUserRoleList().equals(
+                                        userRoleList)) {
+                                    obj.setUserRoleList(userRoleList);
+                                }
+                            }
+                        }
+                    }
+                    ugInfo.setXuserInfo(obj);
+                    ugInfo.setXgroupInfo(getXGroupInfoList(addGroups));
+                    try {
+                        // If the rest call to ranger admin fails,
+                        // propagate the failure to the caller for retry in 
next
+                        // sync cycle.
+                        if (addUserGroupInfo(ugInfo) == null) {
+                            String msg = "Failed to add user group info";
+                            LOG.error(msg);
+                            throw new Exception(msg);
+                        }
+                    } catch (Throwable t) {
+                        LOG.error("PolicyMgrUserGroupBuilder.addUserGroupInfo 
failed with exception: "
+                                + t.getMessage()
+                                + ", for user-group entry: "
+                                + ugInfo);
+                    }
+                }
+                addXUserGroupInfo(user, addGroups);
+            }
+
                        for(String g : delGroups) {
                                LOG.debug("INFO: delPMXAGroupFromUser(" + 
userName + "," + g + ")" );
                        }
@@ -392,23 +424,92 @@ public class PolicyMgrUserGroupBuilder implements 
UserGroupSink {
                                delXUserGroupInfo(user, delGroups);
                        }
                        if (! isMockRun) {
-                               if (!updateGroups.isEmpty()){
-                                       
ugInfo.setXuserInfo(addXUserInfo(userName));
-                                       
ugInfo.setXgroupInfo(getXGroupInfoList(updateGroups));
-                                       try{
-                                               // If the rest call to ranger 
admin fails, 
-                                               // propagate the failure to the 
caller for retry in next sync cycle.
-                                               if (addUserGroupInfo(ugInfo) == 
null) {
-                                                       String msg = "Failed to 
add user group info";
-                                                       LOG.error(msg);
-                                                       throw new 
Exception(msg);
-                                               }
-                                       }catch(Throwable t){
-                                               
LOG.error("PolicyMgrUserGroupBuilder.addUserGroupInfo failed with exception: " 
+ t.getMessage()
-                                               + ", for user-group entry: " + 
ugInfo);
-                                       }
-                               }
-                       }
+                if (!updateGroups.isEmpty()) {
+                    XUserInfo obj = addXUserInfo(userName);
+                    if (obj != null) {
+                        for (int i = 0; i < updateGroups.size(); i++) {
+                            if (groupMap.containsKey(updateGroups.get(i))) {
+                                List<String> userRoleList = new 
ArrayList<String>();
+                                userRoleList.add(groupMap.get(updateGroups
+                                        .get(i)));
+                                if (userMap.containsKey(obj.getName())) {
+                                    List<String> userRole = new 
ArrayList<String>();
+                                    userRole.add(userMap.get(obj.getName()));
+                                    if 
(!obj.getUserRoleList().equals(userRole)) {
+                                        obj.setUserRoleList(userRole);
+                                    }
+                                } else if (!obj.getUserRoleList().equals(
+                                        userRoleList)) {
+                                    obj.setUserRoleList(userRoleList);
+                                }
+                            }
+                        }
+                    }
+                    ugInfo.setXuserInfo(obj);
+                    ugInfo.setXgroupInfo(getXGroupInfoList(updateGroups));
+                    try {
+                        // If the rest call to ranger admin fails,
+                        // propagate the failure to the caller for retry in 
next
+                        // sync cycle.
+                        if (addUserGroupInfo(ugInfo) == null) {
+                            String msg = "Failed to add user group info";
+                            LOG.error(msg);
+                            throw new Exception(msg);
+                        }
+                    } catch (Throwable t) {
+                        LOG.error("PolicyMgrUserGroupBuilder.addUserGroupInfo 
failed with exception: "
+                                + t.getMessage()
+                                + ", for user-group entry: "
+                                + ugInfo);
+                    }
+                }
+            }
+            if (!isMockRun) {
+                XUserInfo obj = addXUserInfo(userName);
+                boolean roleFlag = false;
+                if (obj != null && updateGroups.isEmpty()
+                        && addGroups.isEmpty()) {
+                    if (userMap.containsKey(obj.getName())) {
+                        List<String> userRole = new ArrayList<String>();
+                        userRole.add(userMap.get(obj.getName()));
+                        if (!obj.getUserRoleList().equals(userRole)) {
+                            obj.setUserRoleList(userRole);
+                            roleFlag = true;
+                        }
+                    } else {
+                        for (int i = 0; i < groups.size(); i++) {
+                            if (groupMap.containsKey(groups.get(i))) {
+                                List<String> userRoleList = new 
ArrayList<String>();
+                                userRoleList.add(groupMap.get(groups.get(i)));
+                                if 
(!obj.getUserRoleList().equals(userRoleList)) {
+                                    obj.setUserRoleList(userRoleList);
+                                    roleFlag = true;
+                                }
+                            }
+                        }
+
+                    }
+                    ugInfo.setXuserInfo(obj);
+                    ugInfo.setXgroupInfo(getXGroupInfoList(groups));
+                }
+                if (roleFlag) {
+                    try {
+                        // If the rest call to ranger admin fails,
+                        // propagate the failure to the caller for retry in 
next
+                        // sync cycle.
+                        if (addUserGroupInfo(ugInfo) == null) {
+                            String msg = "Failed to add user group info";
+                            LOG.error(msg);
+                            throw new Exception(msg);
+                        }
+                    } catch (Throwable t) {
+                        LOG.error("PolicyMgrUserGroupBuilder.addUserGroupInfo 
failed with exception: "
+                                + t.getMessage()
+                                + ", for user-group entry: "
+                                + ugInfo);
+                    }
+                }
+            }
                }
        }
        
@@ -529,8 +630,24 @@ public class PolicyMgrUserGroupBuilder implements 
UserGroupSink {
                LOG.debug("INFO: addPMXAUser(" + userName + ")" );
                if (! isMockRun) {
                        user = addXUserInfo(userName);
-               }
-               
+            if (!groups.isEmpty() && user != null) {
+                for (int i = 0; i < groups.size(); i++) {
+                    if (groupMap.containsKey(groups.get(i))) {
+                        List<String> userRoleList = new ArrayList<String>();
+                        userRoleList.add(groupMap.get(groups.get(i)));
+                        if (userMap.containsKey(user.getName())) {
+                            List<String> userRole = new ArrayList<String>();
+                            userRole.add(userMap.get(user.getName()));
+                            user.setUserRoleList(userRole);
+                        } else {
+                            user.setUserRoleList(userRoleList);
+                        }
+                    }
+                }
+            }
+            usergroupInfo.setXuserInfo(user);
+        }
+
                for(String g : groups) {
                                LOG.debug("INFO: addPMXAGroupToUser(" + 
userName + "," + g + ")" );
                }
@@ -621,10 +738,10 @@ public class PolicyMgrUserGroupBuilder implements 
UserGroupSink {
                        XUserInfo xUserInfo = ret.getXuserInfo();
                        addUserToList(xUserInfo);
 
-                       for(XGroupInfo xGroupInfo : ret.getXgroupInfo()) {
-                               addGroupToList(xGroupInfo);
-                               addUserGroupInfoToList(xUserInfo,xGroupInfo);
-                       }
+            for (XGroupInfo xGroupInfo : ret.getXgroupInfo()) {
+                addGroupToList(xGroupInfo);
+                addUserGroupInfoToList(xUserInfo, xGroupInfo);
+            }
                }
        }
        
@@ -809,7 +926,11 @@ public class PolicyMgrUserGroupBuilder implements 
UserGroupSink {
                userInfo.setLoginId(aUserName);
                userInfo.setFirstName(aUserName);
                userInfo.setLastName(aUserName);
-
+        String str[] = new String[1];
+        if (userMap.containsKey(aUserName)) {
+            str[0] = userMap.get(aUserName);
+        }
+        userInfo.setUserRoleList(str);
                if (authenticationType != null && 
AUTH_KERBEROS.equalsIgnoreCase(authenticationType) && 
SecureClientLogin.isKerberosCredentialExists(principal, keytab)) {
                        try {
                                Subject sub = 
SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules);
@@ -1081,5 +1202,73 @@ public class PolicyMgrUserGroupBuilder implements 
UserGroupSink {
                
        }
 
-       
+    private void getRoleForUserGroups(String userGroupRolesData) {
+
+        String roleDelimiter = config.getRoleDelimiter();
+        String userGroupDelimiter = config.getUserGroupDelimiter();
+        String userNameDelimiter = config.getUserGroupNameDelimiter();
+        if (roleDelimiter == null || roleDelimiter.isEmpty()) {
+            roleDelimiter = "&";
+        }
+        if (userGroupDelimiter == null || userGroupDelimiter.isEmpty()) {
+            userGroupDelimiter = ":";
+        }
+        if (userNameDelimiter == null || userNameDelimiter.isEmpty()) {
+            userNameDelimiter = ",";
+        }
+        StringTokenizer str = new StringTokenizer(userGroupRolesData,
+                roleDelimiter);
+        int flag = 0;
+        String userGroupCheck = null;
+        String roleName = null;
+        while (str.hasMoreTokens()) {
+            flag = 0;
+            String tokens = str.nextToken();
+            if (tokens != null && !tokens.isEmpty()) {
+                StringTokenizer userGroupRoles = new StringTokenizer(tokens,
+                        userGroupDelimiter);
+                if (userGroupRoles != null) {
+                    while (userGroupRoles.hasMoreElements()) {
+                        String userGroupRolesTokens = userGroupRoles
+                                .nextToken();
+                        if (userGroupRolesTokens != null
+                                && !userGroupRolesTokens.isEmpty()) {
+                            flag++;
+                            switch (flag) {
+                            case 1:
+                                roleName = userGroupRolesTokens;
+                                break;
+                            case 2:
+                                userGroupCheck = userGroupRolesTokens;
+                                break;
+                            case 3:
+                                StringTokenizer userGroupNames = new 
StringTokenizer(
+                                        userGroupRolesTokens, 
userNameDelimiter);
+                                if (userGroupNames != null) {
+                                    while (userGroupNames.hasMoreElements()) {
+                                        String userGroup = userGroupNames
+                                                .nextToken();
+                                        if (userGroup != null
+                                                && !userGroup.isEmpty()) {
+                                            if 
(userGroupCheck.trim().equalsIgnoreCase("u")) {
+                                                userMap.put(userGroup.trim(), 
roleName.trim());
+                                            } else if 
(userGroupCheck.trim().equalsIgnoreCase("g")) {
+                                                groupMap.put(userGroup.trim(),
+                                                        roleName.trim());
+                                            }
+                                        }
+                                    }
+                                }
+                                break;
+                            default:
+                                userMap.clear();
+                                groupMap.clear();
+                                break;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/unixauthservice/scripts/install.properties
----------------------------------------------------------------------
diff --git a/unixauthservice/scripts/install.properties 
b/unixauthservice/scripts/install.properties
index 00ddef5..88bce69 100644
--- a/unixauthservice/scripts/install.properties
+++ b/unixauthservice/scripts/install.properties
@@ -69,6 +69,22 @@ AUTH_SSL_TRUSTSTORE_PASSWORD=
 # The following properties are relevant only if SYNC_SOURCE = ldap
 # ---------------------------------------------------------------
 
+# The below properties ROLE_ASSIGNMENT_LIST_DELIMITER, 
USERS_GROUPS_ASSIGNMENT_LIST_DELIMITER, 
USERNAME_GROUPNAME_ASSIGNMENT_LIST_DELIMITER,
+#and GROUP_BASED_ROLE_ASSIGNMENT_RULES can be used to assign role to LDAP 
synced users and groups
+#NOTE all the delimiters should have different values and the delimiters 
should not contain characters that are allowed in userName or GroupName
+
+# default value ROLE_ASSIGNMENT_LIST_DELIMITER = &
+ROLE_ASSIGNMENT_LIST_DELIMITER = &
+
+#default value USERS_GROUPS_ASSIGNMENT_LIST_DELIMITER = :
+USERS_GROUPS_ASSIGNMENT_LIST_DELIMITER = :
+
+#default value USERNAME_GROUPNAME_ASSIGNMENT_LIST_DELIMITER = ,
+USERNAME_GROUPNAME_ASSIGNMENT_LIST_DELIMITER = ,
+
+# with above mentioned delimiters a sample value would be 
ROLE_SYS_ADMIN:u:userName1,userName2&ROLE_SYS_ADMIN:g:groupName1,groupName2&ROLE_KEY_ADMIN:u:userName&ROLE_KEY_ADMIN:g:groupName&ROLE_USER:u:userName3,userName4&ROLE_USER:g:groupName3
+GROUP_BASED_ROLE_ASSIGNMENT_RULES =
+
 # URL of source ldap 
 # a sample value would be:  ldap://ldap.example.com:389
 # Must specify a value if SYNC_SOURCE is ldap

http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/unixauthservice/scripts/setup.py
----------------------------------------------------------------------
diff --git a/unixauthservice/scripts/setup.py b/unixauthservice/scripts/setup.py
index bbc9226..5f659d7 100755
--- a/unixauthservice/scripts/setup.py
+++ b/unixauthservice/scripts/setup.py
@@ -366,6 +366,24 @@ def main():
     pid_dir_path = globalDict['USERSYNC_PID_DIR_PATH']
     unix_user = globalDict['unix_user']
 
+    if globalDict['SYNC_SOURCE'].lower() == SYNC_SOURCE_LDAP and 
globalDict.has_key('ROLE_ASSIGNMENT_LIST_DELIMITER') \
+     and globalDict.has_key('USERS_GROUPS_ASSIGNMENT_LIST_DELIMITER') and 
globalDict.has_key('USERNAME_GROUPNAME_ASSIGNMENT_LIST_DELIMITER'):
+        roleAssignmentDelimiter = globalDict['ROLE_ASSIGNMENT_LIST_DELIMITER']
+        userGroupAssignmentDelimiter= 
globalDict['USERS_GROUPS_ASSIGNMENT_LIST_DELIMITER']
+        userNameGroupNameAssignmentListDelimiter= 
globalDict['USERNAME_GROUPNAME_ASSIGNMENT_LIST_DELIMITER'];
+        if roleAssignmentDelimiter != "" :
+            if roleAssignmentDelimiter == userGroupAssignmentDelimiter or 
roleAssignmentDelimiter == userNameGroupNameAssignmentListDelimiter :
+                print "ERROR: All Delimiters ROLE_ASSIGNMENT_LIST_DELIMITER, 
USERS_GROUPS_ASSIGNMENT_LIST_DELIMITER and 
USERNAME_GROUPNAME_ASSIGNMENT_LIST_DELIMITER  should be different"
+                sys.exit(1)
+        if userGroupAssignmentDelimiter != "" :
+            if roleAssignmentDelimiter == userGroupAssignmentDelimiter or 
userGroupAssignmentDelimiter == userNameGroupNameAssignmentListDelimiter:
+                print "ERROR: All Delimiters ROLE_ASSIGNMENT_LIST_DELIMITER, 
USERS_GROUPS_ASSIGNMENT_LIST_DELIMITER and 
USERNAME_GROUPNAME_ASSIGNMENT_LIST_DELIMITER  should be different"
+                sys.exit(1)
+        if userNameGroupNameAssignmentListDelimiter != "":
+            if roleAssignmentDelimiter == 
userNameGroupNameAssignmentListDelimiter or userGroupAssignmentDelimiter == 
userNameGroupNameAssignmentListDelimiter:
+                print "ERROR: All Delimiters ROLE_ASSIGNMENT_LIST_DELIMITER, 
USERS_GROUPS_ASSIGNMENT_LIST_DELIMITER and 
USERNAME_GROUPNAME_ASSIGNMENT_LIST_DELIMITER  should be different"
+                sys.exit(1)
+
     if pid_dir_path == "":
         pid_dir_path = "/var/run/ranger"
 

http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/unixauthservice/scripts/templates/installprop2xml.properties
----------------------------------------------------------------------
diff --git a/unixauthservice/scripts/templates/installprop2xml.properties 
b/unixauthservice/scripts/templates/installprop2xml.properties
index fc69f36..fa342fb 100644
--- a/unixauthservice/scripts/templates/installprop2xml.properties
+++ b/unixauthservice/scripts/templates/installprop2xml.properties
@@ -17,6 +17,10 @@ POLICY_MGR_URL =  ranger.usersync.policymanager.baseURL
 MIN_UNIX_USER_ID_TO_SYNC = ranger.usersync.unix.minUserId
 MIN_UNIX_GROUP_ID_TO_SYNC = ranger.usersync.unix.minGroupId
 SYNC_INTERVAL = ranger.usersync.sleeptimeinmillisbetweensynccycle
+ROLE_ASSIGNMENT_LIST_DELIMITER = ranger.usersync.role.assignment.list.delimiter
+USERS_GROUPS_ASSIGNMENT_LIST_DELIMITER = 
ranger.usersync.users.groups.assignment.list.delimiter
+USERNAME_GROUPNAME_ASSIGNMENT_LIST_DELIMITER = 
ranger.usersync.username.groupname.assignment.list.delimiter
+GROUP_BASED_ROLE_ASSIGNMENT_RULES =  
ranger.usersync.group.based.role.assignment.rules
 SYNC_LDAP_URL = ranger.usersync.ldap.url
 SYNC_LDAP_BIND_DN = ranger.usersync.ldap.binddn
 SYNC_LDAP_BIND_PASSWORD = ranger.usersync.ldap.ldapbindpassword

http://git-wip-us.apache.org/repos/asf/ranger/blob/9f5721bb/unixauthservice/scripts/templates/ranger-ugsync-template.xml
----------------------------------------------------------------------
diff --git a/unixauthservice/scripts/templates/ranger-ugsync-template.xml 
b/unixauthservice/scripts/templates/ranger-ugsync-template.xml
index 5321dc6..0c2d1fc 100644
--- a/unixauthservice/scripts/templates/ranger-ugsync-template.xml
+++ b/unixauthservice/scripts/templates/ranger-ugsync-template.xml
@@ -209,4 +209,20 @@
       <name>ranger.usersync.truststore.password</name>
       <value></value>
     </property>
+    <property>
+      <name>ranger.usersync.role.assignment.list.delimiter</name>
+          <value></value>
+        </property>
+        <property>
+      <name>ranger.usersync.users.groups.assignment.list.delimiter</name>
+      <value></value>
+        </property>
+        <property>
+      <name>ranger.usersync.username.groupname.assignment.list.delimiter</name>
+      <value></value>
+        </property>
+    <property>
+          <name>ranger.usersync.group.based.role.assignment.rules</name>
+      <value></value>
+    </property>
 </configuration>

Reply via email to