Source

BlingNode / htpasswd_users.py

Full commit
from optparse import OptionParser, make_option
import common
common = __import__('common')
from common import command_line_call, ask_yes_or_no
from utils import list_callback

def is_username_valid(htpasswd_username):
    """
        Validates the username to be used in the htpasswd file
    """
    MIN_USERNAME_LENGTH=1
    if len(htpasswd_username)<MIN_USERNAME_LENGTH:
        print "Username is too short!"
        return False
    else:
        return True

def full_htpasswd_file_name(project):
    """
        returns the full filename of the htpasswd file of a given project.
    """
    HTPASSWD_DIR="/var/lib/htpasswd/"
    HTPASSWD_FILE = "%s%s.htpasswd" % (HTPASSWD_DIR, project)
    return HTPASSWD_FILE

def add_user(sudo, HTPASSWD_FILE, username, password=None):
    """
        Checks if a username is valid for the htpasswd file then adds it to the file.
    """
    if is_username_valid(username):
        if password:
            if sudo:
                sudo.run('htpasswd -b %s %s %s' % (HTPASSWD_FILE, username, password))
            else:
                command_line_call("""sudo htpasswd -b %s %s %s""" % (HTPASSWD_FILE, username, password))
        else:
            if sudo:
                sudo.run('htpasswd %s %s' % (HTPASSWD_FILE, username))
            else:
                command_line_call("""sudo htpasswd %s %s""" % (HTPASSWD_FILE, username))
    else:
        print "Invalid username '%s'. Try again." % username
        
def remove_user(sudo, HTPASSWD_FILE, username):
    """
        Removes a user form the htpasswd file.
    """
    if sudo:
        sudo.run('htpasswd -D %s %s' % (HTPASSWD_FILE, username))
    else:
        command_line_call("""sudo htpasswd -D %s %s""" % (HTPASSWD_FILE, username))

def change_user(sudo, HTPASSWD_FILE, username, password):
    remove_user(sudo, HTPASSWD_FILE, username)
    add_user(sudo, HTPASSWD_FILE, username, password)
    
def run_with_no_options(sudo, project, users = None):
    common.check_for_htpasswd_file(project, warn_if_exists=True, sudo=sudo)
    HTPASSWD_FILE = full_htpasswd_file_name(project)
    if users:
        for user in users:
            add_user(sudo, HTPASSWD_FILE, user[0], user[1])
    else:
        add_htpasswd_user_prompt = "\nAdd users to the HTPASSWD file? (y/n)"
        while ask_yes_or_no(add_htpasswd_user_prompt) == "y":
            username = raw_input("\nUsername: ")
            add_user(sudo, HTPASSWD_FILE, username)
            add_htpasswd_user_prompt = "\nAdd more users to the HTPASSWD file? (y/n)"
    
def main(options, args):
    ####### Check For root Access
    if not common.is_user_root():
        common.error_exit(msg="\nERROR: Run this script as root\n")
    
    sudo = None
    
    if options.password:
        print "password: %s" % options.password
        sudo = common.Sudo(password = options.password)
    
    if options.project:
        project = options.project
    else:
        project = raw_input("\nWhat is the Project Name?\n")
    
    common.check_for_htpasswd_file(project, warn_if_exists=True, sudo=sudo)
    HTPASSWD_FILE = full_htpasswd_file_name(project)
    
    if options.add:
        for user in options.add:
            add_user(sudo, HTPASSWD_FILE, user[0], user[1])
    else:
        add_htpasswd_user_prompt = "\nAdd users to the HTPASSWD file? (y/n)"
        while ask_yes_or_no(add_htpasswd_user_prompt) == "y":
            username = raw_input("\nUsername: ")
            add_user(sudo, HTPASSWD_FILE, username)
            add_htpasswd_user_prompt = "\nAdd more users to the HTPASSWD file? (y/n)"
    if options.remove:
        for user in options.remove:
            remove_user(sudo, HTPASSWD_FILE, user)

if __name__ == "__main__":
    options = [
        make_option('-p', '--password', dest='password', action='store',
            help="User password to send to sudo. Note that this will"
            "appear in the operating system's process list."),
        make_option('--project', dest='project',
            help="Project name"),
        make_option('-a','--add', type='string', action='callback', callback=list_callback,
            help="accepts a list of usernames and passwords to be included/changed in the .htpasswd file. sample usage: username1:password1,username2:password2"),
        make_option('-r', '--remove', type='string', action='callback', callback=list_callback,
            help="removes users from the .htpasswd file sample usage: username1,username2"),
    ]

    parser = OptionParser(option_list=options)
    (options, args) = parser.parse_args()

    main(options, args)