Python django.utils.http.urlsafe_base64_encode() Examples

The following are 30 code examples for showing how to use django.utils.http.urlsafe_base64_encode(). 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.http , or try the search function .

Example 1
Project: kobo-predict   Author: awemulya   File: password_reset_serializer.py    License: 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 2
Project: kobo-predict   Author: awemulya   File: test_connect_viewset.py    License: 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 3
Project: volontulo   Author: CodeForPoznan   File: api.py    License: 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 4
Project: AutoGrader   Author: bilalzaib   File: views.py    License: 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 5
Project: django-user-management   Author: incuna   File: test_views.py    License: 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 6
Project: django-user-management   Author: incuna   File: test_views.py    License: 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 7
Project: esdc-ce   Author: erigones   File: forms.py    License: 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 8
Project: jorvik   Author: CroceRossaItaliana   File: tests.py    License: 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 9
Project: openwisp-radius   Author: openwisp   File: views.py    License: 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 10
Project: donation-tracker   Author: GamesDoneQuick   File: auth.py    License: Apache License 2.0 5 votes vote down vote up
def send_registration_mail(
    request,
    user,
    template=None,
    sender=None,
    token_generator=default_token_generator,
    extra_context=None,
):
    template = template or mailutil.get_email_template(
        default_registration_template_name(), default_registration_template()
    )
    return send_auth_token_mail(
        user,
        request.get_host(),
        request.build_absolute_uri(
            reverse(
                'tracker:confirm_registration',
                kwargs={
                    'uidb64': urlsafe_base64_encode(force_bytes(user.pk)),
                    'token': token_generator.make_token(user),
                },
            )
        ),
        template,
        sender,
        extra_context,
    ) 
Example 11
Project: donation-tracker   Author: GamesDoneQuick   File: test_auth.py    License: Apache License 2.0 5 votes vote down vote up
def test_registration_flow(self):
        request = self.factory.post(reverse('tracker:register'))
        new_user = AuthUser.objects.create(
            username='dummyuser', email='test@email.com', is_active=False
        )
        sent_mail = tracker.auth.send_registration_mail(
            request, new_user, template=TEST_AUTH_MAIL_TEMPLATE
        )
        contents = test_util.parse_test_mail(sent_mail)
        self.assertEqual(new_user.username, contents['user'][0])
        parsed = urllib.parse.urlparse(contents['url'][0])
        resp = self.client.get(parsed.path)
        expected_url = reverse(
            'tracker:confirm_registration',
            kwargs={
                'uidb64': urlsafe_base64_encode(force_bytes(new_user.pk)),
                'token': 'register-user',
            },
        )
        self.assertRedirects(resp, expected_url)
        resp = self.client.get(expected_url)
        self.assertContains(resp, 'Please set your username and password.')
        resp = self.client.post(
            expected_url,
            {
                'username': 'dummyuser',
                'password': 'foobar',
                'passwordconfirm': 'foobar',
            },
        )
        self.assertContains(resp, 'Your user account has been confirmed')
        new_user.refresh_from_db()
        self.assertTrue(new_user.is_active)
        self.assertTrue(new_user.check_password('foobar')) 
Example 12
Project: django-herald   Author: worthwhile   File: notifications.py    License: MIT License 5 votes vote down vote up
def get_context_data(self):
        context = super(PasswordResetEmail, self).get_context_data()

        if not self.site_name or self.domain:
            current_site = Site.objects.get_current()
            self.site_name = current_site.name
            self.domain = current_site.domain

        protocol = 'https' if self.use_https else 'http'
        uid = force_text(urlsafe_base64_encode(force_bytes(self.user.pk)))
        token = self.token_generator.make_token(self.user)

        context.update({
            'full_reset_url': '{}://{}{}'.format(
                protocol,
                self.domain,
                reverse('password_reset_confirm', kwargs={'uidb64': uid, 'token': token})
            ),
            'email': self.user.email,
            'domain': self.domain,
            'site_name': self.site_name,
            'uid': uid,
            'user': self.user,
            'token': token,
            'protocol': protocol,
            'template_name': self.email_template_name,
            'html_template_name': self.html_email_template_name,
        })

        if self.extra_email_context is not None:
            context.update(self.extra_email_context)

        return context 
