Python django.utils.http.urlsafe_base64_encode() Examples

The following are 30 code examples of django.utils.http.urlsafe_base64_encode(). 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.http , or try the search function .
Example #1
Source File: views.py    From openwisp-radius with GNU General Public License v3.0 6 votes vote down vote up
def get_serializer_context(self):
        user = self.request.user
        if not user.pk:
            return
        uid = urlsafe_base64_encode(force_bytes(user.pk))
        # until django 2.1 urlsafe_base64_encode returned a bytestring
        if not isinstance(uid, str):  # noqa
            uid = uid.decode()
        token = default_token_generator.make_token(user)
        password_reset_urls = app_settings.PASSWORD_RESET_URLS
        default_url = password_reset_urls.get('default')
        password_reset_url = password_reset_urls.get(
            str(self.organization.pk), default_url
        )
        password_reset_url = password_reset_url.format(
            organization=self.organization.slug, uid=uid, token=token
        )
        context = {'request': self.request, 'password_reset_url': password_reset_url}
        return context 
Example #2
Source File: test_views.py    From django-user-management with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_password_mismatch(self):
        old_password = '0ld_passworD'
        new_password = 'n3w_Password'
        invalid_password = 'different_new_password'
        user = UserFactory.create(password=old_password)

        token = default_token_generator.make_token(user)
        uid = urlsafe_base64_encode(force_bytes(user.pk))

        request = self.create_request(
            'put',
            data={
                'new_password': new_password,
                'new_password2': invalid_password,
            },
            auth=False,
        )
        view = self.view_class.as_view()
        response = view(request, uidb64=uid, token=token)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        # Get the updated user from the db
        user = User.objects.get(pk=user.pk)
        self.assertTrue(user.check_password(old_password)) 
Example #3
Source File: views.py    From AutoGrader with MIT License 6 votes vote down vote up
def resend_signup_email(request):
    user = request.user

    current_site = get_current_site(request)
    subject = 'Activate Your FAST AutoGrader Account'
    message = render_to_string('account/account_activation_email.html', {
        'user': user,
        'domain': current_site.domain,
        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
        'token': account_activation_token.make_token(user),
    })

    user.email_user(subject, message)
    messages.success(request, 'Verification email sent, check your email account.')

    return HttpResponseRedirect(request.META.get('HTTP_REFERER')) 
Example #4
Source File: test_views.py    From django-user-management with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_put(self):
        old_password = '0ld_passworD'
        new_password = 'n3w_Password'
        user = UserFactory.create(password=old_password)

        token = default_token_generator.make_token(user)
        uid = urlsafe_base64_encode(force_bytes(user.pk))

        request = self.create_request(
            'put',
            data={'new_password': new_password, 'new_password2': new_password},
            auth=False,
        )
        view = self.view_class.as_view()
        response = view(request, uidb64=uid, token=token)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Get the updated user from the db
        user = User.objects.get(pk=user.pk)
        self.assertTrue(user.check_password(new_password)) 
Example #5
Source File: api.py    From volontulo with MIT License 6 votes vote down vote up
def password_reset(request):
    """REST API reset password view"""
    serializer = UsernameSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    username = serializer.validated_data.get('username')
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        pass
    else:
        context = {
            'email': username,
            'domain': get_current_site(request).domain,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'user': user,
            'token': default_token_generator.make_token(user),
            'protocol': 'https' if request.is_secure() else 'http',
        }
        send_mail(
            request,
            'password_reset',
            [username],
            context=context,
            send_copy_to_admin=False)
    return Response(dict(), status=status.HTTP_201_CREATED) 
Example #6
Source File: forms.py    From zulip with Apache License 2.0 6 votes vote down vote up
def generate_password_reset_url(user_profile: UserProfile,
                                token_generator: PasswordResetTokenGenerator) -> str:
    token = token_generator.make_token(user_profile)
    uid = urlsafe_base64_encode(force_bytes(user_profile.id))
    endpoint = reverse('django.contrib.auth.views.password_reset_confirm',
                       kwargs=dict(uidb64=uid, token=token))
    return f"{user_profile.realm.uri}{endpoint}" 
Example #7
Source File: test_connect_viewset.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_reset_user_password(self):
        # set user.last_login, ensures we get same/valid token
        # https://code.djangoproject.com/ticket/10265
        self.user.last_login = now()
        self.user.save()
        token = default_token_generator.make_token(self.user)
        new_password = "bobbob1"
        data = {'token': token, 'new_password': new_password}
        # missing uid, should fail
        request = self.factory.post('/', data=data)
        response = self.view(request)
        self.assertEqual(response.status_code, 400)

        data['uid'] = urlsafe_base64_encode(force_bytes(self.user.pk))
        # with uid, should be successful
        request = self.factory.post('/', data=data)
        response = self.view(request)
        self.assertEqual(response.status_code, 204)
        user = User.objects.get(email=self.user.email)
        self.assertTrue(user.check_password(new_password))

        request = self.factory.post('/', data=data)
        response = self.view(request)
        self.assertEqual(response.status_code, 400) 
