django.utils.crypto.get_random_string

Here are the examples of the python api django.utils.crypto.get_random_string taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

199 Examples 7

Example 1

Project: django-allauth
Source File: models.py
View license
    @classmethod
    def stash_state(cls, request):
        state = cls.state_from_request(request)
        verifier = get_random_string()
        request.session['socialaccount_state'] = (state, verifier)
        return verifier

Example 2

Project: django-allauth
Source File: provider.py
View license
    def get_nonce(self, request, or_create=False, pop=False):
        if pop:
            nonce = request.session.pop(NONCE_SESSION_KEY, None)
        else:
            nonce = request.session.get(NONCE_SESSION_KEY)
        if not nonce and or_create:
            nonce = get_random_string(32)
            request.session[NONCE_SESSION_KEY] = nonce
        return nonce

Example 3

Project: pretix
Source File: invoices.py
View license
def invoice_filename(instance, filename: str) -> str:
    secret = get_random_string(length=16, allowed_chars=string.ascii_letters + string.digits)
    return 'invoices/{org}/{ev}/{no}-{code}-{secret}.pdf'.format(
        org=instance.event.organizer.slug, ev=instance.event.slug,
        no=instance.number, code=instance.order.code, secret=secret
    )

Example 4

Project: pretix
Source File: user.py
View license
    def post(self, request, *args, **kwargs):
        d = StaticDevice.objects.get(user=self.request.user, name='emergency')
        d.token_set.all().delete()
        for i in range(10):
            d.token_set.create(token=get_random_string(length=12, allowed_chars='1234567890'))
        self.request.user.log_action('pretix.user.settings.2fa.regenemergency', user=self.request.user)
        self.request.user.send_security_notice([
            _('Your two-factor emergency codes have been regenerated.')
        ])
        messages.success(request, _('Your emergency codes have been newly generated. Remember to store them in a safe '
                                    'place in case you lose access to your devices.'))
        return redirect(reverse('control:user.settings.2fa'))

Example 5

Project: pretix
Source File: views.py
View license
    def get_context_data(self, **kwargs):
        ctx = super().get_context_data()
        key = self.request.event.settings.get('pretixdroid_key')
        if not key or 'flush_key' in self.request.GET:
            key = get_random_string(length=32,
                                    allowed_chars=string.ascii_uppercase + string.ascii_lowercase + string.digits)
            self.request.event.settings.set('pretixdroid_key', key)

        ctx['qrdata'] = json.dumps({
            'version': API_VERSION,
            'url': build_absolute_uri('plugins:pretixdroid:api.redeem', kwargs={
                'organizer': self.request.event.organizer.slug,
                'event': self.request.event.slug
            })[:-7],  # the slice removes the redeem/ part at the end
            'key': key
        })
        return ctx

Example 6

Project: PyClassLessons
Source File: hashers.py
View license
def make_password(password, salt=None, hasher='default'):
    """
    Turn a plain-text password into a hash for database storage

    Same as encode() but generates a new random salt.
    If password is None then a concatenation of
    UNUSABLE_PASSWORD_PREFIX and a random string will be returned
    which disallows logins. Additional random string reduces chances
    of gaining access to staff or superuser accounts.
    See ticket #20079 for more info.
    """
    if password is None:
        return UNUSABLE_PASSWORD_PREFIX + get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH)
    hasher = get_hasher(hasher)

    if not salt:
        salt = hasher.salt()

    return hasher.encode(password, salt)

Example 7

Project: PyClassLessons
Source File: models.py
View license
    def make_random_password(self, length=10,
                             allowed_chars='abcdefghjkmnpqrstuvwxyz'
                                           'ABCDEFGHJKLMNPQRSTUVWXYZ'
                                           '23456789'):
        """
        Generates a random password with the given length and given
        allowed_chars. Note that the default value of allowed_chars does not
        have "I" or "O" or letters and digits that look similar -- just to
        avoid confusion.
        """
        return get_random_string(length, allowed_chars)

Example 8

