Python django.utils.crypto.get_random_string() Examples

The following are 30 code examples for showing how to use django.utils.crypto.get_random_string(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.utils.crypto , or try the search function .

Example 1
Project: GTDWeb   Author: lanbing510   File: startproject.py    License: GNU General Public License v2.0 6 votes vote down vote up
def handle(self, **options):
        project_name, target = options.pop('name'), options.pop('directory')
        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 to put it in the main settings.
        chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
        options['secret_key'] = get_random_string(50, chars)

        super(Command, self).handle('project', project_name, target, **options) 
Example 2
Project: django_reddit   Author: nikolak   File: test_frontpage.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.c = Client()
        author = RedditUser.objects.create(
            user=User.objects.create_user(username="username",
                                          password="password"))

        for i in range(50):
            Submission.objects.create(score=50 - i,
                                      title=get_random_string(length=20),
                                      author=author).save()

        for i in range(1, 50, 10):
            # [1, 11, 21] [31, 41] have upvotes (lists demonstrate pages)
            Vote.create(user=author,
                        vote_object=Submission.objects.get(id=i),
                        vote_value=1).save()

        for i in range(2, 50, 15):
            # [2, 17] [32, 47] have downvotes (lists demonstrate pages)
            Vote.create(user=author,
                        vote_object=Submission.objects.get(id=i),
                        vote_value=-1).save() 
Example 3
Project: django-sudo   Author: mattrobenolt   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def grant_sudo_privileges(request, max_age=COOKIE_AGE):
    """
    Assigns a random token to the user's session
    that allows them to have elevated permissions
    """
    user = getattr(request, "user", None)

    # If there's not a user on the request, just noop
    if user is None:
        return

    if not user.is_authenticated():
        raise ValueError("User needs to be logged in to be elevated to sudo")

    # Token doesn't need to be unique,
    # just needs to be unpredictable and match the cookie and the session
    token = get_random_string()
    request.session[COOKIE_NAME] = token
    request._sudo = True
    request._sudo_token = token
    request._sudo_max_age = max_age
    return token 
Example 4
Project: django-simple-forum   Author: MicroPyramid   File: views.py    License: MIT License 6 votes vote down vote up
def form_valid(self, form):
        user = User.objects.filter(email=self.request.POST.get('email'))
        if user:
            user = user[0]
            subject = "Password Reset"
            password = get_random_string(6)
            message = '<p>Your Password for the forum account is <strong>'+password + \
                '</strong></p><br/><p>Use this credentials to login into <a href="' + \
                settings.HOST_URL + '/forum/">forum</a></p>'
            to = user.email
            from_email = settings.DEFAULT_FROM_EMAIL
            Memail([to], from_email, subject, message, email_template_name=None, context=None)
            user.set_password(password)
            user.save()
            data = {
                "error": False, "response": "An Email is sent to the entered email id"}
            return JsonResponse(data)
        else:
            data = {
                "error": True, "message": "User With this email id doesn't exists!!!"}
            return JsonResponse(data) 
Example 5
def form_valid(self, form):
        user = form.user_cache

        activation = user.activation_set.first()
        activation.delete()

        code = get_random_string(20)

        act = Activation()
        act.code = code
        act.user = user
        act.save()

        send_activation_email(self.request, user.email, code)

        messages.success(self.request, _('A new activation code has been sent to your email address.'))

        return redirect('accounts:resend_activation_code') 
Example 6
def form_valid(self, form):
        user = self.request.user
        email = form.cleaned_data['email']

        if settings.ENABLE_ACTIVATION_AFTER_EMAIL_CHANGE:
            code = get_random_string(20)

            act = Activation()
            act.code = code
            act.user = user
            act.email = email
            act.save()

            send_activation_change_email(self.request, email, code)

            messages.success(self.request, _('To complete the change of email address, click on the link sent to it.'))
        else:
            user.email = email
            user.save()

            messages.success(self.request, _('Email successfully changed.'))

        return redirect('accounts:change_email') 
Example 7
Project: lego   Author: webkom   File: storage.py    License: MIT License 6 votes vote down vote up
def get_available_name(self, bucket, key, max_length=32, force_name_change=False):
        file_root, file_ext = os.path.splitext(key)
        while (
            force_name_change
            or self.key_exists(bucket, key)
            or (max_length and len(key) > max_length)
        ):
            force_name_change = False
            # file_ext includes the dot.
            key = "%s_%s%s" % (file_root, get_random_string(7), file_ext)
            if max_length is None:
                continue
            # Truncate file_root if max_length exceeded.
            truncation = len(key) - max_length
            if truncation > 0:
                file_root = file_root[:-truncation]
                # Entire file_root was truncated in attempt to find an available filename.
                if not file_root:
                    raise SuspiciousFileOperation(
                        'Storage can not find an available filename for "%s". '
                        "Please make sure that the corresponding file field "
                        'allows sufficient "max_length".' % key
                    )
                key = "%s_%s%s" % (file_root, get_random_string(7), file_ext)
        return key 
Example 8
Project: django-freeradius   Author: openwisp   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_or_create_user(self, row, users_list, password_length):
        generated_password = None
        username, password, email, first_name, last_name = row
        if not username and email:
            username = email.split('@')[0]
        username = find_available_username(username, users_list)
        user = User(username=username,
                    email=email,
                    first_name=first_name,
                    last_name=last_name)
        cleartext_delimiter = 'cleartext$'
        if not password:
            password = get_random_string(length=password_length)
            user.set_password(password)
            generated_password = ([username, password, email])
        elif password and password.startswith(cleartext_delimiter):
            password = password[len(cleartext_delimiter):]
            user.set_password(password)
        else:
            user.password = password
        user.full_clean()
        return user, generated_password 
Example 9
Project: django-gcloud-storage   Author: Strayer   File: conftest.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def storage(request):
    # create a random test bucket name
    bucket_name = "test_bucket_" + get_random_string(6, string.ascii_lowercase)

    storage = DjangoGCloudStorage(
        project=request.config.getoption("--gcs-project-name"),
        bucket=bucket_name,
        credentials_file_path=request.config.getoption("--gcs-credentials-file")
    )

    # Make sure the bucket exists
    bucket = Bucket(storage.client, bucket_name)
    bucket.create(
        location=request.config.getoption("--gcs-bucket-location")
    )

    yield storage

    storage.bucket.delete_blobs(storage.bucket.list_blobs())

    storage.bucket.delete(force=True) 
Example 10
Project: happinesspackets   Author: happinesspackets   File: misc.py    License: Apache License 2.0 6 votes vote down vote up
def readable_random_token(alphanumeric=False, add_spaces=False, short_token=False, long_token=False):
    """
    Generate a random token that is also reasonably readable.

    Generates 4 segments of 4 characters, seperated by dashes. Can either use digits only (default),
    or non-confusing letters and digits (alphanumeric=True). If add_spaces is set, spaces are added
    around the groups. This is intended to prevent mobile phones that see e.g. "-3" as an emoticon.
    If short_token is set, the token is two segments of four characters.
    """
    segments = 4
    if short_token:
        segments = 2
    if long_token:
        segments = 8
    if alphanumeric:
        allowed_chars = "BCDFGHJLKMNPQRSTVWXYZ23456789"
    else:
        allowed_chars = "1234567890"
    elements = [get_random_string(length=4, allowed_chars=allowed_chars) for i in range(segments)]
    join_str = "-"
    if add_spaces:
        join_str = " - "
    return join_str.join(elements) 
Example 11
Project: zentral   Author: zentralopensource   File: api.py    License: Apache License 2.0 6 votes vote down vote up
def do_node_post(self, data):
        probe_source_id = int(data["request_id"].split("_")[-1])
        probe_source = ProbeSource.objects.get(pk=probe_source_id)
        session_id = get_random_string(64)
        CarveSession.objects.create(probe_source=probe_source,
                                    machine_serial_number=self.machine_serial_number,
                                    session_id=session_id,
                                    carve_guid=data["carve_id"],
                                    carve_size=int(data["carve_size"]),
                                    block_size=int(data["block_size"]),
                                    block_count=int(data["block_count"]))
        post_file_carve_events(self.machine_serial_number, self.user_agent, self.ip,
                               [{"probe": {"id": probe_source.pk,
                                           "name": probe_source.name},
                                 "action": "start",
                                 "session_id": session_id}])
        return {"session_id": session_id} 
Example 12
Project: zentral   Author: zentralopensource   File: models.py    License: Apache License 2.0 6 votes vote down vote up
def get_sync_server_config(self):
        config = {k: getattr(self, k)
                  for k in self.SYNC_SERVER_CONFIGURATION_ATTRIBUTES}
        # translate client mode
        if self.client_mode == self.MONITOR_MODE:
            config["client_mode"] = self.PREFLIGHT_MONITOR_MODE
        elif self.client_mode == self.LOCKDOWN_MODE:
            config["client_mode"] = self.PREFLIGHT_LOCKDOWN_MODE
        else:
            raise NotImplementedError("Unknown santa client mode: {}".format(self.client_mode))
        # provide non matching regexp if the regexp are empty
        for attr in ("blacklist_regex",
                     "whitelist_regex"):
            if not config.get(attr):
                config[attr] = "NON_MATCHING_PLACEHOLDER_{}".format(get_random_string(8))
        return config 
Example 13
Project: zentral   Author: zentralopensource   File: test_artifacts.py    License: Apache License 2.0 6 votes vote down vote up
def setUpTestData(cls):
        push_certificate = PushCertificate.objects.create(
            name=get_random_string(64),
            topic=get_random_string(256),
            not_before=datetime(2000, 1, 1),
            not_after=datetime(2050, 1, 1),
            certificate=get_random_string(64).encode("utf-8"),
            private_key=get_random_string(64).encode("utf-8")
        )
        cls.meta_business_unit = MetaBusinessUnit.objects.create(name=get_random_string(32))
        cls.meta_business_unit.create_enrollment_business_unit()
        MetaBusinessUnitPushCertificate.objects.create(
            push_certificate=push_certificate,
            meta_business_unit=cls.meta_business_unit
        )
        cls.enrolled_device = EnrolledDevice.objects.create(
            push_certificate=push_certificate,
            serial_number=get_random_string(64),
            udid=get_random_string(36),
            token=get_random_string(32).encode("utf-8"),
            push_magic=get_random_string(73),
            unlock_token=get_random_string(32).encode("utf-8")
        )
        cls.serial_number = cls.enrolled_device.serial_number 
Example 14
Project: zentral   Author: zentralopensource   File: test_setup_views.py    License: Apache License 2.0 6 votes vote down vote up
def test_enroll_view(self):
        self.log_user_in()
        _, enrollment = self.create_enrollment()
        self.log_user_out()
        response = self.post_as_json("enroll", {})
        self.assertEqual(response.status_code, 400)
        machine_serial_number = get_random_string(32)
        response = self.post_as_json("enroll", {"secret": "yolo",
                                                "uuid": str(uuid.uuid4()),
                                                "serial_number": machine_serial_number})
        self.assertEqual(response.status_code, 400)
        response = self.post_as_json("enroll", {"secret": enrollment.secret.secret,
                                                "uuid": str(uuid.uuid4()),
                                                "serial_number": machine_serial_number})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], "application/json")
        json_response = response.json()
        self.assertCountEqual(["token"], json_response.keys())
        token = json_response["token"]
        enrolled_machine = EnrolledMachine.objects.get(enrollment=enrollment,
                                                       serial_number=machine_serial_number)
        self.assertEqual(token, enrolled_machine.token) 
