Python django.contrib.auth.tokens.default_token_generator.make_token() Examples
The following are 30
code examples of django.contrib.auth.tokens.default_token_generator.make_token().
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.contrib.auth.tokens.default_token_generator
, or try the search function
.
Example #1
Source File: views.py From openwisp-radius with GNU General Public License v3.0 | 6 votes |
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_activation.py From djoser with MIT License | 6 votes |
def test_post_sent_confirmation_email(self): user = create_user() user.is_active = False user.save() djoser.signals.user_activated.connect(self.signal_receiver) data = { "uid": djoser.utils.encode_uid(user.pk), "token": default_token_generator.make_token(user), } response = self.client.post(self.base_url, data) self.assert_status_equal(response, status.HTTP_204_NO_CONTENT) self.assert_emails_in_mailbox(1) self.assert_email_exists(to=[user.email]) self.assertTrue(self.signal_sent)
Example #3
Source File: test_activation.py From djoser with MIT License | 6 votes |
def test_post_respond_with_bad_request_when_stale_token(self): user = create_user() djoser.signals.user_activated.connect(self.signal_receiver) data = { "uid": djoser.utils.encode_uid(user.pk), "token": default_token_generator.make_token(user), } response = self.client.post(self.base_url, data) self.assert_status_equal(response, status.HTTP_403_FORBIDDEN) self.assertEqual(list(response.data.keys()), ["detail"]) self.assertEqual( response.data["detail"], default_settings.CONSTANTS.messages.STALE_TOKEN_ERROR, ) self.assertFalse(self.signal_sent)
Example #4
Source File: test_connect_viewset.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
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 #5
Source File: test_reset_username_confirm.py From djoser with MIT License | 6 votes |
def test_post_not_set_new_username_if_username_mismatch(self): user = create_user() data = { "uid": djoser.utils.encode_uid(user.pk), "token": default_token_generator.make_token(user), "new_username": "new_username", "re_new_username": "wrong", } response = self.client.post(self.base_url, data) self.assert_status_equal(response, status.HTTP_400_BAD_REQUEST) self.assertEqual( response.data["non_field_errors"], [ default_settings.CONSTANTS.messages.USERNAME_MISMATCH_ERROR.format( User.USERNAME_FIELD ) ], # noqa )
Example #6
Source File: test_reset_username_confirm.py From djoser with MIT License | 6 votes |
def test_post_readable_error_message_when_uid_is_broken(self): user = create_user() data = { "uid": b"\xd3\x10\xb4", "token": default_token_generator.make_token(user), "new_username": "new_username", } response = self.client.post(self.base_url, data) self.assert_status_equal(response, status.HTTP_400_BAD_REQUEST) self.assertIn("uid", response.data) self.assertEqual(len(response.data["uid"]), 1) self.assertEqual( response.data["uid"][0], default_settings.CONSTANTS.messages.INVALID_UID_ERROR, )
Example #7
Source File: test_password_reset_confirm.py From djoser with MIT License | 6 votes |
def test_post_not_set_new_password_if_password_mismatch(self): user = create_user() data = { "uid": djoser.utils.encode_uid(user.pk), "token": default_token_generator.make_token(user), "new_password": "new password", "re_new_password": "wrong", } response = self.client.post(self.base_url, data) self.assert_status_equal(response, status.HTTP_400_BAD_REQUEST) self.assertEqual( response.data["non_field_errors"], [default_settings.CONSTANTS.messages.PASSWORD_MISMATCH_ERROR], )
Example #8
Source File: test_password_reset_confirm.py From djoser with MIT License | 6 votes |
def test_post_readable_error_message_when_uid_is_broken(self): """ Regression test for https://github.com/sunscrapers/djoser/issues/122 When uid was not correct unicode string, error message was a standard Python error messsage. Now we provide human readable message. """ user = create_user() data = { "uid": b"\xd3\x10\xb4", "token": default_token_generator.make_token(user), "new_password": "new password", } response = self.client.post(self.base_url, data) self.assert_status_equal(response, status.HTTP_400_BAD_REQUEST) self.assertIn("uid", response.data) self.assertEqual(len(response.data["uid"]), 1) self.assertEqual( response.data["uid"][0], default_settings.CONSTANTS.messages.INVALID_UID_ERROR, )
Example #9
Source File: test_views.py From django-user-management with BSD 2-Clause "Simplified" License | 6 votes |
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 #10
Source File: test_views.py From django-user-management with BSD 2-Clause "Simplified" License | 6 votes |
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 #11
Source File: api.py From volontulo with MIT License | 6 votes |
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 #12
Source File: tests.py From jorvik with GNU General Public License v3.0 | 6 votes |
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 #13
Source File: test_reset_password_flow.py From pycon with MIT License | 6 votes |
def test_request_reset_password_email_for_a_existing_user(user_factory, graphql_client): user = user_factory() response = _request_password_reset(graphql_client, user.email) assert response["data"]["requestPasswordReset"]["__typename"] == "OperationResult" assert response["data"]["requestPasswordReset"]["ok"] is True assert len(mail.outbox) == 1 email = mail.outbox[0] html_body = email.alternatives[0][0] token = default_token_generator.make_token(user) userid = urlsafe_b64encode(bytes(str(user.id), "utf-8")).decode("utf-8") assert email.to == [user.email] assert f"http://test.it/en/reset-password/{userid}/{token}" in email.body assert f"http://test.it/en/reset-password/{userid}/{token}" in html_body
Example #14
Source File: test_reset_password_flow.py From pycon with MIT License | 6 votes |
def test_cannot_reuse_same_reset_password_token_multiple_times( user_factory, graphql_client ): user = user_factory(password="old") token = default_token_generator.make_token(user) assert user.check_password("old") response = _reset_password(graphql_client, token, user.id, "new") assert response["data"]["resetPassword"]["__typename"] == "OperationResult" assert response["data"]["resetPassword"]["ok"] is True user.refresh_from_db() assert user.check_password("new") response = _reset_password(graphql_client, token, user.id, "another") assert ( response["data"]["resetPassword"]["__typename"] == "ResetPasswordMutationErrors" ) assert response["data"]["resetPassword"]["token"] == ["Invalid token"]
Example #15
Source File: test_reset_username_confirm.py From djoser with MIT License | 5 votes |
def test_post_not_set_new_username_if_mismatch(self): user = create_user() data = { "uid": djoser.utils.encode_uid(user.pk), "token": default_token_generator.make_token(user), "new_username": "new_username", "re_new_username": "wrong", } response = self.client.post(self.base_url, data) self.assert_status_equal(response, status.HTTP_400_BAD_REQUEST) user.refresh_from_db() self.assertNotEqual(user.username, data["new_username"])
Example #16
Source File: test_views.py From django-user-management with BSD 2-Clause "Simplified" License | 5 votes |
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 #17
Source File: email.py From djoser with MIT License | 5 votes |
def get_context_data(self): # ActivationEmail can be deleted context = super().get_context_data() user = context.get("user") context["uid"] = utils.encode_uid(user.pk) context["token"] = default_token_generator.make_token(user) context["url"] = settings.ACTIVATION_URL.format(**context) return context
Example #18
Source File: email.py From djoser with MIT License | 5 votes |
def get_context_data(self): # PasswordResetEmail can be deleted context = super().get_context_data() user = context.get("user") context["uid"] = utils.encode_uid(user.pk) context["token"] = default_token_generator.make_token(user) context["url"] = settings.PASSWORD_RESET_CONFIRM_URL.format(**context) return context
Example #19
Source File: email.py From djoser with MIT License | 5 votes |
def get_context_data(self): context = super().get_context_data() user = context.get("user") context["uid"] = utils.encode_uid(user.pk) context["token"] = default_token_generator.make_token(user) context["url"] = settings.USERNAME_RESET_CONFIRM_URL.format(**context) return context
Example #20
Source File: test_view_password_reset.py From django-beginners-guide with MIT License | 5 votes |
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 #21
Source File: schema.py From django-graph-auth with MIT License | 5 votes |
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 #22
Source File: test_account_creation.py From callisto-core with GNU Affero General Public License v3.0 | 5 votes |
def test_can_activate_account(self): BulkAccount.objects.create(emails="tech@projectcallisto.org", site_id=2) account = Account.objects.get(school_email="tech@projectcallisto.org") uid = urlsafe_base64_encode(force_bytes(account.user.pk)) token = default_token_generator.make_token(account.user) response = self.client.get( reverse("activate_account", kwargs={"uidb64": uid, "token": token}), follow=True, ) self.assertNotIn("invalid_token", response.context) self.assertTemplateUsed( response, "callisto_core/accounts/account_activation_confirm.html" )
Example #23
Source File: api.py From callisto-core with GNU Affero General Public License v3.0 | 5 votes |
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 #24
Source File: test_api.py From django-rest-auth with MIT License | 5 votes |
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 #25
Source File: test_view_password_reset.py From django-beginners-guide with MIT License | 5 votes |
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 #26
Source File: test_views.py From django-user-management with BSD 2-Clause "Simplified" License | 5 votes |
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 #27
Source File: test_views.py From django-user-management with BSD 2-Clause "Simplified" License | 5 votes |
def test_full_stack_wrong_url(self): user = UserFactory.create() token = default_token_generator.make_token(user) uid = urlsafe_base64_encode(b'0') # Invalid uid, therefore bad url view_name = 'user_management_api:password_reset_confirm' url = reverse(view_name, kwargs={'uidb64': uid, 'token': token}) response = self.client.put(url) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertTrue(hasattr(response, 'accepted_renderer'))
Example #28
Source File: test_activation.py From djoser with MIT License | 5 votes |
def test_post_activate_user_and_not_login(self): user = create_user() user.is_active = False user.save() data = { "uid": djoser.utils.encode_uid(user.pk), "token": default_token_generator.make_token(user), } response = self.client.post(self.base_url, data) user.refresh_from_db() self.assert_status_equal(response, status.HTTP_204_NO_CONTENT) self.assertTrue(user.is_active)
Example #29
Source File: test_reset_username_confirm.py From djoser with MIT License | 5 votes |
def test_post_username_changed_confirmation_email(self): user = create_user() data = { "uid": djoser.utils.encode_uid(user.pk), "token": default_token_generator.make_token(user), "new_username": "new_username", } response = self.client.post(self.base_url, data) self.assert_status_equal(response, status.HTTP_204_NO_CONTENT) user.refresh_from_db() self.assertEqual(user.username, data["new_username"]) self.assert_emails_in_mailbox(1) self.assert_email_exists(to=[user.email])
Example #30
Source File: test_reset_username_confirm.py From djoser with MIT License | 5 votes |
def test_post_not_reset_if_fails_username_validation(self): user = create_user() data = { "uid": djoser.utils.encode_uid(user.pk), "token": default_token_generator.make_token(user), "new_username": "new username", "re_new_username": "new_username", } response = self.client.post(self.base_url, data) self.assert_status_equal(response, status.HTTP_400_BAD_REQUEST) user.refresh_from_db() self.assertNotEqual(user.username, data["new_username"])