Project: PyClassLessons
Source File: base.py
View license
    def _get_new_session_key(self):
        "Returns session key that isn't being used."
        while True:
            session_key = get_random_string(32, VALID_KEY_CHARS)
            if not self.exists(session_key):
                break
        return session_key

Example 9

Project: PyClassLessons
Source File: storage.py
View license
    def get_available_name(self, name):
        """
        Returns a filename that's free on the target storage system, and
        available for new content to be written to.
        """
        dir_name, file_name = os.path.split(name)
        file_root, file_ext = os.path.splitext(file_name)
        # If the filename already exists, add an underscore and a random 7
        # character alphanumeric string (before the file extension, if one
        # exists) to the filename until the generated filename doesn't exist.
        while self.exists(name):
            # file_ext includes the dot.
            name = os.path.join(dir_name, "%s_%s%s" % (file_root, get_random_string(7), file_ext))

        return name

Example 10

Project: PyClassLessons
Source File: startproject.py
View license
    def handle(self, project_name=None, target=None, *args, **options):
        self.validate_name(project_name, "project")

        # Check that the project_name cannot be imported.
        try:
            import_module(project_name)
        except ImportError:
            pass
        else:
            raise CommandError("%r conflicts with the name of an existing "
                               "Python module and cannot be used as a "
                               "project name. Please try another name." %
                               project_name)

        # Create a random SECRET_KEY hash to put it in the main settings.
        chars = '[email protected]#$%^&*(-_=+)'
        options['secret_key'] = get_random_string(50, chars)

        super(Command, self).handle('project', project_name, target, **options)

Example 11

Project: django-userlog
Source File: util.py
View license
def get_token(username, length=20, timeout=20):
    """
    Obtain an access token that can be passed to a websocket client.
    """
    redis = get_redis_client()
    token = get_random_string(length)
    token_key = 'token:{}'.format(token)
    redis.set(token_key, username)
    redis.expire(token_key, timeout)
    return token

Example 12

Project: Misago
Source File: poll.py
View license
    def clean_choice(self, choice):
        clean_choice = {
            'hash': choice.get('hash', get_random_string(12)),
            'label': choice.get('label', ''),
        }

        serializer = PollChoiceSerializer(data=clean_choice)
        if not serializer.is_valid():
            raise serializers.ValidationError(_("One or more poll choices are invalid."))

        return serializer.data

Example 13

Project: Misago
Source File: poll.py
View license
    def validate_choices(self, choices):
        clean_choices = list(map(self.clean_choice, choices))

        self.validate_choices_num(clean_choices)

        for choice in clean_choices:
            choice.update({
                'hash': get_random_string(12),
                'votes': 0
            })

        return clean_choices

Example 14

Project: ava
Source File: models.py
View license
    @staticmethod
    def generate_unique_token():
        logger.debug('Function called'
                     ' - evaluate::EvaluateTargetProfile::generate_unique_token')
        return_string = get_random_string(settings.EVAL_TOKEN_LENGTH)

        while EvaluateTest.objects.filter(token__exact=return_string).exists():
            return_string - get_random_string(settings.EVAL_TOKEN_LENGTH)

        return return_string

Example 15

Project: Django--an-app-at-a-time
Source File: hashers.py
View license
def make_password(password, salt=None, hasher='default'):
    """
    Turn a plain-text password into a hash for database storage

    Same as encode() but generates a new random salt.
    If password is None then a concatenation of
    UNUSABLE_PASSWORD_PREFIX and a random string will be returned
    which disallows logins. Additional random string reduces chances
    of gaining access to staff or superuser accounts.
    See ticket #20079 for more info.
    """
    if password is None:
        return UNUSABLE_PASSWORD_PREFIX + get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH)
    hasher = get_hasher(hasher)

    if not salt:
        salt = hasher.salt()

    return hasher.encode(password, salt)

Example 16

Project: Django--an-app-at-a-time
Source File: models.py
View license
    def make_random_password(self, length=10,
                             allowed_chars='abcdefghjkmnpqrstuvwxyz'
                                           'ABCDEFGHJKLMNPQRSTUVWXYZ'
                                           '23456789'):
        """
        Generates a random password with the given length and given
        allowed_chars. Note that the default value of allowed_chars does not
        have "I" or "O" or letters and digits that look similar -- just to
        avoid confusion.
        """
        return get_random_string(length, allowed_chars)