Example 15
def get_valid_name(self, name):
        file_root, file_ext = os.path.splitext(name)
        return "%s%s" % (get_random_string(RANDOM_FILENAME_LENGTH).lower(), file_ext) 
Example 16
def get_available_name(self, name):
        dir_name, file_name = os.path.split(name)
        file_root, file_ext = os.path.splitext(file_name)
        while self.exists(name):
            name = os.path.join(dir_name, "%s%s" % (get_random_string(RANDOM_FILENAME_LENGTH).lower(), file_ext))
        return name 
Example 17
Project: django-phone-verify   Author: CuriousLearner   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_security_code(cls):
        """
        Returns a unique random `security_code` for given `TOKEN_LENGTH` in the settings.
        """
        token_length = django_settings.PHONE_VERIFICATION.get(
            "TOKEN_LENGTH", DEFAULT_TOKEN_LENGTH
        )
        return get_random_string(token_length, allowed_chars="0123456789") 
Example 18
Project: django-oidc-rp   Author: impak-finance   File: views.py    License: MIT License 5 votes vote down vote up
def get(self, request):
        """ Processes GET requests. """
        # Defines common parameters used to bootstrap the authentication request.
        authentication_request_params = request.GET.dict()
        authentication_request_params.update({
            'scope': oidc_rp_settings.SCOPES,
            'response_type': 'code',
            'client_id': oidc_rp_settings.CLIENT_ID,
            'redirect_uri': request.build_absolute_uri(reverse('oidc_auth_callback')),
        })

        # States should be used! They are recommended in order to maintain state between the
        # authentication request and the callback.
        if oidc_rp_settings.USE_STATE:
            state = get_random_string(oidc_rp_settings.STATE_LENGTH)
            authentication_request_params.update({'state': state})
            request.session['oidc_auth_state'] = state

        # Nonces should be used too! In that case the generated nonce is stored both in the
        # authentication request parameters and in the user's session.
        if oidc_rp_settings.USE_NONCE:
            nonce = get_random_string(oidc_rp_settings.NONCE_LENGTH)
            authentication_request_params.update({'nonce': nonce, })
            request.session['oidc_auth_nonce'] = nonce

        # Stores the "next" URL in the session if applicable.
        next_url = request.GET.get('next')
        request.session['oidc_auth_next_url'] = next_url \
            if is_safe_url(url=next_url, allowed_hosts=(request.get_host(), )) else None

        # Redirects the user to authorization endpoint.
        query = urlencode(authentication_request_params)
        redirect_url = '{url}?{query}'.format(
            url=oidc_rp_settings.PROVIDER_AUTHORIZATION_ENDPOINT, query=query)
        return HttpResponseRedirect(redirect_url) 
