コード例 #1
0
def redirect_to_password_login(email, remember_me):
    """Helper function to redirect user to password login page.

    Return an HttpResponse.
    """
    token = make_timed_token(email, 1, remember_me)
    return redirect(
        reverse('authentication:password_login', kwargs={'token': token}))
コード例 #2
0
    def test_mail_with_valid_token(self):
        # create user and get pk
        User.objects.create_user(username="******",
                                 email="*****@*****.**")
        user = User.objects.get(username="******")

        # Create token with user.pk
        token = make_timed_token(user.pk, 20)
        # Test redirection to index
        index_response = self.client.get("/auth/activate/True/" + token)
        self.assertEqual(index_response.url, "/")
コード例 #3
0
ファイル: tests_auth.py プロジェクト: transport-nantes/tn_web
    def setUp(self):
        # Create a token for password login.
        EMAIL = "*****@*****.**"
        EXPIRY_MINUTES = 2
        NOW = datetime.datetime.now().timestamp()
        self.token = make_timed_token(EMAIL, EXPIRY_MINUTES, 0, NOW)

        self.pass_user = User.objects.create_user(username='******',
                                                  password='******',
                                                  email="*****@*****.**")
        self.pass_user.profile.authenticates_by_mail = False
        self.pass_user.save()
コード例 #4
0
    def test_mail_with_invalid_token(self):
        # create user and get pk
        User.objects.create_user(username="******",
                                 email="*****@*****.**")
        user = User.objects.get(username="******")

        # Create token with user.pk
        token = make_timed_token(user.pk, 20)
        # Test redirection to invalid page
        invalid_response = self.client.get("/auth/activate/True/" +
                                           token[:-2] + get_random_string(2))
        self.assertIn(
            "Le lien de confirmation est invalide. Peut-être qu'il a déjà été utilisé ou qu'il a expiré.",
            invalid_response.content.decode("utf-8"))
コード例 #5
0
    def test_mail_with_timed_out_token(self):
        # create user and get pk
        User.objects.create_user(username="******",
                                 email="*****@*****.**")
        user = User.objects.get(username="******")

        # Create token with user.pk
        EXPIRY_MINUTES = 0
        EXPIRY_SECONDS = EXPIRY_MINUTES * 60
        NOW = datetime.datetime.now().timestamp() - 1
        token = make_timed_token(user.pk, EXPIRY_MINUTES, NOW)
        # Test redirection to invalid page
        response = self.client.get("/auth/activate/True/" + token)
        self.assertInHTML(
            "Le lien de confirmation est invalide. Peut-être qu'il a déjà été utilisé ou qu'il a expiré.",
            response.content.decode("utf-8"))
コード例 #6
0
ファイル: tests_auth.py プロジェクト: transport-nantes/tn_web
    def test_expiry(self):
        """Test token expiration.

        Test that the token remains valid for the time we expect and
        not after.

        """
        EMAIL = "*****@*****.**"
        EXPIRY_MINUTES = 2
        EXPIRY_SECONDS = EXPIRY_MINUTES * 60
        NOW = datetime.datetime.now().timestamp()
        for persisted in [0, 1]:
            token = make_timed_token(EMAIL, EXPIRY_MINUTES, persisted, NOW)
            now_response = token_valid(token, NOW)
            self.assertEqual(now_response[0], EMAIL)
            self.assertEqual(now_response[1], persisted)
            before_response = token_valid(token, NOW + EXPIRY_SECONDS - 1)
            self.assertEqual(before_response[0], EMAIL)
            self.assertEqual(before_response[1], persisted)
            after_response = token_valid(token, NOW + EXPIRY_SECONDS + 1)
            self.assertEqual(after_response[0], None)
            self.assertEqual(after_response[1], 0)
コード例 #7
0
ファイル: views.py プロジェクト: Shriukan33/tn_web
def send_activation(request, user):
    """Send user an activation/login link.

    The caller should then redirect to / render a template letting the
    user know the mail is on its way, since the redirect is a GET.

    """
    current_site = get_current_site(request)
    subject = 'Votre compte à {dom}'.format(dom=current_site.domain)
    message = render_to_string(
        'authentication/account_activation_email.html', {
            'user_id': user.pk,
            'domain': current_site.domain,
            'token': make_timed_token(user.pk, 20),
        })
    if hasattr(settings,
               'ROLE') and settings.ROLE in ['staging', 'production']:
        user.email_user(subject, message)
    else:
        # We're in dev.
        print("Mode dev : mél qui aurait été envoyé :")
        print(message)
コード例 #8
0
def send_activation(request, email, remember_me):
    """Send user an activation/login link.

    In fact, the user may not exist yet.  New users we create after
    they respond to the email link.

    The caller should then redirect to / render a template letting the
    user know the mail is on its way, since the redirect is a GET.

    """
    subject = 'sujet'
    # Emails can have a HTML version and a plain text alternative.
    # https://docs.djangoproject.com/en/3.2/topics/email/#send-mail
    # You can pass html to the send_mail function through the
    # html_message argument.
    html_message = render_to_string(
        'authentication/account_activation_email.html',
        {  # request.build_absolute_uri(),
            'scheme': request.scheme,
            'host': request.get_host(),
            'token': make_timed_token(email, 20),
            'remember_me': remember_me,
        })
    plain_text_message = strip_tags(html_message)
    if hasattr(settings, 'ROLE') and settings.ROLE in ['beta', 'production']:
        try:
            send_mail(subject,
                      plain_text_message,
                      settings.DEFAULT_FROM_EMAIL, [email],
                      html_message=html_message,
                      fail_silently=False)
        except Exception as e:
            logger.error(f"Error while sending mail to {email} : {e}")

    elif os.getenv('TEST_MODE', "0") == "0":
        # Only print this in dev mode, which is the only time
        # we'd care.
        print(f"Sent message : \n{plain_text_message}")
コード例 #9
0
    def test_unchecked_remember_me(self):

        # create user and get pk
        User.objects.create_user(username="******",
                                 email="*****@*****.**")
        user = User.objects.get(username="******")

        # Create token with user.pk
        token = make_timed_token(user.pk, 20)

        # Set remember_me to "False" like if checked
        remember_me = "False"
        # Simulate connexion
        response = self.client.get("/auth/activate/" + remember_me + "/" +
                                   token)

        # Get cookies
        cookies = response.client.cookies
        for k, v in cookies.items():
            if k == "sessionid":
                max_age = v["max-age"]

        # Test that max-age value of sessionid cookie is set to expire at the end of the session
        self.assertEqual(max_age, "")