Example 17

Project: Django--an-app-at-a-time
Source File: base.py
View license
    def _get_new_session_key(self):
        "Returns session key that isn't being used."
        while True:
            session_key = get_random_string(32, VALID_KEY_CHARS)
            if not self.exists(session_key):
                break
        return session_key

Example 18

View license
def encrypt_match_report(apps, schema_editor):
    MatchReport = apps.get_model('delivery', 'MatchReport')
    for match_report in MatchReport.objects.all():
        match_report_content = MatchReportContent(identifier=match_report.identifier,
                                                  perp_name=match_report.name,
                                                  email=match_report.contact_email,
                                                  phone=match_report.contact_phone,
                                                  contact_name=match_report.contact_name,
                                                  voicemail=match_report.contact_voicemail,
                                                  notes=match_report.contact_notes)
        match_report.salt = get_random_string()
        stretched_identifier = pbkdf2(match_report.identifier, match_report.salt,
                                      settings.ORIGINAL_KEY_ITERATIONS, digest=hashlib.sha256)
        encrypted_match_report = _pepper(_encrypt_report(stretched_key=stretched_identifier,
                                                         report_text=json.dumps(match_report_content.__dict__)))
        match_report.encrypted = encrypted_match_report
        if match_report.seen:
            match_report.identifier = None
        match_report.save()

Example 19

Project: callisto-core
Source File: models.py
View license
    def encrypt_match_report(self, report_text, key):
        """Encrypts and attaches report text. Generates a random salt and stores it in an encode prefix on the
        MatchReport object.

        Args:
          report_text (str): the full text of the report
          key (str): the secret key

        """
        if self.salt:
            self.salt = None
        hasher = get_hasher()
        salt = get_random_string()

        encoded = hasher.encode(key, salt)
        self.encode_prefix, stretched_key = hasher.split_encoded(encoded)

        self.encrypted = _pepper(_encrypt_report(stretched_key=stretched_key, report_text=report_text))

Example 20

Project: callisto-core
Source File: models.py
View license
    def encrypt_report(self, report_text, key):
        """Encrypts and attaches report text. Generates a random salt and stores it on the Report object.

        Args:
          report_text (str): the full text of the report
          key (str): the secret key
          edit (obj): the object to edit
          autosave (bool): whether or not this encryption is part of an automatic save

        """
        if not self.salt:
            self.salt = get_random_string()
        self.encrypted = _legacy_encrypt_report(salt=self.salt, key=key, report_text=report_text)

Example 21

Project: callisto-core
Source File: models.py
View license
    def encrypt_match_report(self, report_text, key):
        """Encrypts and attaches report text. Generates a random salt and stores it on the MatchReport object.

        Args:
          report_text (str): the full text of the report
          key (str): the secret key

        """
        self.salt = get_random_string()
        self.encrypted = _pepper(_legacy_encrypt_report(salt=self.salt, key=key, report_text=report_text))

Example 22

Project: shuup
Source File: _shipments.py
View license
    def __init__(self, *args, **kwargs):
        super(Shipment, self).__init__(*args, **kwargs)
        if not self.identifier:
            if self.order and self.order.pk:
                prefix = '%s/%s/' % (self.order.pk, self.order.shipments.count())
            else:
                prefix = ''
            self.identifier = prefix + get_random_string(32)

Example 23

Project: shuup
Source File: telemetry.py
View license
def get_installation_key():
    """
    Get the unique installation ID for this Shuup instance.

    If one doesn't exist, it's generated and saved at this point.

    :return: Installation key string
    :rtype: str
    """
    try:
        return PersistentCacheEntry.objects.get(**INSTALLATION_KEY_KWARGS).data
    except ObjectDoesNotExist:
        key = get_random_string(48)
        PersistentCacheEntry.objects.create(data=key, **INSTALLATION_KEY_KWARGS)
        return key

Example 24

