ldap_createsuperuser.py 1.67 KB
Newer Older
1 2 3 4 5
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import getpass
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
6

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

class Command(BaseCommand):
    help = "Used to create a superuser without a usable password."
    
    # This command is reused for creating staff-only users (ldap_createstaffuser),
    # so this flag controls wether the superuser privilege is granted or not.
    # The `is_staff` privilege is always granted.
    GRANT_SUPERUSER_PRIVILEGES = True
    
    def add_arguments(self, parser):
        parser.add_argument('--username', dest='username', metavar='USERNAME', nargs='?', help='Specifies the login for the superuser.')
    
    def handle(self, **options):
        User = get_user_model()
        
        #verbosity = options.get()
        username = options.get('username')
        if not username:
            current_user = getpass.getuser()
26
            input_user = input('Username [{}]: '.format(current_user))
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
            if not input_user:
                username = current_user
            else:
                username = input_user

        obj, created = User.objects.get_or_create(username=username)
        obj.is_staff = True
        if self.GRANT_SUPERUSER_PRIVILEGES:
            privilege = "superuser"
            obj.is_superuser = True
        else:
            privilege = "staff"

        
        if created:
            obj.set_unusable_password()
            obj.save()
            self.stdout.write("Created user %s with %s privileges." % (username, privilege))
        else:
            obj.save()
            self.stdout.write("Granted %s privileges to user %s." % (privilege, username))
48