Exemple #1
0
    def test_not_exists(self):
        with htpasswd.Basic(t_userdb, mode='md5') as userdb:

            def not_exists():
                userdb.__contains__("nobody")

            self.assertRaises(UserNotExists, not_exists())
Exemple #2
0
def add_user(user_ID):
    data = request.get_json()
    password = data.get('password')
    # add user to passwd.git
    with htpasswd.Basic(PASSWD) as userdb:
        userdb.add(user_ID, password)
    return jsonify({'response': 1})
Exemple #3
0
 def user_has_api_password(self, user):
     try:
         with htpasswd.Basic(self.filename) as userdb:
             return user in userdb.users
     except IOError as e:
         logger.debug('Could not check htpasswd: %s' % unicode(e))
         raise e
def setup_apache(args):
    env = create_env(args)
    render_template('index.html.template', '/var/www/html/index.html', env)
    render_httpd_template('apache-proxy.conf.template', env)
    render_httpd_template('apache-proxy-nn.conf.template', env)
    render_httpd_template('apache-proxy-ap.conf.template', env)
    render_httpd_template('apache-proxy-rm.conf.template', env)
    render_httpd_template('apache-proxy-hue.conf.template', env)
    render_httpd_template('apache-proxy-hbase.conf.template', env)
    render_httpd_template('apache-proxy-zeppelin.conf.template', env)
    render_httpd_template('apache-proxy-jupyter.conf.template', env)

    hostname = env['aliasHostName']
    create_certificate(hostname)
    create_certificate('nn.' + hostname)
    create_certificate('ap.' + hostname)
    create_certificate('rm.' + hostname)
    create_certificate('hue.' + hostname)
    create_certificate('hbase.' + hostname)
    create_certificate('zeppelin.' + hostname)
    create_certificate('jupyter.' + hostname)

    with open(env["htpasswd"], 'wt') as userdb:
        pass
    with htpasswd.Basic(env["htpasswd"]) as userdb:
        userdb.add(env['username'], env['password'])
Exemple #5
0
def user_groups(username):
    admin, message = check_user_is_admin(get_remote_user(request))
    if not admin:
        # User is not admin or admin group does exist. Ciao
        return render_template("message.html", message=message)

    with htpasswd.Basic(CONF["PWD_FILE"], mode="md5") as userdb:
        with htpasswd.Group(CONF["GROUP_FILE"]) as groupdb:
            if request.method == "GET":
                groups = dict()
                for group in groupdb.groups:
                    if groupdb.is_user_in(username, group):
                        groups[group] = True
                    else:
                        groups[group] = False
                return render_template("groups.html", groups=groups)
            else:
                # POST Request
                checked_groups = [
                    g.split("_", 1)[1] for g in list(request.form.keys())
                    if g.startswith("group_")
                ]
                for group in groupdb.groups:
                    if group in checked_groups:
                        if not groupdb.is_user_in(username, group):
                            groupdb.add_user(username, group)
                    else:
                        if groupdb.is_user_in(username, group):
                            groupdb.delete_user(username, group)
                return render_template("message.html",
                                       message="User groups changed",
                                       success=True)
Exemple #6
0
def setup_munin():
    upload_template('config/munin/apache.conf',
                    '/etc/munin/apache.conf',
                    context=get_context(env),
                    use_jinja=True,
                    use_sudo=True)

    if not config_secrets['munin_auth_info']:
        # Generate a random password for now.
        config_secrets['munin_auth_info'] = {
            'munin':
            ''.join([
                random.choice(string.letters + string.digits)
                for i in range(40)
            ])
        }

    if not os.path.exists('config_secrets/munin-htpasswd'):
        f = open('config_secrets/munin-htpasswd', 'w')
        f.close()

    with htpasswd.Basic("config_secrets/munin-htpasswd") as userdb:
        for username, password in config_secrets['munin_auth_info'].iteritems(
        ):
            if username not in userdb:
                userdb.add(username, password)
            else:
                userdb.change_password(username, password)

    upload_template('config_secrets/munin-htpasswd',
                    '/etc/munin/munin-htpasswd',
                    context=get_context(env),
                    use_jinja=True,
                    use_sudo=True)
	def add_user(self, user, password, file_id="default"):
		file_config_section = self._get_file_config_section(file_id)
		if file_config_section is None:
			raise FileIdNotFound()

		# Read file config
		path = file_config_section["path"]
		mode = file_config_section["mode"]
		autocreate = file_config_section.getboolean("autocreate")

		# Create file at the path if configured so
		if autocreate:
			try:
				open(path, 'a').close()
			except OSError as e:
				L.error("Can't create file: {}".format(e))

		# Create user
		try:
			with htpasswd.Basic(
				userdb=path,
				mode=self._mode_to_htpasswd_mod_map[mode]
			) as userdb:
				userdb.add(user, password)
		except FileNotFoundError:
			L.error("File '{}' not found.".format(path))
			raise FileNotFound()
		except ValueError as e:
			L.error("Invalid file '{}': {}".format(path, e))
			raise InvalidFile()
		except htpasswd.basic.UserExists:
			L.error("User '{}' already exists".format(user))
			raise UserNotFound()