Project: splunk-webframework
Source File: appdo.py
View license
def generate_random_key():
    from django.utils.crypto import get_random_string
    chars = '[email protected]#$%^&*(-_=+)'
    secret_key = get_random_string(50, chars)
    
    return secret_key

Example 25

Project: splunk-webframework
Source File: models.py
View license
    def make_random_password(self, length=10,
                             allowed_chars='abcdefghjkmnpqrstuvwxyz'
                                           'ABCDEFGHJKLMNPQRSTUVWXYZ'
                                           '23456789'):
        """
        Generates a random password with the given length and given
        allowed_chars. Note that the default value of allowed_chars does not
        have "I" or "O" or letters and digits that look similar -- just to
        avoid confusion.
        """
        return get_random_string(length, allowed_chars)

Example 26

Project: splunk-webframework
Source File: base.py
View license
    def _get_new_session_key(self):
        "Returns session key that isn't being used."
        while True:
            session_key = get_random_string(32, VALID_KEY_CHARS)
            if not self.exists(session_key):
                break
        return session_key

Example 27

View license
    def handle(self, *args, **options):
        length = options.get('length')
        alphabet = options.get('alphabet')
        secret_key = str(get_random_string(length=length, allowed_chars=alphabet))

        print('SECRET_KEY: %s' % secret_key)

Example 28

Project: python-useful
Source File: auth.py
View license
def get_random_password(size=7, cadre='abcdehkmnprstuvxyz2345678923456789'):
    """
    Returns the password composed of the easily readable letters and digits
    by default (digits doubled to increase the occurrence).
    """
    return get_random_string(size, cadre)

Example 29

Project: django-registration
Source File: models.py
View license
    def create_profile(self, user):
        """
        Create a ``RegistrationProfile`` for a given user, and return
        the ``RegistrationProfile``.

        """
        User = get_user_model()
        username = str(getattr(user, User.USERNAME_FIELD))
        hash_input = (get_random_string(5) + username).encode('utf-8')
        activation_key = hashlib.sha1(hash_input).hexdigest()
        return self.create(user=user,
                           activation_key=activation_key)

Example 30

Project: db_file_storage
Source File: storage.py
View license
    def _get_unique_filename(self, model_cls, filename_field, filename):
        final_name = filename

        if ('.' in filename.rsplit(os.sep, 1)[-1]):
            stem, extension = final_name.rsplit('.', 1)
        else:
            stem, extension = (final_name, '')

        random_str = get_random_string(7)
        while model_cls.objects.filter(
            **{filename_field: final_name}
        ).exists():  # pragma: no cover
            final_name = '%s_(%s)%s' % (
                stem, random_str,
                ('.%s' % extension) if extension else ''
            )
            random_str = get_random_string(7)
        return final_name

Example 31

Project: nodewatcher
Source File: forms.py
View license
    def set_defaults(self, state, create):
        # If we are not creating a new node, ignore this.
        if not create:
            return

        # Generate a default random password in case no authentication is configured.
        try:
            state.filter_items('core.authentication')[0]
        except IndexError:
            state.append_item(
                cgm_models.PasswordAuthenticationConfig,
                password=crypto.get_random_string(),
            )

Example 32

Project: nodewatcher
Source File: forms.py
View license
    def set_defaults(self, state, create):
        # If we are not creating a new node, ignore this.
        if not create:
            return

        # Generate a default random password in case no authentication is configured.
        try:
            state.filter_items('core.authentication')[0]
        except IndexError:
            state.append_item(
                cgm_models.PasswordAuthenticationConfig,
                password=crypto.get_random_string(),
            )

Example 33

Project: zentral
Source File: models.py
View license
def enroll(serial_number, business_unit):
    tree = {'source': {'module': 'zentral.contrib.osquery',
                       'name': 'OSQuery'},
            'reference': get_random_string(64),
            'machine': {'serial_number': serial_number}}
    if business_unit:
        tree['business_unit'] = business_unit.serialize()
    ms, _ = MachineSnapshot.objects.commit(tree)
    # TODO: check, but _ must be always true (because of the random reference)
    try:
        previous_ms = ms.mt_previous
    except MachineSnapshot.DoesNotExist:
        previous_ms = None
    if previous_ms:
        # ms with same source for same serial number existed
        return ms, 're-enrollment'
    return ms, 'enrollment'