Example 19
Project: heltour   Author: cyanfish   File: views.py    License: MIT License 5 votes vote down vote up
def lichess_api_call(request, path):
    params = request.GET.dict()
    priority = int(params.pop('priority', 0))
    max_retries = int(params.pop('max_retries', 3))
    format = params.pop('format', None)
    redis_key = get_random_string(length=16)

    # support either a form encoded body or a raw body
    post_data = request.POST.dict()
    if len(post_data) == 0:
        post_data = request.body.decode('utf-8')

    worker.queue_work(priority, _do_lichess_api_call, redis_key, path, request.method,
                      post_data, params, priority, max_retries, format)
    return HttpResponse(redis_key) 
Example 20
Project: heltour   Author: cyanfish   File: models.py    License: MIT License 5 votes vote down vote up
def create_api_token():
    return get_random_string(length=32) 
Example 21
Project: resolwe   Author: genialis   File: test_purge.py    License: Apache License 2.0 5 votes vote down vote up
def create_and_run_processor(self, processor, **kwargs):
        processor_slug = get_random_string(6)
        Process.objects.create(
            slug=processor_slug,
            name="Test Purge Process",
            contributor=self.admin,
            type="data:test",
            version=1,
            **processor,
        )
        data = self.run_process(processor_slug, **kwargs)
        return data 