Example #8
Source File: password_reset_serializer.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_password_reset_email(user, reset_url,
                             subject_template_name='registration/password_reset_subject.txt',  # noqa
                             email_template_name='api_password_reset_email.html',  # noqa
                             token_generator=default_token_generator):
    """Creates the subject and email body for password reset email."""
    result = urlparse(reset_url)
    site_name = domain = result.hostname
    c = {
        'email': user.email,
        'domain': domain,
        'path': result.path,
        'site_name': site_name,
        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
        'username': user.username,
        'encoded_username': urlsafe_base64_encode(user.username),
        'token': token_generator.make_token(user),
        'protocol': result.scheme if result.scheme != '' else 'http',
    }
    subject = loader.render_to_string(subject_template_name, c)
    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())
    email = loader.render_to_string(email_template_name, c)

    return subject, email 
Example #9
Source File: forms.py    From esdc-ce with Apache License 2.0 6 votes vote down vote up
def save(self, domain_override=None,
             subject_template_name='registration/password_reset_subject.txt',
             email_template_name='registration/password_reset_email.html',
             use_https=False, token_generator=default_token_generator,
             **kwargs):
        # Complete override, because we have to use our sendmail()
        for user in self.users_cache:
            # Update verification token
            profile = user.userprofile
            profile.email_token = token_generator.make_token(user)
            profile.save()
            sendmail(user, subject_template_name, email_template_name, extra_context={
                'user': user,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': profile.email_token,
                'protocol': use_https and 'https' or 'http',
            }) 
Example #10
Source File: tests.py    From jorvik with GNU General Public License v3.0 6 votes vote down vote up
def test_recupero_password_link_valido(self):
        presidente = crea_persona()
        persona, sede, app = crea_persona_sede_appartenenza(presidente=presidente)
        persona_in_sede = crea_persona()
        utenza_persona_in_sede = crea_utenza(persona_in_sede)
        appartenenza_persona_in_sede = crea_appartenenza(persona, sede)
        uid = urlsafe_base64_encode(force_bytes(utenza_persona_in_sede.pk))
        reset_pw_link = default_token_generator.make_token(utenza_persona_in_sede)
        sessione = self.sessione_anonimo()
        sessione.visit("%s%s" % (self.live_server_url, reverse('recupera_password_conferma',  kwargs={ 'uidb64': uid, 'token': reset_pw_link})))
        sessione.fill('new_password1', 'new_password')
        sessione.fill('new_password2', 'new_password')
        sessione.find_by_css('.btn.btn-block.btn-primary').first.click()
        self.assertTrue(sessione.is_text_present('La tua nuova password รจ stata impostata'))
        sessione.visit("%s%s" % (self.live_server_url, '/login/'))
        sessione.fill('auth-username', utenza_persona_in_sede.email)
        sessione.fill('auth-password', 'new_password')
        sessione.find_by_css('.btn.btn-block.btn-primary').first.click()
        testo_personalizzato = 'Ciao, {0}'.format(persona_in_sede.nome)
        self.assertTrue(sessione.is_text_present(testo_personalizzato)) 
Example #11
Source File: test_api.py    From django-rest-auth with MIT License 5 votes vote down vote up
def _generate_uid_and_token(self, user):
        result = {}
        from django.utils.encoding import force_bytes
        from django.contrib.auth.tokens import default_token_generator
        from django.utils.http import urlsafe_base64_encode

        result['uid'] = urlsafe_base64_encode(force_bytes(user.pk))
        result['token'] = default_token_generator.make_token(user)
        return result 
Example #12
Source File: tokens.py    From registration with MIT License 5 votes vote down vote up
def generate_verify_email(user):
    token = account_activation_token.make_token(user)
    uuid = urlsafe_base64_encode(force_bytes(user.pk))
    activate_url = 'http://' + settings.HACKATHON_DOMAIN + \
                   reverse('activate', kwargs={'uid': uuid, 'token': token})
    return create_verify_email(user, activate_url) 
Example #13
Source File: tokens.py    From registration with MIT License 5 votes vote down vote up
def generate_pw_reset_email(user, request):
    token = password_reset_token.make_token(user)
    uuid = urlsafe_base64_encode(force_bytes(user.pk))
    reset_url = r_reverse('password_reset_confirm', kwargs={'uid': uuid, 'token': token}, request=request)
    return create_password_reset_email(user, reset_url) 