Example 13
Project: GTDWeb   Author: lanbing510   File: forms.py    License: GNU General Public License v2.0 5 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,
             from_email=None, request=None, html_email_template_name=None):
        """
        Generates a one-use only link for resetting password and sends to the
        user.
        """
        email = self.cleaned_data["email"]
        for user in self.get_users(email):
            if not domain_override:
                current_site = get_current_site(request)
                site_name = current_site.name
                domain = current_site.domain
            else:
                site_name = domain = domain_override
            context = {
                'email': user.email,
                'domain': domain,
                'site_name': site_name,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'user': user,
                'token': token_generator.make_token(user),
                'protocol': 'https' if use_https else 'http',
            }

            self.send_mail(subject_template_name, email_template_name,
                           context, from_email, user.email,
                           html_email_template_name=html_email_template_name) 
Example 14
def test_get_password_reset_email(self):
        """Test base64 username is included in reset email."""
        subject, email = get_password_reset_email(self.user, 'https://ona.io')

        self.assertIn(urlsafe_base64_encode(self.user.username), email,
                      "Username is included in reset email.") 
Example 15
Project: kobo-predict   Author: awemulya   File: models.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_absolute_url(self):
        invite_idb64 = urlsafe_base64_encode(force_bytes(self.pk))
        kwargs = {'invite_idb64': invite_idb64, 'token': self.token}
        return reverse('fieldsight:activate-role', kwargs=kwargs) 
Example 16
Project: bioforum   Author: reBiocoder   File: forms.py    License: MIT License 5 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,
             from_email=None, request=None, html_email_template_name=None,
             extra_email_context=None):
        """
        Generate a one-use only link for resetting password and send it to the
        user.
        """
        email = self.cleaned_data["email"]
        for user in self.get_users(email):
            if not domain_override:
                current_site = get_current_site(request)
                site_name = current_site.name
                domain = current_site.domain
            else:
                site_name = domain = domain_override
            context = {
                'email': email,
                'domain': domain,
                'site_name': site_name,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
                'user': user,
                'token': token_generator.make_token(user),
                'protocol': 'https' if use_https else 'http',
            }
            if extra_email_context is not None:
                context.update(extra_email_context)
            self.send_mail(
                subject_template_name, email_template_name, context, from_email,
                email, html_email_template_name=html_email_template_name,
            ) 
Example 17
Project: django-users2   Author: mishbahr   File: compat.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def urlsafe_base64_encode(s):
        """
        Encodes a bytestring in base64 for use in URLs, stripping any trailing
        equal signs.
        """
        return base64.urlsafe_b64encode(s).rstrip(b'\n=') 
Example 18
Project: zulip   Author: zulip   File: forms.py    License: Apache License 2.0 5 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 19
def form_valid(self, form):
        user = form.user_cache
        token = default_token_generator.make_token(user)
        uid = urlsafe_base64_encode(force_bytes(user.pk))

        if isinstance(uid, bytes):
            uid = uid.decode()

        send_reset_password_email(self.request, user.email, token, uid)

        return redirect('accounts:restore_password_done') 
Example 20
Project: Collaboration-System   Author: fresearchgroup   File: views.py    License: GNU General Public License v2.0 5 votes vote down vote up
def send_mail(request, user, to_email):
    current_site = get_current_site(request)
    mail_subject = 'Please activate your account.'
    message = render_to_string('activate_email.html', {
    'user': user,
    'domain': current_site.domain,
    'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(),
    'token':account_activation_token.make_token(user),
    })
    #print(mail_subject, message, to_email)
    email = EmailMessage(mail_subject, message, to=[to_email])
    email.send(fail_silently=True) 
