Python django.utils.crypto.get_random_string() Examples

The following are 30 code examples of django.utils.crypto.get_random_string(). 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 also want to check out all available functions/classes of the module django.utils.crypto , or try the search function .
Example #1
Source File: startproject.py    From GTDWeb with 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
Source File: api.py    From zentral with 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 #3
Source File: misc.py    From happinesspackets with 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 #4
Source File: test_frontpage.py    From django_reddit with 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 #5
Source File: models.py    From zentral with 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 #6
Source File: test_artifacts.py    From zentral with 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 #7
Source File: utils.py    From django-sudo with 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 #8
Source File: conftest.py    From django-gcloud-storage with 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 #9
Source File: views.py    From simple-django-login-and-register with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #10
Source File: test_setup_views.py    From zentral with 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 #11
Source File: views.py    From simple-django-login-and-register with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #12
Source File: views.py    From django-simple-forum with 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 #13
Source File: storage.py    From lego with 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 #14
Source File: models.py    From django-freeradius with 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 #15
Source File: settings.py    From ara with GNU General Public License v3.0 5 votes vote down vote up
def get_secret_key():
    if not settings.get("SECRET_KEY"):
        print("[ara] No setting found for SECRET_KEY. Generating a random key...")
        return get_random_string(length=50)
    return settings.get("SECRET_KEY") 
Example #16
Source File: test_api_views.py    From zentral with Apache License 2.0 5 votes vote down vote up
def make_enrolled_machine(self):
        return EnrolledMachine.objects.create(enrollment=self.enrollment,
                                              serial_number=get_random_string(32),
                                              token=get_random_string(64)) 
Example #17
Source File: test_api_views.py    From zentral with Apache License 2.0 5 votes vote down vote up
def test_job_details_conflict(self):
        enrolled_machine = self.make_enrolled_machine()
        response = self.post_as_json(reverse("munki:job_details"),
                                     {"machine_serial_number": get_random_string(3)},
                                     HTTP_AUTHORIZATION="MunkiEnrolledMachine {}".format(enrolled_machine.token))
        self.assertContains(response, "different from enrollment SN", status_code=403) 
Example #18
Source File: elasticsearch2.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, index):
        self.alias = index
        self.index = index.backend.index_class(
            index.backend,
            self.alias.name + '_' + get_random_string(7).lower()
        ) 
Example #19
Source File: test_api_views.py    From zentral with Apache License 2.0 5 votes vote down vote up
def test_job_details_old_way_conflict(self):
        _, api_secret = self.make_api_secret()
        response = self.post_as_json(reverse("munki:job_details"),
                                     {"machine_serial_number": get_random_string(3)},
                                     HTTP_ZENTRAL_API_SECRET=api_secret)
        self.assertContains(response, "different from enrollment SN", status_code=403) 
Example #20
Source File: base_user.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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 #21
Source File: test_api_views.py    From zentral with Apache License 2.0 5 votes vote down vote up
def test_post_job(self):
        enrolled_machine = self.make_enrolled_machine()
        computer_name = get_random_string(45)
        report_sha1sum = 40 * "0"
        response = self.post_as_json(reverse("munki:post_job"),
                                     {"machine_snapshot": {"serial_number": enrolled_machine.serial_number,
                                                           "system_info": {"computer_name": computer_name}},
                                      "reports": [{"start_time": "2018-01-01 00:00:00 +0000",
                                                   "end_time": "2018-01-01 00:01:00 +0000",
                                                   "basename": "report2018",
                                                   "run_type": "auto",
                                                   "sha1sum": report_sha1sum,
                                                   "events": []}]},
                                     HTTP_AUTHORIZATION="MunkiEnrolledMachine {}".format(enrolled_machine.token))
        self.assertEqual(response.status_code, 200)
        response = self.post_as_json(reverse("munki:job_details"),
                                     {"machine_serial_number": enrolled_machine.serial_number},
                                     HTTP_AUTHORIZATION="MunkiEnrolledMachine {}".format(enrolled_machine.token))
        self.assertEqual(response.status_code, 200)
        response_json = response.json()
        self.assertCountEqual(["last_seen_sha1sum"], response_json.keys())
        self.assertEqual(response_json["last_seen_sha1sum"], report_sha1sum)
        ms = MachineSnapshot.objects.current().get(serial_number=enrolled_machine.serial_number)
        ms2 = MachineSnapshot.objects.current().get(reference=enrolled_machine.serial_number)
        self.assertEqual(ms, ms2)
        self.assertEqual(ms.system_info.computer_name, computer_name) 