Example #14
Source File: views.py    From doccano with MIT License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)

        # here we make sure that a post request won't trigger a subscription in case allow_signup is False
        if not bool(settings.ALLOW_SIGNUP):
            return redirect('signup')

        if not hasattr(settings, "EMAIL_BACKEND") and not hasattr(settings, "EMAIL_HOST"):
            return render(request, 'email_not_set.html')

        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            mail_subject = 'Activate your account.'
            message = render_to_string('acc_active_email.html', {
                'user': user,
                'domain': current_site.domain,
                'scheme': request.scheme,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
                'token': account_activation_token.make_token(user),
            })
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(
                mail_subject, message, to=[to_email]
            )
            email.send()
            return render(request, 'validate_mail_address_complete.html')
        else:
            return render(request, self.template_name, {'form': form, 'allow_signup': bool(settings.ALLOW_SIGNUP)}) 
Example #15
Source File: test_activate.py    From doccano with MIT License 5 votes vote down vote up
def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()

        request_POST = {'username': 'username5648',
                        'email': 'email@example.com',
                        'password1': 'pwd0000Y00$$',
                        'password2': 'pwd0000Y00$$'}
        user = SignupForm(request_POST).save(commit=False)
        user.save()
        self.token = account_activation_token.make_token(user)
        self.uid = urlsafe_base64_encode(force_bytes(user.pk)).decode() 
Example #16
Source File: utils.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_activation_email(user, site=None):
    """
    Send the activation email. The activation key is the username,
    signed using TimestampSigner.
    """
    token_generator = PasswordResetTokenGenerator()
    token = token_generator.make_token(user)

    uid = urlsafe_base64_encode(force_bytes(user.pk))

    activation_path = reverse('users:activate', kwargs={'uidb64': uid, 'token': token})

    context = {
        'user': user,
        'name': user.get_full_name(),
        'username': user.get_username(),
        'activation_path': activation_path,
        'timeout_days': settings.PASSWORD_RESET_TIMEOUT_DAYS,
        'org_long_name': settings.ORG_LONG_NAME,
    }

    if site:
        context.update(site=site)

    subject = 'Account details for {username} at {org_long_name}'.format(**context)
    # Force subject to a single line to avoid header-injection issues.
    subject = ''.join(subject.splitlines())
    message = render_to_string('users/activation/email.txt', context)
    user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL) 
Example #17
Source File: test_views.py    From django-user-management with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_options(self):
        user = UserFactory.create()
        token = default_token_generator.make_token(user)
        uid = urlsafe_base64_encode(force_bytes(user.pk))

        request = self.create_request('options', auth=False)
        view = self.view_class.as_view()
        response = view(request, uidb64=uid, token=token)
        self.assertEqual(response.status_code, status.HTTP_200_OK) 
Example #18
Source File: view_partials.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def student_confirmation_url(self):
        uidb64 = urlsafe_base64_encode(force_bytes(self.request.user.pk)).decode(
            "utf-8"
        )
        token = self.token_generator.make_token(self.request.user)
        return reverse(
            self.request.resolver_match.view_name,
            kwargs={"uuid": self.report.uuid, "uidb64": uidb64, "token": token},
        ) 
Example #19
Source File: api.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_account_activation_email(self, user, email):
        # TODO: mirror send_password_reset_email
        self.send_with_kwargs(
            email_template_name="callisto_core/accounts/account_activation_email.html",
            to_addresses=[email],
            site_id=user.account.site_id,
            user=user,
            uid=urlsafe_base64_encode(force_bytes(user.pk)),
            token=default_token_generator.make_token(copy.copy(user)),
            email_subject="Keep Our Community Safe with Callisto",
            email_name="account_activation_email",
        ) 
Example #20
Source File: test_views.py    From django-user-management with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_put_invalid_user(self):
        # There should never be a user with pk 0
        invalid_uid = urlsafe_base64_encode(b'0')

        request = self.create_request('put', auth=False)
        view = self.view_class.as_view()
        response = view(request, uidb64=invalid_uid)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) 
Example #21
Source File: test_views.py    From django-user-management with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_put_invalid_token(self):
        user = UserFactory.create()
        other_user = UserFactory.create()
        token = default_token_generator.make_token(other_user)
        uid = urlsafe_base64_encode(force_bytes(user.pk))

        request = self.create_request('put', auth=False)
        view = self.view_class.as_view()
        response = view(request, uidb64=uid, token=token)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) 