Example 34

Project: cgstudiomap
Source File: base_user.py
View license
    def make_random_password(self, length=10,
                             allowed_chars='abcdefghjkmnpqrstuvwxyz'
                                           'ABCDEFGHJKLMNPQRSTUVWXYZ'
                                           '23456789'):
        """
        Generate a random password with the given length and given
        allowed_chars. The default value of allowed_chars does not have "I" or
        "O" or letters and digits that look similar -- just to avoid confusion.
        """
        return get_random_string(length, allowed_chars)

Example 35

Project: cgstudiomap
Source File: hashers.py
View license
def make_password(password, salt=None, hasher='default'):
    """
    Turn a plain-text password into a hash for database storage

    Same as encode() but generates a new random salt.
    If password is None then a concatenation of
    UNUSABLE_PASSWORD_PREFIX and a random string will be returned
    which disallows logins. Additional random string reduces chances
    of gaining access to staff or superuser accounts.
    See ticket #20079 for more info.
    """
    if password is None:
        return UNUSABLE_PASSWORD_PREFIX + get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH)
    hasher = get_hasher(hasher)

    if not salt:
        salt = hasher.salt()

    return hasher.encode(password, salt)

Example 36

Project: cgstudiomap
Source File: base.py
View license
    def _get_new_session_key(self):
        "Returns session key that isn't being used."
        while True:
            session_key = get_random_string(32, VALID_KEY_CHARS)
            if not self.exists(session_key):
                break
        return session_key

Example 37

Project: hue
Source File: hashers.py
View license
def make_password(password, salt=None, hasher='default'):
    """
    Turn a plain-text password into a hash for database storage

    Same as encode() but generates a new random salt.
    If password is None then a concatenation of
    UNUSABLE_PASSWORD_PREFIX and a random string will be returned
    which disallows logins. Additional random string reduces chances
    of gaining access to staff or superuser accounts.
    See ticket #20079 for more info.
    """
    if password is None:
        return UNUSABLE_PASSWORD_PREFIX + get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH)
    hasher = get_hasher(hasher)

    if not salt:
        salt = hasher.salt()

    return hasher.encode(password, salt)

Example 38

Project: hue
Source File: models.py
View license
    def make_random_password(self, length=10,
                             allowed_chars='abcdefghjkmnpqrstuvwxyz'
                                           'ABCDEFGHJKLMNPQRSTUVWXYZ'
                                           '23456789'):
        """
        Generates a random password with the given length and given
        allowed_chars. Note that the default value of allowed_chars does not
        have "I" or "O" or letters and digits that look similar -- just to
        avoid confusion.
        """
        return get_random_string(length, allowed_chars)

Example 39

Project: hue
Source File: base.py
View license
    def _get_new_session_key(self):
        "Returns session key that isn't being used."
        while True:
            session_key = get_random_string(32, VALID_KEY_CHARS)
            if not self.exists(session_key):
                break
        return session_key

Example 40

Project: hue
Source File: storage.py
View license
    def get_available_name(self, name):
        """
        Returns a filename that's free on the target storage system, and
        available for new content to be written to.
        """
        dir_name, file_name = os.path.split(name)
        file_root, file_ext = os.path.splitext(file_name)
        # If the filename already exists, add an underscore and a random 7
        # character alphanumeric string (before the file extension, if one
        # exists) to the filename until the generated filename doesn't exist.
        while self.exists(name):
            # file_ext includes the dot.
            name = os.path.join(dir_name, "%s_%s%s" % (file_root, get_random_string(7), file_ext))

        return name

Example 41

