From 4c0d52d9ede51bd7d06559ec1a074b0aeca8bb85 Mon Sep 17 00:00:00 2001 From: Henrik Levkowetz Date: Wed, 9 Apr 2014 18:28:42 +0000 Subject: [PATCH] Split out the actual htpasswd import functionality from the BaseCommand subclass, so we can call it from elsewhere. - Legacy-Id: 7583 --- .../management/commands/import_htpasswd.py | 50 ++++++++++--------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/ietf/utils/management/commands/import_htpasswd.py b/ietf/utils/management/commands/import_htpasswd.py index 304cd9e5b..52a08819a 100644 --- a/ietf/utils/management/commands/import_htpasswd.py +++ b/ietf/utils/management/commands/import_htpasswd.py @@ -6,6 +6,31 @@ from textwrap import dedent from django.contrib.auth.models import User from django.core.management.base import BaseCommand +def import_htpasswd_file(filename, verbosity=1, overwrite=False): + with open(filename) as file: + for line in file: + if not ':' in line: + raise ValueError('Found a line without colon separator in the htpassword file %s:'+ + ' "%s"' % (file.name, line)) + username, password = line.strip().split(':', 1) + try: + user = User.objects.get(username=username) + if overwrite == True or not user.password: + if password.startswith('{SHA}'): + user.password = "sha1$$%s" % password[len('{SHA}'):] + elif password.startswith('$apr1$'): + user.password = "md5$%s" % password[len('$apr1$'):] + else: # Assume crypt + user.password = "crypt$$%s" % password + user.save() + if verbosity > 0: + sys.stderr.write('.') + if verbosity > 1: + sys.stderr.write(' %s\n' % username) + except User.DoesNotExist: + if verbosity > 1: + sys.stderr.write('\nNo such user: %s\n' % username) + class Command(BaseCommand): """ Import passwords from one or more htpasswd files to Django's auth_user table. @@ -33,28 +58,5 @@ class Command(BaseCommand): overwrite = options.get('overwrite', False) verbosity = int(options.get('verbosity')) for fn in filenames: - with open(fn) as file: - for line in file: - if not ':' in line: - raise ValueError('Found a line without colon separator in the htpassword file %s:'+ - ' "%s"' % (file.name, line)) - username, password = line.strip().split(':', 1) - try: - user = User.objects.get(username=username) - if overwrite == True or not user.password: - if password.startswith('{SHA}'): - user.password = "sha1$$%s" % password[len('{SHA}'):] - elif password.startswith('$apr1$'): - user.password = "md5$%s" % password[len('$apr1$'):] - else: # Assume crypt - user.password = "crypt$$%s" % password - user.save() - if verbosity > 0: - sys.stderr.write('.') - if verbosity > 1: - sys.stderr.write(' %s\n' % username) - except User.DoesNotExist: - if verbosity > 1: - sys.stderr.write('\nNo such user: %s\n' % username) - + import_htpasswd_file(fn) \ No newline at end of file