Exemple #8
0
 def get_users():
     with htpasswd.Basic(
             f'{str(os.path.realpath(str(Path(__file__).parent.parent)))}/config/.htpasswd'
     ) as userdb:
         try:
             return userdb.users
         except Exception:
             return []
Exemple #9
0
 def test_no_newline(self):
     with htpasswd.Basic(t_userdb, mode='md5') as userdb:
         self.assertNotIn('\n',
                          userdb._encrypt_password('password'),
                          msg="no newline characters allowed in pwd")
         self.assertNotIn('\r',
                          userdb._encrypt_password('password'),
                          msg="no newline characters allowed in pwd")
Exemple #10
0
 def test_change_password(self):
     with htpasswd.Basic(t_userdb, mode='md5') as userdb:
         userdb.change_password("alice", "password")
     with open(t_userdb, "r") as users:
         for user in users.readlines():
             if user.startswith("alice:"):
                 test = user
     self.assertRegexpMatches(test, "alice:\$apr1\$")
Exemple #11
0
 def test_change_password(self):
     with htpasswd.Basic(t_userdb) as userdb:
         userdb.change_password("alice", "password")
     with open(t_userdb, "r") as users:
         for user in users.readlines():
             if user.startswith("alice:"):
                 test = user
     self.assertNotEqual(test, "alice:2EtHk7FyD0THc\n")
Exemple #12
0
 def test_change_password(self):
     with htpasswd.Basic(t_userdb_md5_base, mode='md5-base') as userdb:
         userdb.change_password("john", "password")
     with open(t_userdb_md5_base, "r") as users:
         for user in users.readlines():
             if user.startswith("john:"):
                 test = user
     self.assertRegexpMatches(test, "john:\$1\$")
Exemple #13
0
def user(username):
    with htpasswd.Basic(CONF["PWD_FILE"], mode="md5") as userdb:
        new_user = username not in userdb
        admin, admin_error_message = check_user_is_admin(
            request.environ.get('REMOTE_USER'))
        ask_old_password = True
        if admin and request.environ.get('REMOTE_USER') != username:
            ask_old_password = False
        if CONF["REQUIRE_REMOTE_USER"]:
            if not request.environ.get('REMOTE_USER'):
                return render_template(
                    "message.html",
                    message=
                    "Sorry, you must be logged with http basic auth to go here"
                )
            if request.environ.get('REMOTE_USER') != username or new_user:
                # User trying to change someone else password

                if not admin:
                    # User is not admin or admin group does exist. Ciao
                    return render_template("message.html",
                                           message=admin_error_message)

        if request.method == "GET":
            return render_template("user.html",
                                   username=username,
                                   new=new_user,
                                   ask_old_password=ask_old_password,
                                   password_pattern=CONF["PASSWORD_PATTERN"])
        else:
            # POST Request
            if request.form["new_password"] != request.form["repeat_password"]:
                return render_template(
                    "message.html",
                    message="Password differ. Please hit back and try again")
            if ask_old_password and not check_password(
                    userdb.new_users[username], request.form["old_password"]):
                return render_template("message.html",
                                       message="password does not match")
            if not match(CONF["PASSWORD_PATTERN"],
                         request.form["new_password"]):
                return render_template(
                    "message.html",
                    message="new password does not match requirements (%s" %
                    CONF["PASSWORD_PATTERN_HELP"])
            # Ok, ready to change password or create user
            if new_user:
                userdb.add(username, request.form["new_password"])
                message = "User created"
            else:
                userdb.change_password(username, request.form["new_password"])
                message = "Password changed"
            if request.args.get("return_to"):
                return redirect(request.args.get("return_to"))
            else:
                return render_template("message.html",
                                       message=message,
                                       success=True)
