summaryrefslogtreecommitdiff
path: root/lib/python2.7/site-packages/django/contrib/auth/management
diff options
context:
space:
mode:
authorttt2017-05-13 00:29:47 +0530
committerttt2017-05-13 00:29:47 +0530
commitabf599be33b383a6a5baf9493093b2126a622ac8 (patch)
tree4c5ab6e0d935d5e65fabcf0258e4a00dd20a5afa /lib/python2.7/site-packages/django/contrib/auth/management
downloadSBHS-2018-Rpi-abf599be33b383a6a5baf9493093b2126a622ac8.tar.gz
SBHS-2018-Rpi-abf599be33b383a6a5baf9493093b2126a622ac8.tar.bz2
SBHS-2018-Rpi-abf599be33b383a6a5baf9493093b2126a622ac8.zip
added all server files
Diffstat (limited to 'lib/python2.7/site-packages/django/contrib/auth/management')
-rw-r--r--lib/python2.7/site-packages/django/contrib/auth/management/__init__.py193
-rw-r--r--lib/python2.7/site-packages/django/contrib/auth/management/commands/__init__.py0
-rw-r--r--lib/python2.7/site-packages/django/contrib/auth/management/commands/changepassword.py63
-rw-r--r--lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py143
4 files changed, 399 insertions, 0 deletions
diff --git a/lib/python2.7/site-packages/django/contrib/auth/management/__init__.py b/lib/python2.7/site-packages/django/contrib/auth/management/__init__.py
new file mode 100644
index 0000000..7b0f5ad
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/auth/management/__init__.py
@@ -0,0 +1,193 @@
+"""
+Creates permissions for all installed apps that need permissions.
+"""
+from __future__ import unicode_literals
+
+import getpass
+import unicodedata
+
+from django.contrib.auth import (models as auth_app, get_permission_codename,
+ get_user_model)
+from django.core import exceptions
+from django.core.management.base import CommandError
+from django.db import DEFAULT_DB_ALIAS, router
+from django.db.models import get_model, get_models, signals, UnavailableApp
+from django.utils.encoding import DEFAULT_LOCALE_ENCODING
+from django.utils import six
+from django.utils.six.moves import input
+
+
+def _get_all_permissions(opts, ctype):
+ """
+ Returns (codename, name) for all permissions in the given opts.
+ """
+ builtin = _get_builtin_permissions(opts)
+ custom = list(opts.permissions)
+ _check_permission_clashing(custom, builtin, ctype)
+ return builtin + custom
+
+
+def _get_builtin_permissions(opts):
+ """
+ Returns (codename, name) for all autogenerated permissions.
+ """
+ perms = []
+ for action in ('add', 'change', 'delete'):
+ perms.append((get_permission_codename(action, opts),
+ 'Can %s %s' % (action, opts.verbose_name_raw)))
+ return perms
+
+
+def _check_permission_clashing(custom, builtin, ctype):
+ """
+ Check that permissions for a model do not clash. Raises CommandError if
+ there are duplicate permissions.
+ """
+ pool = set()
+ builtin_codenames = set(p[0] for p in builtin)
+ for codename, _name in custom:
+ if codename in pool:
+ raise CommandError(
+ "The permission codename '%s' is duplicated for model '%s.%s'." %
+ (codename, ctype.app_label, ctype.model_class().__name__))
+ elif codename in builtin_codenames:
+ raise CommandError(
+ "The permission codename '%s' clashes with a builtin permission "
+ "for model '%s.%s'." %
+ (codename, ctype.app_label, ctype.model_class().__name__))
+ pool.add(codename)
+
+
+def create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS, **kwargs):
+ try:
+ get_model('auth', 'Permission')
+ except UnavailableApp:
+ return
+
+ if not router.allow_syncdb(db, auth_app.Permission):
+ return
+
+ from django.contrib.contenttypes.models import ContentType
+
+ app_models = get_models(app)
+
+ # This will hold the permissions we're looking for as
+ # (content_type, (codename, name))
+ searched_perms = list()
+ # The codenames and ctypes that should exist.
+ ctypes = set()
+ for klass in app_models:
+ # Force looking up the content types in the current database
+ # before creating foreign keys to them.
+ ctype = ContentType.objects.db_manager(db).get_for_model(klass)
+ ctypes.add(ctype)
+ for perm in _get_all_permissions(klass._meta, ctype):
+ searched_perms.append((ctype, perm))
+
+ # Find all the Permissions that have a content_type for a model we're
+ # looking for. We don't need to check for codenames since we already have
+ # a list of the ones we're going to create.
+ all_perms = set(auth_app.Permission.objects.using(db).filter(
+ content_type__in=ctypes,
+ ).values_list(
+ "content_type", "codename"
+ ))
+
+ perms = [
+ auth_app.Permission(codename=codename, name=name, content_type=ctype)
+ for ctype, (codename, name) in searched_perms
+ if (ctype.pk, codename) not in all_perms
+ ]
+ auth_app.Permission.objects.using(db).bulk_create(perms)
+ if verbosity >= 2:
+ for perm in perms:
+ print("Adding permission '%s'" % perm)
+
+
+def create_superuser(app, created_models, verbosity, db, **kwargs):
+ try:
+ get_model('auth', 'Permission')
+ UserModel = get_user_model()
+ except UnavailableApp:
+ return
+
+ from django.core.management import call_command
+
+ if UserModel in created_models and kwargs.get('interactive', True):
+ msg = ("\nYou just installed Django's auth system, which means you "
+ "don't have any superusers defined.\nWould you like to create one "
+ "now? (yes/no): ")
+ confirm = input(msg)
+ while 1:
+ if confirm not in ('yes', 'no'):
+ confirm = input('Please enter either "yes" or "no": ')
+ continue
+ if confirm == 'yes':
+ call_command("createsuperuser", interactive=True, database=db)
+ break
+
+
+def get_system_username():
+ """
+ Try to determine the current system user's username.
+
+ :returns: The username as a unicode string, or an empty string if the
+ username could not be determined.
+ """
+ try:
+ result = getpass.getuser()
+ except (ImportError, KeyError):
+ # KeyError will be raised by os.getpwuid() (called by getuser())
+ # if there is no corresponding entry in the /etc/passwd file
+ # (a very restricted chroot environment, for example).
+ return ''
+ if six.PY2:
+ try:
+ result = result.decode(DEFAULT_LOCALE_ENCODING)
+ except UnicodeDecodeError:
+ # UnicodeDecodeError - preventive treatment for non-latin Windows.
+ return ''
+ return result
+
+
+def get_default_username(check_db=True):
+ """
+ Try to determine the current system user's username to use as a default.
+
+ :param check_db: If ``True``, requires that the username does not match an
+ existing ``auth.User`` (otherwise returns an empty string).
+ :returns: The username, or an empty string if no username can be
+ determined.
+ """
+ # If the User model has been swapped out, we can't make any assumptions
+ # about the default user name.
+ if auth_app.User._meta.swapped:
+ return ''
+
+ default_username = get_system_username()
+ try:
+ default_username = unicodedata.normalize('NFKD', default_username)\
+ .encode('ascii', 'ignore').decode('ascii').replace(' ', '').lower()
+ except UnicodeDecodeError:
+ return ''
+
+ # Run the username validator
+ try:
+ auth_app.User._meta.get_field('username').run_validators(default_username)
+ except exceptions.ValidationError:
+ return ''
+
+ # Don't return the default username if it is already taken.
+ if check_db and default_username:
+ try:
+ auth_app.User._default_manager.get(username=default_username)
+ except auth_app.User.DoesNotExist:
+ pass
+ else:
+ return ''
+ return default_username
+
+signals.post_syncdb.connect(create_permissions,
+ dispatch_uid="django.contrib.auth.management.create_permissions")
+signals.post_syncdb.connect(create_superuser,
+ sender=auth_app, dispatch_uid="django.contrib.auth.management.create_superuser")
diff --git a/lib/python2.7/site-packages/django/contrib/auth/management/commands/__init__.py b/lib/python2.7/site-packages/django/contrib/auth/management/commands/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/auth/management/commands/__init__.py
diff --git a/lib/python2.7/site-packages/django/contrib/auth/management/commands/changepassword.py b/lib/python2.7/site-packages/django/contrib/auth/management/commands/changepassword.py
new file mode 100644
index 0000000..ad1c784
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/auth/management/commands/changepassword.py
@@ -0,0 +1,63 @@
+from __future__ import unicode_literals
+
+import getpass
+from optparse import make_option
+
+from django.contrib.auth import get_user_model
+from django.core.management.base import BaseCommand, CommandError
+from django.db import DEFAULT_DB_ALIAS
+from django.utils.encoding import force_str
+
+
+class Command(BaseCommand):
+ option_list = BaseCommand.option_list + (
+ make_option('--database', action='store', dest='database',
+ default=DEFAULT_DB_ALIAS, help='Specifies the database to use. Default is "default".'),
+ )
+ help = "Change a user's password for django.contrib.auth."
+
+ requires_model_validation = False
+
+ def _get_pass(self, prompt="Password: "):
+ p = getpass.getpass(prompt=force_str(prompt))
+ if not p:
+ raise CommandError("aborted")
+ return p
+
+ def handle(self, *args, **options):
+ if len(args) > 1:
+ raise CommandError("need exactly one or zero arguments for username")
+
+ if args:
+ username, = args
+ else:
+ username = getpass.getuser()
+
+ UserModel = get_user_model()
+
+ try:
+ u = UserModel._default_manager.using(options.get('database')).get(**{
+ UserModel.USERNAME_FIELD: username
+ })
+ except UserModel.DoesNotExist:
+ raise CommandError("user '%s' does not exist" % username)
+
+ self.stdout.write("Changing password for user '%s'\n" % u)
+
+ MAX_TRIES = 3
+ count = 0
+ p1, p2 = 1, 2 # To make them initially mismatch.
+ while p1 != p2 and count < MAX_TRIES:
+ p1 = self._get_pass()
+ p2 = self._get_pass("Password (again): ")
+ if p1 != p2:
+ self.stdout.write("Passwords do not match. Please try again.\n")
+ count = count + 1
+
+ if count == MAX_TRIES:
+ raise CommandError("Aborting password change for user '%s' after %s attempts" % (u, count))
+
+ u.set_password(p1)
+ u.save()
+
+ return "Password changed successfully for user '%s'" % u
diff --git a/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py b/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py
new file mode 100644
index 0000000..ac2835d
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py
@@ -0,0 +1,143 @@
+"""
+Management utility to create superusers.
+"""
+from __future__ import unicode_literals
+
+import getpass
+import sys
+from optparse import make_option
+
+from django.contrib.auth import get_user_model
+from django.contrib.auth.management import get_default_username
+from django.core import exceptions
+from django.core.management.base import BaseCommand, CommandError
+from django.db import DEFAULT_DB_ALIAS
+from django.utils.encoding import force_str
+from django.utils.six.moves import input
+from django.utils.text import capfirst
+
+
+class Command(BaseCommand):
+
+ def __init__(self, *args, **kwargs):
+ # Options are defined in an __init__ method to support swapping out
+ # custom user models in tests.
+ super(Command, self).__init__(*args, **kwargs)
+ self.UserModel = get_user_model()
+ self.username_field = self.UserModel._meta.get_field(self.UserModel.USERNAME_FIELD)
+
+ self.option_list = BaseCommand.option_list + (
+ make_option('--%s' % self.UserModel.USERNAME_FIELD, dest=self.UserModel.USERNAME_FIELD, default=None,
+ help='Specifies the login for the superuser.'),
+ make_option('--noinput', action='store_false', dest='interactive', default=True,
+ help=('Tells Django to NOT prompt the user for input of any kind. '
+ 'You must use --%s with --noinput, along with an option for '
+ 'any other required field. Superusers created with --noinput will '
+ ' not be able to log in until they\'re given a valid password.' %
+ self.UserModel.USERNAME_FIELD)),
+ make_option('--database', action='store', dest='database',
+ default=DEFAULT_DB_ALIAS, help='Specifies the database to use. Default is "default".'),
+ ) + tuple(
+ make_option('--%s' % field, dest=field, default=None,
+ help='Specifies the %s for the superuser.' % field)
+ for field in self.UserModel.REQUIRED_FIELDS
+ )
+
+ option_list = BaseCommand.option_list
+ help = 'Used to create a superuser.'
+
+ def handle(self, *args, **options):
+ username = options.get(self.UserModel.USERNAME_FIELD, None)
+ interactive = options.get('interactive')
+ verbosity = int(options.get('verbosity', 1))
+ database = options.get('database')
+
+ # If not provided, create the user with an unusable password
+ password = None
+ user_data = {}
+
+ # Do quick and dirty validation if --noinput
+ if not interactive:
+ try:
+ if not username:
+ raise CommandError("You must use --%s with --noinput." %
+ self.UserModel.USERNAME_FIELD)
+ username = self.username_field.clean(username, None)
+
+ for field_name in self.UserModel.REQUIRED_FIELDS:
+ if options.get(field_name):
+ field = self.UserModel._meta.get_field(field_name)
+ user_data[field_name] = field.clean(options[field_name], None)
+ else:
+ raise CommandError("You must use --%s with --noinput." % field_name)
+ except exceptions.ValidationError as e:
+ raise CommandError('; '.join(e.messages))
+
+ else:
+ # Prompt for username/password, and any other required fields.
+ # Enclose this whole thing in a try/except to trap for a
+ # keyboard interrupt and exit gracefully.
+ default_username = get_default_username()
+ try:
+
+ # Get a username
+ verbose_field_name = self.username_field.verbose_name
+ while username is None:
+ if not username:
+ input_msg = capfirst(verbose_field_name)
+ if default_username:
+ input_msg = "%s (leave blank to use '%s')" % (
+ input_msg, default_username)
+ raw_value = input(force_str('%s: ' % input_msg))
+
+ if default_username and raw_value == '':
+ raw_value = default_username
+ try:
+ username = self.username_field.clean(raw_value, None)
+ except exceptions.ValidationError as e:
+ self.stderr.write("Error: %s" % '; '.join(e.messages))
+ username = None
+ continue
+ try:
+ self.UserModel._default_manager.db_manager(database).get_by_natural_key(username)
+ except self.UserModel.DoesNotExist:
+ pass
+ else:
+ self.stderr.write("Error: That %s is already taken." %
+ verbose_field_name)
+ username = None
+
+ for field_name in self.UserModel.REQUIRED_FIELDS:
+ field = self.UserModel._meta.get_field(field_name)
+ user_data[field_name] = options.get(field_name)
+ while user_data[field_name] is None:
+ raw_value = input(force_str('%s: ' % capfirst(field.verbose_name)))
+ try:
+ user_data[field_name] = field.clean(raw_value, None)
+ except exceptions.ValidationError as e:
+ self.stderr.write("Error: %s" % '; '.join(e.messages))
+ user_data[field_name] = None
+
+ # Get a password
+ while password is None:
+ if not password:
+ password = getpass.getpass()
+ password2 = getpass.getpass(force_str('Password (again): '))
+ if password != password2:
+ self.stderr.write("Error: Your passwords didn't match.")
+ password = None
+ continue
+ if password.strip() == '':
+ self.stderr.write("Error: Blank passwords aren't allowed.")
+ password = None
+ continue
+
+ except KeyboardInterrupt:
+ self.stderr.write("\nOperation cancelled.")
+ sys.exit(1)
+
+ user_data[self.UserModel.USERNAME_FIELD] = username
+ user_data['password'] = password
+ self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
+ if verbosity >= 1:
+ self.stdout.write("Superuser created successfully.")