Example 21
Project: djoser   Author: sunscrapers   File: utils.py    License: MIT License 5 votes vote down vote up
def encode_uid(pk):
    return force_text(urlsafe_base64_encode(force_bytes(pk))) 
Example 22
Project: AutoGrader   Author: bilalzaib   File: views.py    License: MIT License 5 votes vote down vote up
def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()

            student = Student.objects.create(user=user)
            student.save()

            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)

            """
            try:
                user.email_user(subject, message)
                return redirect('account_activation_sent')
            except Exception:
                form.add_error(None, "Email sending failed, try again later.")
                user.delete()
            """


            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            login(request, user)
            request.session['username'] = user.username
            return redirect('home')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form}) 
Example 23
Project: AutoGrader   Author: bilalzaib   File: views.py    License: MIT License 5 votes vote down vote up
def change_email(request):
    email = request.POST.get("email")

    form = ChangeEmailForm(request.POST)
    if form.is_valid():
        user = request.user
        user.email = form.cleaned_data.get('email')
        user.save()

        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, 'Email updated and verification email sent.')
    else:
        for field in form:
            for error in field.errors:
                messages.warning(request, field.label + ": " + error)

    return HttpResponseRedirect(request.META.get('HTTP_REFERER')) 
Example 24
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: forms.py    License: MIT License 5 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,
             from_email=None, request=None, html_email_template_name=None,
             extra_email_context=None):
        """
        Generate a one-use only link for resetting password and send it to the
        user.
        """
        email = self.cleaned_data["email"]
        for user in self.get_users(email):
            if not domain_override:
                current_site = get_current_site(request)
                site_name = current_site.name
                domain = current_site.domain
            else:
                site_name = domain = domain_override
            context = {
                'email': email,
                'domain': domain,
                'site_name': site_name,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
                'user': user,
                'token': token_generator.make_token(user),
                'protocol': 'https' if use_https else 'http',
                **(extra_email_context or {}),
            }
            self.send_mail(
                subject_template_name, email_template_name, context, from_email,
                email, html_email_template_name=html_email_template_name,
            ) 
Example 25
Project: wagtail   Author: wagtail   File: test_account_management.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup_password_reset_confirm_tests(self):
        from django.utils.encoding import force_bytes, force_str
        from django.utils.http import urlsafe_base64_encode

        # Get user
        self.user = get_user_model().objects.get(username='test')

        # Generate a password reset token
        self.password_reset_token = PasswordResetTokenGenerator().make_token(self.user)

        # Generate a password reset uid
        self.password_reset_uid = force_str(urlsafe_base64_encode(force_bytes(self.user.pk)))

        # Create url_args
        if DJANGO_VERSION >= (3, 0):
            token = auth_views.PasswordResetConfirmView.reset_url_token
        else:
            token = auth_views.INTERNAL_RESET_URL_TOKEN

        self.url_kwargs = dict(uidb64=self.password_reset_uid, token=token)

        # Add token to session object
        s = self.client.session
        s.update({
            auth_views.INTERNAL_RESET_SESSION_TOKEN: self.password_reset_token,
        })
        s.save() 
Example 26
Project: django-graph-auth   Author: morgante   File: schema.py    License: MIT License 5 votes vote down vote up
def mutate_and_get_payload(cls, input, context, info):
        if graph_auth_settings.CUSTOM_PASSWORD_RESET_TEMPLATE is not None and graph_auth_settings.EMAIL_FROM is not None and graph_auth_settings.PASSWORD_RESET_URL_TEMPLATE is not None:

            from mail_templated import EmailMessage

            for user in UserModel.objects.filter(email=input.get('email')):
                uid = urlsafe_base64_encode(force_bytes(user.pk)).decode()
                token = token_generator.make_token(user)
                link = graph_auth_settings.PASSWORD_RESET_URL_TEMPLATE.format(token=token, uid=uid)
                input_data = {
                    "email": user.email, 
                    "first_name": user.first_name, 
                    "last_name": user.last_name, 
                    "link": link
                    }
                message = EmailMessage(graph_auth_settings.CUSTOM_PASSWORD_RESET_TEMPLATE, input_data, graph_auth_settings.EMAIL_FROM, [user.email])
                message.send()

        else:
            data = {
                'email': input.get('email'),
            }

            reset_form = PasswordResetForm(data=data)

            if not reset_form.is_valid():
                raise Exception("The email is not valid")

            options = {
                'use_https': context.is_secure(),
                'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
                'request': context
            }

            reset_form.save(**options)

        return ResetPasswordRequest(ok=True) 