Exemple #14
0
 def change_password(data):
     with htpasswd.Basic(
             f'{str(os.path.realpath(str(Path(__file__).parent.parent)))}/config/.htpasswd'
     ) as userdb:
         try:
             userdb.change_password(data['user'], data['password'])
         except htpasswd.basic.UserNotExists:
             return False
     return Password.get_users()
def add_user():
    username = request.form['username']
    password = request.form['password']
    with htpasswd.Basic(USER_DB) as userdb:
        try:
            userdb.add(username, password)
        except UserExists: # user exists
            flash('Error: user already exists', 'danger')
    return redirect(url_for('index'))
Exemple #16
0
def batch_user_creation():

    admin, message = check_user_is_admin(get_remote_user(request))
    if not admin:
        # User is not admin or admin group does exist. Ciao
        return render_template("message.html", message=message)

    with htpasswd.Basic(CONF["PWD_FILE"], mode="md5") as userdb:
        with htpasswd.Group(CONF["GROUP_FILE"]) as groupdb:
            if request.method == "GET":
                groups = []
                for group in groupdb.groups:
                    groups.append(group)
                return render_template(
                    "batch_user_creation.html",
                    groups=groups,
                    mail_capabilities=CONF["ENABLE_MAIL_CAPABILITIES"])
            else:
                # POST Request
                users = request.form["users_login"].split("\r\n")
                checked_groups = [
                    g.split("_", 1)[1] for g in list(request.form.keys())
                    if g.startswith("group_")
                ]
                result = []
                for username in users:
                    new_password = generate_random_password()
                    new_user = username not in userdb
                    if new_user:
                        userdb.add(username, new_password)
                        action = "create"
                    else:
                        userdb.change_password(username, new_password)
                        action = "update"
                    result.append((username, new_password, action))
                    for group in groupdb.groups:
                        if group in checked_groups:
                            if not groupdb.is_user_in(username, group):
                                groupdb.add_user(username, group)
                        else:
                            if groupdb.is_user_in(username, group):
                                groupdb.delete_user(username, group)
                message = "Batch of user created with generated passwords"

                # If the "send_mail" checkbox is enabled
                if request.form.get("send_mail") is not None:
                    message = "Batch of user created with generated passwords, a mail has been sent to all of them"
                    send_mail(result, request.form["mail_suffix"],
                              request.form["instance"])

                return render_template("message.html",
                                       message=message,
                                       success=True,
                                       result=render_template(
                                           "result_template.html",
                                           result=result))
def change_password(username=None):
    password = request.form['password']
    print("Updating password for {}".format(username))
    with htpasswd.Basic(USER_DB) as userdb:
        try:
            userdb.change_password(username, password)
            flash('Password updated', 'success')
        except UserNotExists:
            flash('Error: unknown user', 'danger')
    return redirect(url_for('index'))
Exemple #18
0
 def delete(self, user):
     try:
         with htpasswd.Basic(self.filename) as userdb:
             userdb.pop(user)
     except htpasswd.basic.UserNotExists:
         # we don't care
         pass
     except IOError as e:
         logger.debug('Could not update htpasswd: %s' % unicode(e))
         raise e
Exemple #19
0
def create_file():
    file_name = '.htpasswd'
    if os.path.exists(file_name):
        return file_name
    open(file_name, 'a').close()
    users = [('Adam', 'haslo'), ('Steve', 'Rogers'), ('Tony', 'haslo')]
    with htpasswd.Basic(file_name) as userdb:
        for user in users:
            userdb.add(*user)
    return file_name
Exemple #20
0
def reset_git_directory():
    for d in os.listdir(CHALLENGES_BASE_PATH):
        full_path = os.path.join(CHALLENGES_BASE_PATH, d)
        if os.path.isdir(full_path):
            subprocess.call(['sudo', 'chmod', '-R', '777', full_path])
            shutil.rmtree(full_path)

    with htpasswd.Basic(CHALLENGES_AUTH_FP) as authdb:
        for user in authdb.users:
            authdb.pop(user)
Exemple #21
0
 def _verify(self, expected_pairs):
     expected = OrderedDict()
     for user, password in expected_pairs:
         expected[user] = password
     with htpasswd.Basic(settings.HTPASSWD_PATH) as found:
         self.assertEqual(expected.keys(), found.new_users.keys())
         for item in expected.items():
             user = item[0]
             pwd = item[1]
             hash = found.new_users[user]
             _, alg, salt, value = hash.split('$', 3)
             self.assertEqual(hash, _recrypt(alg, salt, pwd))
