You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ranger.apache.org by ga...@apache.org on 2017/01/05 08:45:58 UTC

incubator-ranger git commit: RANGER-696 : Option to use custom "admin" username

Repository: incubator-ranger
Updated Branches:
  refs/heads/master 85093b8b4 -> 05e179d44


RANGER-696 : Option to use custom "admin" username

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


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

Branch: refs/heads/master
Commit: 05e179d442192b6e64d174a6786de0a90716ba8a
Parents: 85093b8
Author: pradeep agrawal <pr...@freestoneinfotech.com>
Authored: Thu Dec 22 18:29:03 2016 +0530
Committer: Gautam Borad <ga...@apache.org>
Committed: Thu Jan 5 14:14:13 2017 +0530

----------------------------------------------------------------------
 security-admin/scripts/changeusernameutil.py    | 128 ++++++++++++++++++
 .../java/org/apache/ranger/biz/UserMgr.java     |  39 ++++++
 .../patch/cliutil/ChangeUserNameUtil.java       | 133 +++++++++++++++++++
 src/main/assembly/admin-web.xml                 |   1 +
 4 files changed, 301 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/05e179d4/security-admin/scripts/changeusernameutil.py
----------------------------------------------------------------------
diff --git a/security-admin/scripts/changeusernameutil.py b/security-admin/scripts/changeusernameutil.py
new file mode 100644
index 0000000..7216bbc
--- /dev/null
+++ b/security-admin/scripts/changeusernameutil.py
@@ -0,0 +1,128 @@
+#
+# 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. See accompanying LICENSE file.
+#
+
+import os
+import re
+import sys
+import errno
+import shlex
+import logging
+import subprocess
+import platform
+import fileinput
+import getpass
+import shutil
+from xml.etree import ElementTree as ET
+from os.path import basename
+from subprocess import Popen,PIPE
+from datetime import date
+from datetime import datetime
+
+os_name = platform.system()
+os_name = os_name.upper()
+
+if os_name == "LINUX":
+        RANGER_ADMIN_HOME = os.getenv("RANGER_ADMIN_HOME")
+        if RANGER_ADMIN_HOME is None:
+                RANGER_ADMIN_HOME = os.getcwd()
+elif os_name == "WINDOWS":
+        RANGER_ADMIN_HOME = os.getenv("RANGER_ADMIN_HOME")
+
+def log(msg,type):
+        if type == 'info':
+                logging.info(" %s",msg)
+        if type == 'debug':
+                logging.debug(" %s",msg)
+        if type == 'warning':
+                logging.warning(" %s",msg)
+        if type == 'exception':
+                logging.exception(" %s",msg)
+        if type == 'error':
+                logging.error(" %s",msg)
+
+def username_validation(username):
+        if username:
+                if re.search("[\\\`'\"]",username):
+                        log("[E] username contains one of the unsupported special characters like \" ' \ `","error")
+                        sys.exit(1)
+
+
+def main(argv):
+        FORMAT = '%(asctime)-15s %(message)s'
+        logging.basicConfig(format=FORMAT, level=logging.DEBUG)
+        ews_lib = os.path.join(RANGER_ADMIN_HOME,"ews","lib")
+        app_home = os.path.join(RANGER_ADMIN_HOME,"ews","webapp")
+        ranger_log = os.path.join(RANGER_ADMIN_HOME,"ews","logs")
+
+        if os.environ['JAVA_HOME'] == "":
+                log("[E] ---------- JAVA_HOME environment property not defined, aborting installation. ----------", "error")
+                sys.exit(1)
+        JAVA_BIN=os.path.join(os.environ['JAVA_HOME'],'bin','java')
+        if os_name == "WINDOWS" :
+                JAVA_BIN = JAVA_BIN+'.exe'
+        if os.path.isfile(JAVA_BIN):
+                pass
+        else:
+                while os.path.isfile(JAVA_BIN) == False:
+                        log("Enter java executable path: :","info")
+                        JAVA_BIN=raw_input()
+        log("[I] Using Java:" + str(JAVA_BIN),"info")
+
+        USERNAME = ''
+        OLD_PASSWORD = ''
+        NEW_USERNAME=''
+
+        if len(argv)==4:
+                userName=argv[1]
+                oldPassword=argv[2]
+                newUserName=argv[3]
+        else:
+                log("[E] Invalid argument list.", "error")
+                log("[I] Usage : python changeusernameutil.py <loginID> <currentPassword> <newUserName>","info")
+                sys.exit(1)
+
+        while userName == "":
+                print "Enter user name:"
+                userName=raw_input()
+
+        while oldPassword == "":
+                oldPassword=getpass.getpass("Enter current password:")
+
+        while newUserName == "":
+                newUserName=getpass.getpass("Enter new user name:")
+
+        if userName==newUserName:
+                log("[E] Old User Name and New User Name argument are same. Exiting!!", "error")
+                sys.exit(1)
+
+        if userName != "" and oldPassword != "" and newUserName != "":
+                username_validation(newUserName)
+                if os_name == "LINUX":
+                        path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s/*")%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home,ews_lib)
+                elif os_name == "WINDOWS":
+                        path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home)
+                get_java_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.cliutil.%s %s %s %s"%(JAVA_BIN,ranger_log,path,'ChangeUserNameUtil',userName,oldPassword,newUserName)
+                if os_name == "LINUX":
+                        ret = subprocess.call(shlex.split(get_java_cmd))
+                elif os_name == "WINDOWS":
+                        ret = subprocess.call(get_java_cmd)
+                if ret == 0:
+                        log("[I] User name updated successfully","info")
+                else:
+                        log("[E] Unable to update user name of user:"+userName,"error")
+                        sys.exit(1)
+        else:
+                log("[E] Input Error","error")
+
+main(sys.argv)

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/05e179d4/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 925c0e5..8f9db09 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
@@ -47,6 +47,7 @@ import org.apache.ranger.entity.XXGroupPermission;
 import org.apache.ranger.entity.XXPortalUser;
 import org.apache.ranger.entity.XXPortalUserRole;
 import org.apache.ranger.entity.XXTrxLog;
+import org.apache.ranger.entity.XXUser;
 import org.apache.ranger.entity.XXUserPermission;
 import org.apache.ranger.service.XGroupPermissionService;
 import org.apache.ranger.service.XPortalUserService;
@@ -1239,6 +1240,8 @@ public class UserMgr {
                                 xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_PASSWORD_CHANGE);
                                 xTrxLog.setObjectId(xXPortalUser.getId());
                                 xTrxLog.setObjectName(xXPortalUser.getLoginId());
+                                xTrxLog.setAddedByUserId(xXPortalUser.getId());
+                                xTrxLog.setUpdatedByUserId(xXPortalUser.getId());
                                 trxLogList.add(xTrxLog);
                                 msBizUtil.createTrxLog(trxLogList);
                         }
@@ -1281,4 +1284,40 @@ public class UserMgr {
 		}
 		return roleList;
 	}
+
+        @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
+        public XXPortalUser updateOldUserName(String userLoginId,String newUserName, String currentPassword) {
+                if (userLoginId == null || newUserName == null
+                                || userLoginId.trim().isEmpty() || newUserName.trim().isEmpty()){
+                        return null;
+                }
+
+                XXPortalUser xXPortalUser = this.findByLoginId(userLoginId);
+        XXUser xXUser = daoManager.getXXUser().findByUserName(userLoginId);
+                if (xXPortalUser == null || xXUser == null) {
+                        return null;
+                }
+                xXUser.setName(newUserName);
+                daoManager.getXXUser().update(xXUser);
+
+                xXPortalUser.setLoginId(newUserName);
+                // The old password needs to be encrypted by the new user name
+                String updatedPwd = encrypt(newUserName,currentPassword);
+                xXPortalUser.setPassword(updatedPwd);
+                xXPortalUser = daoManager.getXXPortalUser().update(xXPortalUser);
+                List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
+                XXTrxLog xTrxLog = new XXTrxLog();
+                xTrxLog.setAttributeName("User Name");
+                xTrxLog.setPreviousValue(userLoginId);
+                xTrxLog.setNewValue(newUserName);
+                xTrxLog.setAction("update");
+                xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_USER_PROFILE);
+                xTrxLog.setObjectId(xXPortalUser.getId());
+                xTrxLog.setObjectName(xXPortalUser.getLoginId());
+                xTrxLog.setAddedByUserId(xXPortalUser.getId());
+                xTrxLog.setUpdatedByUserId(xXPortalUser.getId());
+                trxLogList.add(xTrxLog);
+                msBizUtil.createTrxLog(trxLogList);
+                return xXPortalUser;
+        }
 }

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/05e179d4/security-admin/src/main/java/org/apache/ranger/patch/cliutil/ChangeUserNameUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/ChangeUserNameUtil.java b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/ChangeUserNameUtil.java
new file mode 100644
index 0000000..531ee34
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/ChangeUserNameUtil.java
@@ -0,0 +1,133 @@
+/*<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one or more
+  contributor license agreements.  See the NOTICE file distributed with
+  this work for additional information regarding copyright ownership.
+  The ASF licenses this file to You 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.
+-->*/
+
+package org.apache.ranger.patch.cliutil;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.biz.UserMgr;
+import org.apache.ranger.db.RangerDaoManager;
+import org.apache.ranger.entity.XXPortalUser;
+import org.apache.ranger.patch.BaseLoader;
+import org.apache.ranger.util.CLIUtil;
+import org.apache.solr.common.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class ChangeUserNameUtil extends BaseLoader {
+    private static Logger logger = Logger.getLogger(ChangeUserNameUtil.class);
+
+    @Autowired
+    RangerDaoManager daoMgr;
+
+    @Autowired
+    UserMgr userMgr;
+
+    public static String userLoginId;
+    public static String currentPassword;
+    public static String newUserName;
+
+    public static void main(String[] args) {
+        logger.info("main()");
+        try {
+            ChangeUserNameUtil loader = (ChangeUserNameUtil) CLIUtil.getBean(ChangeUserNameUtil.class);
+            loader.init();
+            if (args.length == 3) {
+                userLoginId = args[0];
+                currentPassword = args[1];
+                newUserName = args[2];
+                if(StringUtils.isEmpty(userLoginId)){
+                    System.out.println("Invalid login ID. Exiting!!!");
+                    logger.info("Invalid login ID. Exiting!!!");
+                    System.exit(1);
+                }
+                if(StringUtils.isEmpty(currentPassword)){
+                    System.out.println("Invalid current password. Exiting!!!");
+                    logger.info("Invalid current password. Exiting!!!");
+                    System.exit(1);
+                }
+                if(StringUtils.isEmpty(newUserName)){
+                    System.out.println("Invalid new user name. Exiting!!!");
+                    logger.info("Invalid new user name. Exiting!!!");
+                    System.exit(1);
+                }
+                while (loader.isMoreToProcess()) {
+                    loader.load();
+                }
+                logger.info("Load complete. Exiting!!!");
+                System.exit(0);
+            }else{
+                System.out.println("ChangeUserNameUtil: Incorrect Arguments \n Usage: \n <loginId> <current-password> <new-username>");
+                logger.error("ChangeUserNameUtil: Incorrect Arguments \n Usage: \n <loginId> <current-password> <new-username>");
+                System.exit(1);
+            }
+        }
+        catch (Exception e) {
+            logger.error("Error loading", e);
+            System.exit(1);
+        }
+    }
+
+    @Override
+    public void init() throws Exception {
+    }
+
+    @Override
+    public void printStats() {
+    }
+
+    @Override
+    public void execLoad() {
+        logger.info("==> ChangeUserNameUtil.execLoad()");
+        updateUserName();
+        logger.info("<== ChangeUserNameUtil.execLoad()");
+    }
+
+    public void updateUserName() {
+        // if newUserName already exists
+        if (daoMgr.getXXPortalUser().findByLoginId(newUserName) != null) {
+            System.out.println("New user name already exist in DB!");
+            logger.error("New user name already exist in DB");
+            System.exit(1);
+        }
+        XXPortalUser xPortalUser=daoMgr.getXXPortalUser().findByLoginId(userLoginId);
+        if (xPortalUser!=null){
+            String dbPassword=xPortalUser.getPassword();
+            String currentEncryptedPassword=null;
+            try {
+                currentEncryptedPassword=userMgr.encrypt(userLoginId, currentPassword);
+                if (currentEncryptedPassword.equals(dbPassword)){
+                    userMgr.updateOldUserName(userLoginId, newUserName, currentPassword);
+                    logger.info("User Name '"+userLoginId+"' updated to '"+newUserName+"' sucessfully.");
+                }
+                else{
+                    System.out.println("Invalid user password");
+                    logger.error("Invalid user password");
+                    System.exit(1);
+                }
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+        else{
+            System.out.println("User does not exist in DB!!");
+            logger.error("User does not exist in DB");
+            System.exit(1);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/05e179d4/src/main/assembly/admin-web.xml
----------------------------------------------------------------------
diff --git a/src/main/assembly/admin-web.xml b/src/main/assembly/admin-web.xml
index b06cdec..70873d5 100644
--- a/src/main/assembly/admin-web.xml
+++ b/src/main/assembly/admin-web.xml
@@ -358,6 +358,7 @@
 			<include>ranger_credential_helper.py</include>
 			<include>deleteUserGroupUtil.py</include>
 			<include>changepasswordutil.py</include>
+                        <include>changeusernameutil.py</include>
 		</includes>
 		<fileMode>544</fileMode>
 	</fileSet>