Example #22
Source File: creation.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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 #23
Source File: csrf.py    From Hands-On-Application-Development-with-PyCharm with 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) 
Example #24
Source File: models.py    From zentral with Apache License 2.0 5 votes vote down vote up
def save(self, *args, **kwargs):
        if not self.pk:
            self.secret = get_random_string(kwargs.pop("secret_length", 64))
        super().save(*args, **kwargs) 
Example #25
Source File: models.py    From django-rest-framework-passwordless with MIT License 5 votes vote down vote up
def generate_numeric_token():
    """
    Generate a random 6 digit string of numbers.
    We use this formatting to allow leading 0s.
    """
    return get_random_string(length=6, allowed_chars=string.digits) 
Example #26
Source File: views.py    From Django-to-do with MIT License 5 votes vote down vote up
def tasks(request):
    if request.method == 'POST':
        # this is wehere POST request is accessed
        form = TaskForm(request.POST or None)
        if form.is_valid():
            user = Username.objects.get(username=request.COOKIES.get('username'))
            temp = form.save(commit=False)
            temp.username = user
            temp.save()
            form = TaskForm()
        tasks = Task.objects.filter(username__username=request.COOKIES.get('username')).order_by('priority')
        return render(request, 'tasks.html', {'form': form, 'tasks': tasks, 'user': user})
    else:
        if 'username' not in request.COOKIES:
            from django.utils.crypto import get_random_string
            unique_id = get_random_string(length=32)
            username = Username()
            username.username = unique_id
            username.save()
            response = redirect(reverse('tasks'))
            # 604800s = 1 week
            response.set_cookie('username', username, max_age=604800)
            return response
        # this is where GET request are accessed
        form = TaskForm()
        tasks = Task.objects.filter(username__username=request.COOKIES.get('username')).order_by('priority')
        user = Username.objects.filter(username=request.COOKIES.get('username'))
    return render(request, 'tasks.html', {'form': form, 'tasks': tasks, 'user': user}) 
Example #27
Source File: models.py    From byro with Apache License 2.0 5 votes vote down vote up
def generate_default_token():
    return get_random_string(
        allowed_chars=string.ascii_lowercase + string.digits, length=32
    ) 
Example #28
Source File: suponoff-server.py    From suponoff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def configure(site_path, supervisors, debug, metadata_dir):
    settings.configure(
        DEBUG=debug,
        ALLOWED_HOSTS = ['*'],
        SECRET_KEY=get_random_string(50),
        ROOT_URLCONF=__name__,
        MIDDLEWARE_CLASSES=(
            'django.middleware.common.CommonMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.middleware.clickjacking.XFrameOptionsMiddleware',
        ),
        INSTALLED_APPS=(
            'django.contrib.contenttypes',
            'django.contrib.staticfiles',
            'suponoff',
        ),
        SUPERVISORS=supervisors,
        METADATA_DIR = metadata_dir,
        STATIC_URL='/'+site_path+'static/',
        SITE_ROOT='/'+site_path,
        # django<=1.8
        TEMPLATE_CONTEXT_PROCESSORS=['django.core.context_processors.request'],
        TEMPLATE_LOADERS=[
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader',
        ],
        # django>=1.8
        TEMPLATES = [
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'APP_DIRS': True,
            },
        ]
    ) 
Example #29
Source File: base.py    From django-connected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_application_state(self, request, callback):
        """Generate state optional parameter."""
        return get_random_string(32) 
Example #30
Source File: utils.py    From django-freeradius with GNU General Public License v3.0 5 votes vote down vote up
def prefix_generate_users(prefix, n, password_length):
    users_list = []
    user_password = []
    User = get_user_model()
    for i in range(n):
        username = find_available_username(prefix, users_list, True)
        password = get_random_string(length=password_length)
        u = User(username=username)
        u.set_password(password)
        users_list.append(u)
        user_password.append([username, password])
    return users_list, user_password