def delete_user(username=None):
    # do not allow the admin user to be deleted
    if username == 'admin':
        flash('Error: you cannot delete the admin user', 'danger')
    else:
        with htpasswd.Basic(USER_DB) as userdb:
            try:
                userdb.pop(username)
                print("User deleted: {}".format(username))
            except UserNotExists:
                pass
    return redirect(url_for('index'))
def index():
    auth = request.authorization
    if not app.config['DEBUG']:
        # only allow the admin user
        if auth.username != 'admin':
            abort(403)
    with htpasswd.Basic(USER_DB) as userdb:
        users = userdb.users
    ctx = {
        'users': userdb.users,
    }
    return render_template('index.html', **ctx)
Exemple #24
0
def add_user(user_ID):
    """
    called every time when user registered
    :param user_ID:
    :return:
    """
    data = request.get_json()
    password = data.get('password')
    # add user to passwd.git
    with htpasswd.Basic(PASSWD) as userdb:
        userdb.add(user_ID, password)
    return jsonify({'response': 1})
Exemple #25
0
def rewrite_htpasswd():
    written_users = []
    users = User.objects.all()
    with open(settings.HTPASSWD_PATH, 'a'):
        pass
    with htpasswd.Basic(settings.HTPASSWD_PATH, 'md5') as userdb:
        userdb.new_users.clear()
        for u in users:
            if hasattr(u, 'encryptedpwd'):
                enc = u.encryptedpwd
                userdb.new_users[u.username] = enc.pwd
                written_users.append(u.username)
    return written_users
Exemple #26
0
def gen_htpasswd(pn, user):
    passwd = _gen_token(8)
    print('Writing user to {}'.format(pn))
    if not os.path.exists(pn):
        with open(pn, 'w'):
            pass

    with htpasswd.Basic(pn) as passdb:
        try:
            passdb.add(user, passwd)
        except htpasswd.basic.UserExists:
            print('WARNING: changing existing password')
            passdb.change_password(user, passwd)
    print('Password for user {} is "{}"'.format(user, passwd))
Exemple #27
0
def handleHtp(data, output):
    htpName = '.htpasswd_{}'.format(data['campus'])
    if os.path.isdir(conf.HTPDIR):
        if os.path.isfile(conf.HTPDIR + htpName):
            output['htpStatus'] = 'updated'
        else:
            htp = open(conf.HTPDIR + htpName, "w+")
            htp.close()
            output['htpStatus'] = 'created'
        with htpasswd.Basic(conf.HTPDIR + htpName) as userdb:
            try:
                userdb.add(data['login'], data['password'])
            except htpasswd.basic.UserExists, e:
                output['htpStatus'] = 'user exists'
        return 0
Exemple #28
0
 def set_api_password(self, user):
     password = ''.join(
         random.SystemRandom().choice(string.letters + string.digits)
         for _ in range(12))
     try:
         with htpasswd.Basic(self.filename) as userdb:
             try:
                 userdb.add(user, password)
             except htpasswd.basic.UserExists:
                 pass
             userdb.change_password(user, password)
             logger.debug('Updated htpasswd entry for user %s' % user)
     except IOError as e:
         logger.debug('Could not update htpasswd: %s' % unicode(e))
         raise e
     return password
Exemple #29
0
	def read_users(self, file_id="default"):
		path = self._get_file_path(file_id)
		if path is None:
			raise FileIdNotFound()

		try:
			with htpasswd.Basic(path) as userdb:
				users = userdb.users
		except FileNotFoundError:
			L.error("File '{}' not found.".format(path))
			raise FileNotFound()
		except ValueError as e:
			L.error("Invalid file '{}': {}".format(path, e))
			raise InvalidFile()

		return users
Exemple #30
0
 def setUp(self):
     self.passwd = join(dirname(__name__), "test_password")
     self.group = join(dirname(__name__), "test_group")
     open(self.passwd, "w").close()
     open(self.group, "w").close()
     with htpasswd.Basic(self.passwd, mode="md5") as userdb:
         userdb.add("user1", "user1")
         userdb.add("user2", "user2")
     with htpasswd.Group(self.group) as groupdb:
         groupdb.add_user("user1", "admin")
         groupdb.add_user("user1", "users")
         groupdb.add_user("user2", "users")
     app.config["TESTING"] = True
     CONF["PWD_FILE"] = self.passwd
     CONF["GROUP_FILE"] = self.group
     self.client = app.test_client()