Example 22
Project: resolwe   Author: genialis   File: test_purge.py    License: Apache License 2.0 5 votes vote down vote up
def assertFieldWorks(
        self, field_type, field_value, script_setup, script_save, removed, not_removed
    ):
        """
        Checks that a field is handled correctly when running a processor, which
        uses the field.
        """

        field_schema = {"name": "sample", "label": "Sample output", "type": field_type}

        # Test output.
        data = self.create_and_run_processor(
            processor=dict(
                input_schema=[],
                output_schema=[field_schema],
                run={"language": "bash", "program": script_setup + "\n" + script_save},
            )
        )

        self.assertFilesRemoved(data, *removed)
        self.assertFilesNotRemoved(data, *not_removed)

        # Test descriptor.
        descriptor_schema = DescriptorSchema.objects.create(
            slug=get_random_string(6), contributor=self.admin, schema=[field_schema]
        )
        data = self.create_and_run_processor(
            processor=dict(
                input_schema=[],
                output_schema=[],
                run={"language": "bash", "program": script_setup},
            ),
            descriptor_schema=descriptor_schema,
            descriptor={"sample": field_value},
        )

        self.assertFilesRemoved(data, *removed)
        self.assertFilesNotRemoved(data, *not_removed) 
Example 23
Project: GTDWeb   Author: lanbing510   File: csrf.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _get_new_csrf_key():
    return get_random_string(CSRF_KEY_LENGTH) 