Project: hue
Source File: startproject.py
View license
    def handle(self, project_name=None, target=None, *args, **options):
        self.validate_name(project_name, "project")

        # Check that the project_name cannot be imported.
        try:
            import_module(project_name)
        except ImportError:
            pass
        else:
            raise CommandError("%r conflicts with the name of an existing "
                               "Python module and cannot be used as a "
                               "project name. Please try another name." %
                               project_name)

        # Create a random SECRET_KEY hash to put it in the main settings.
        chars = '[email protected]#$%^&*(-_=+)'
        options['secret_key'] = get_random_string(50, chars)

        super(Command, self).handle('project', project_name, target, **options)

Example 42

Project: decode-Django
Source File: models.py
View license
    def make_random_password(self, length=10,
                             allowed_chars='abcdefghjkmnpqrstuvwxyz'
                                           'ABCDEFGHJKLMNPQRSTUVWXYZ'
                                           '23456789'):
        """
        Generates a random password with the given length and given
        allowed_chars. Note that the default value of allowed_chars does not
        have "I" or "O" or letters and digits that look similar -- just to
        avoid confusion.
        """
        return get_random_string(length, allowed_chars)

Example 43

Project: decode-Django
Source File: base.py
View license
    def _get_new_session_key(self):
        "Returns session key that isn't being used."
        while True:
            session_key = get_random_string(32, VALID_KEY_CHARS)
            if not self.exists(session_key):
                break
        return session_key

Example 44

Project: django
Source File: base_user.py
View license
    def make_random_password(self, length=10,
                             allowed_chars='abcdefghjkmnpqrstuvwxyz'
                                           'ABCDEFGHJKLMNPQRSTUVWXYZ'
                                           '23456789'):
        """
        Generate a random password with the given length and given
        allowed_chars. The default value of allowed_chars does not have "I" or
        "O" or letters and digits that look similar -- just to avoid confusion.
        """
        return get_random_string(length, allowed_chars)

Example 45

Project: django
Source File: hashers.py
View license
def make_password(password, salt=None, hasher='default'):
    """
    Turn a plain-text password into a hash for database storage

    Same as encode() but generates a new random salt.
    If password is None then a concatenation of
    UNUSABLE_PASSWORD_PREFIX and a random string will be returned
    which disallows logins. Additional random string reduces chances
    of gaining access to staff or superuser accounts.
    See ticket #20079 for more info.
    """
    if password is None:
        return UNUSABLE_PASSWORD_PREFIX + get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH)
    hasher = get_hasher(hasher)

    if not salt:
        salt = hasher.salt()

    return hasher.encode(password, salt)

Example 46

Project: django
Source File: base.py
View license
    def _get_new_session_key(self):
        "Returns session key that isn't being used."
        while True:
            session_key = get_random_string(32, VALID_KEY_CHARS)
            if not self.exists(session_key):
                break
        return session_key

Example 47

Project: django
Source File: utils.py
View license
def get_random_secret_key():
    """
    Return a 50 character random string usable as a SECRET_KEY setting value.
    """
    chars = '[email protected]#$%^&*(-_=+)'
    return get_random_string(50, chars)

Example 48

Project: django
Source File: creation.py
View license
    def _test_database_passwd(self):
        password = self._test_settings_get('PASSWORD')
        if password is None and self._test_user_create():
            # Oracle passwords are limited to 30 chars and can't contain symbols.
            password = get_random_string(length=30)
        return password

Example 49

Project: django-mail-queue
Source File: utils.py
View license
def upload_to(instance, filename):
    # Because filename may also contain path
    # which is unneeded and may be harmful
    filename = filename.split('/')[-1]
    # Because instead of filesystem, email message
    # can have multiple attachments with the same filename
    return 'mailqueue-attahcments/{0}_{1}'.format(get_random_string(length=24), filename)

Example 50

Project: edx-platform
Source File: middleware.py
View license
    @classmethod
    def create(cls, session_id, user_id):
        """
        Factory method for creating the cryptographically bound
        safe cookie data for the session and the user.

        Raises SafeCookieError if session_id is None.
        """
        cls._validate_cookie_params(session_id, user_id)
        safe_cookie_data = SafeCookieData(
            cls.CURRENT_VERSION,
            session_id,
            key_salt=get_random_string(),
            signature=None,
        )
        safe_cookie_data.sign(user_id)
        return safe_cookie_data