Skip to content

Commit 4c0d52d

Browse files
committed
Split out the actual htpasswd import functionality from the BaseCommand subclass, so we can call it from elsewhere.
- Legacy-Id: 7583
1 parent 156b0d4 commit 4c0d52d

1 file changed

Lines changed: 26 additions & 24 deletions

File tree

ietf/utils/management/commands/import_htpasswd.py

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,31 @@
66
from django.contrib.auth.models import User
77
from django.core.management.base import BaseCommand
88

9+
def import_htpasswd_file(filename, verbosity=1, overwrite=False):
10+
with open(filename) as file:
11+
for line in file:
12+
if not ':' in line:
13+
raise ValueError('Found a line without colon separator in the htpassword file %s:'+
14+
' "%s"' % (file.name, line))
15+
username, password = line.strip().split(':', 1)
16+
try:
17+
user = User.objects.get(username=username)
18+
if overwrite == True or not user.password:
19+
if password.startswith('{SHA}'):
20+
user.password = "sha1$$%s" % password[len('{SHA}'):]
21+
elif password.startswith('$apr1$'):
22+
user.password = "md5$%s" % password[len('$apr1$'):]
23+
else: # Assume crypt
24+
user.password = "crypt$$%s" % password
25+
user.save()
26+
if verbosity > 0:
27+
sys.stderr.write('.')
28+
if verbosity > 1:
29+
sys.stderr.write(' %s\n' % username)
30+
except User.DoesNotExist:
31+
if verbosity > 1:
32+
sys.stderr.write('\nNo such user: %s\n' % username)
33+
934
class Command(BaseCommand):
1035
"""
1136
Import passwords from one or more htpasswd files to Django's auth_user table.
@@ -33,28 +58,5 @@ def handle(self, *filenames, **options):
3358
overwrite = options.get('overwrite', False)
3459
verbosity = int(options.get('verbosity'))
3560
for fn in filenames:
36-
with open(fn) as file:
37-
for line in file:
38-
if not ':' in line:
39-
raise ValueError('Found a line without colon separator in the htpassword file %s:'+
40-
' "%s"' % (file.name, line))
41-
username, password = line.strip().split(':', 1)
42-
try:
43-
user = User.objects.get(username=username)
44-
if overwrite == True or not user.password:
45-
if password.startswith('{SHA}'):
46-
user.password = "sha1$$%s" % password[len('{SHA}'):]
47-
elif password.startswith('$apr1$'):
48-
user.password = "md5$%s" % password[len('$apr1$'):]
49-
else: # Assume crypt
50-
user.password = "crypt$$%s" % password
51-
user.save()
52-
if verbosity > 0:
53-
sys.stderr.write('.')
54-
if verbosity > 1:
55-
sys.stderr.write(' %s\n' % username)
56-
except User.DoesNotExist:
57-
if verbosity > 1:
58-
sys.stderr.write('\nNo such user: %s\n' % username)
59-
61+
import_htpasswd_file(fn)
6062

0 commit comments

Comments
 (0)