Example #22
Source File: mixins.py    From django-user-management with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def generate_uid(self):
        """Generate user uid for password reset."""
        return urlsafe_base64_encode(force_bytes(self.pk)) 
Example #23
Source File: test_views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_confirm_invalid_uuid(self):
        """A uidb64 that decodes to a non-UUID doesn't crash."""
        _, path = self._test_confirm_start()
        invalid_uidb64 = urlsafe_base64_encode('INVALID_UUID'.encode()).decode()
        first, _uuidb64_, second = path.strip('/').split('/')
        response = self.client.get('/' + '/'.join((first, invalid_uidb64, second)) + '/')
        self.assertContains(response, 'The password reset link was invalid') 
Example #24
Source File: test_templates.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_PasswordResetConfirmView_valid_token(self):
        # PasswordResetConfirmView valid token
        client = PasswordResetConfirmClient()
        default_token_generator = PasswordResetTokenGenerator()
        token = default_token_generator.make_token(self.user)
        uidb64 = urlsafe_base64_encode(str(self.user.pk).encode()).decode()
        url = reverse('password_reset_confirm', kwargs={'uidb64': uidb64, 'token': token})
        response = client.get(url)
        self.assertContains(response, '<title>Enter new password</title>')
        self.assertContains(response, '<h1>Enter new password</h1>') 
Example #25
Source File: test_views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_confirm_invalid_uuid(self):
        """A uidb64 that decodes to a non-UUID doesn't crash."""
        _, path = self._test_confirm_start()
        invalid_uidb64 = urlsafe_base64_encode('INVALID_UUID'.encode())
        first, _uuidb64_, second = path.strip('/').split('/')
        response = self.client.get('/' + '/'.join((first, invalid_uidb64, second)) + '/')
        self.assertContains(response, 'The password reset link was invalid') 
Example #26
Source File: test_templates.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_PasswordResetConfirmView_valid_token(self):
        # PasswordResetConfirmView valid token
        client = PasswordResetConfirmClient()
        default_token_generator = PasswordResetTokenGenerator()
        token = default_token_generator.make_token(self.user)
        uidb64 = urlsafe_base64_encode(str(self.user.pk).encode())
        url = reverse('password_reset_confirm', kwargs={'uidb64': uidb64, 'token': token})
        response = client.get(url)
        self.assertContains(response, '<title>Enter new password</title>')
        self.assertContains(response, '<h1>Enter new password</h1>') 
Example #27
Source File: test_view_password_reset.py    From django-beginners-guide with MIT License 5 votes vote down vote up
def setUp(self):
        user = User.objects.create_user(username='john', email='john@doe.com', password='123abcdef')

        '''
        create a valid password reset token
        based on how django creates the token internally:
        https://github.com/django/django/blob/1.11.5/django/contrib/auth/forms.py#L280
        '''
        self.uid = urlsafe_base64_encode(force_bytes(user.pk)).decode()
        self.token = default_token_generator.make_token(user)

        url = reverse('password_reset_confirm', kwargs={'uidb64': self.uid, 'token': self.token})
        self.response = self.client.get(url, follow=True) 
Example #28
Source File: test_view_password_reset.py    From django-beginners-guide with MIT License 5 votes vote down vote up
def setUp(self):
        user = User.objects.create_user(username='john', email='john@doe.com', password='123abcdef')
        uid = urlsafe_base64_encode(force_bytes(user.pk)).decode()
        token = default_token_generator.make_token(user)

        '''
        invalidate the token by changing the password
        '''
        user.set_password('abcdef123')
        user.save()

        url = reverse('password_reset_confirm', kwargs={'uidb64': uid, 'token': token})
        self.response = self.client.get(url) 
Example #29
Source File: register_view.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def _notify_user(request, user, profile):
        """
        Function that notifies user that he has been registered in the system.

        Can be overloaded to send different text in the email, or use different method of notification.
        """
        sendmail(user, 'gui/accounts/register_subject.txt', 'gui/accounts/register_email.txt', extra_context={
            'user': user,
            'profile': profile,
            'token': profile.email_token,
            'uid': urlsafe_base64_encode(str(user.id)),
        }, dc=request.dc)

    # noinspection PyUnusedLocal 
Example #30
Source File: utils.py    From django-uniauth with GNU Lesser General Public License v3.0 5 votes vote down vote up
def encode_pk(pk):
    """
    Returns the base64 encoding of the provided pk
    """
    encoded = urlsafe_base64_encode(force_bytes(pk))
    # On Django <2.1, this method returns a byte string
    try:
        encoded = encoded.decode()
    except AttributeError:
        pass
    return encoded