File: set_fake_passwords.py

package info (click to toggle)
python-django-extensions 1.7.4-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,016 kB
  • ctags: 1,342
  • sloc: python: 8,873; makefile: 117
file content (51 lines) | stat: -rw-r--r-- 1,767 bytes parent folder | download
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
# -*- coding: utf-8 -*-
"""
set_fake_passwords.py

    Reset all user passwords to a common value. Useful for testing in a
    development environment. As such, this command is only available when
    setting.DEBUG is True.

"""
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError

from django_extensions.management.utils import signalcommand

DEFAULT_FAKE_PASSWORD = 'password'


class Command(BaseCommand):
    help = 'DEBUG only: sets all user passwords to a common value ("%s" by default)' % (DEFAULT_FAKE_PASSWORD, )
    requires_model_validation = False

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--prompt', dest='prompt_passwd', default=False,
            action='store_true',
            help='Prompts for the new password to apply to all users')
        parser.add_argument(
            '--password', dest='default_passwd', default=DEFAULT_FAKE_PASSWORD,
            help='Use this as default password.')

    @signalcommand
    def handle(self, *args, **options):
        if not settings.DEBUG:
            raise CommandError('Only available in debug mode')

        if options.get('prompt_passwd', False):
            from getpass import getpass
            passwd = getpass('Password: ')
            if not passwd:
                raise CommandError('You must enter a valid password')
        else:
            passwd = options.get('default_passwd', DEFAULT_FAKE_PASSWORD)

        User = get_user_model()
        user = User()
        user.set_password(passwd)
        count = User.objects.all().update(password=user.password)

        print('Reset %d passwords' % count)