Example 24
Project: GTDWeb   Author: lanbing510   File: models.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 25
Project: GTDWeb   Author: lanbing510   File: storage.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_available_name(self, name, max_length=None):
        """
        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.
        # Truncate original name if required, so the new filename does not
        # exceed the max_length.
        while self.exists(name) or (max_length and len(name) > max_length):
            # file_ext includes the dot.
            name = os.path.join(dir_name, "%s_%s%s" % (file_root, get_random_string(7), file_ext))
            if max_length is None:
                continue
            # Truncate file_root if max_length exceeded.
            truncation = len(name) - max_length
            if truncation > 0:
                file_root = file_root[:-truncation]
                # Entire file_root was truncated in attempt to find an available filename.
                if not file_root:
                    raise SuspiciousFileOperation(
                        'Storage can not find an available filename for "%s". '
                        'Please make sure that the corresponding file field '
                        'allows sufficient "max_length".' % name
                    )
                name = os.path.join(dir_name, "%s_%s%s" % (file_root, get_random_string(7), file_ext))
        return name 
Example 26
Project: dingtalk-django-example   Author: 007gzs   File: storage.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_available_name(self, name, max_length=None):
        """
        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)
        nowstr = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
        name = os.path.join(dir_name, "%s%s%s" % (nowstr, get_random_string(8, '1234567890'), file_ext))
        return name 
Example 27
Project: Tenma   Author: Tenma-Server   File: generatesecretkey.py    License: MIT License 5 votes vote down vote up
def _generate_secret_key():
		chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+'
		return get_random_string(50, chars) 
Example 28
Project: django_reddit   Author: nikolak   File: test_comments.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.c = Client()
        self.credentials = {'username': 'commentposttest',
                            'password': 'password'}
        author = RedditUser.objects.create(
            user=User.objects.create_user(**self.credentials)
        )

        Submission.objects.create(
            id=99,
            score=1,
            title=get_random_string(length=12),
            author=author
        ) 
Example 29
Project: django_reddit   Author: nikolak   File: test_frontpage.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.c = Client()
        author = RedditUser.objects.create(
            user=User.objects.create_user(username="username",
                                          password="password"))

        for i in range(50):
            Submission.objects.create(score=i ** 2,
                                      title=get_random_string(length=20),
                                      author=author) 
Example 30
Project: bioforum   Author: reBiocoder   File: csrf.py    License: MIT License 5 votes vote down vote up
def _get_new_csrf_string():
    return get_random_string(CSRF_SECRET_LENGTH, allowed_chars=CSRF_ALLOWED_CHARS)