forked from adamlaska/datatracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport_htpasswd.py
More file actions
63 lines (51 loc) · 2.51 KB
/
import_htpasswd.py
File metadata and controls
63 lines (51 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# Copyright The IETF Trust 2014-2020, All Rights Reserved
import io
import sys
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 io.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.
This command only imports passwords; it does not import usernames, as that
would leave usernames without associated Person records in the database,
something which is undesirable.
By default the command won't overwrite existing password entries, but
given the --force switch, it will overwrite existing entries too. Without
the --force switch, the command is safe to run repeatedly.
"""
help = dedent(__doc__).strip()
def add_arguments(self, parser):
parser.add_argument('--force',
action='store_true', dest='overwrite', default=False,
help='Overwrite existing passwords in the auth_user table.')
args = '[path [path [...]]]'
def handle(self, *filenames, **options):
overwrite = options.get('overwrite', False)
verbosity = int(options.get('verbosity'))
for fn in filenames:
import_htpasswd_file(fn, verbosity=verbosity, overwrite=overwrite)