Example 27
Project: openhgsenti   Author: drexly   File: forms.py    License: Apache License 2.0 5 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,
             from_email=None, request=None, html_email_template_name=None,
             extra_email_context=None):
        """
        Generates a one-use only link for resetting password and sends to the
        user.
        """
        email = self.cleaned_data["email"]
        for user in self.get_users(email):
            if not domain_override:
                current_site = get_current_site(request)
                site_name = current_site.name
                domain = current_site.domain
            else:
                site_name = domain = domain_override
            context = {
                'email': user.email,
                'domain': domain,
                'site_name': site_name,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'user': user,
                'token': token_generator.make_token(user),
                'protocol': 'https' if use_https else 'http',
            }
            if extra_email_context is not None:
                context.update(extra_email_context)
            self.send_mail(subject_template_name, email_template_name,
                           context, from_email, user.email,
                           html_email_template_name=html_email_template_name) 
Example 28
Project: cruzz   Author: Monal5031   File: views.py    License: MIT License 5 votes vote down vote up
def post(self, request):
        user = request.data.get('user', {})

        # The create serializer, validate serializer, save serializer pattern
        # below is common.
        serializer = self.serializer_class(data=user)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        user = User.objects.get(email=serializer.data['email'])

        current_site = get_current_site(request)
        print(current_site)
        mail_subject = 'Activate your Vconnect account.'
        message = render_to_string('acc_active_email.html', {
            'user': user,
            'domain': current_site,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
            'token': account_activation_token.make_token(user),
        })
        print(message)
        to_email = serializer.data['email']
        email = EmailMessage(
            mail_subject, message, to=[to_email]
        )
        print(email, to_email)

        email.send()

        serializer.data['is_active'] = False
        return Response(serializer.data, status=status.HTTP_201_CREATED) 
Example 29
Project: python2017   Author: bpgc-cte   File: forms.py    License: MIT License 5 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,
             from_email=None, request=None, html_email_template_name=None,
             extra_email_context=None):
        """
        Generates a one-use only link for resetting password and sends to the
        user.
        """
        email = self.cleaned_data["email"]
        for user in self.get_users(email):
            if not domain_override:
                current_site = get_current_site(request)
                site_name = current_site.name
                domain = current_site.domain
            else:
                site_name = domain = domain_override
            context = {
                'email': email,
                'domain': domain,
                'site_name': site_name,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'user': user,
                'token': token_generator.make_token(user),
                'protocol': 'https' if use_https else 'http',
            }
            if extra_email_context is not None:
                context.update(extra_email_context)
            self.send_mail(
                subject_template_name, email_template_name, context, from_email,
                email, html_email_template_name=html_email_template_name,
            ) 
Example 30
Project: Ouroboros   Author: tamuhack-org   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def send_confirmation_email(curr_domain: RequestSite, user: User) -> None:
    subject = "Confirm your email address!"
    template_name = "registration/emails/activate.html"
    context = {
        "user": user,
        "domain": curr_domain,
        "uid": urlsafe_base64_encode(force_bytes(user.pk)),
        "token": email_confirmation_generator.make_token(user),
        "event_name": settings.EVENT_NAME,
    }
    user.send_html_email(template_name, context, subject)


# Create your views here.