Python django.conf.settings.PASSWORD_RESET_TIMEOUT_DAYS Examples

The following are 13 code examples for showing how to use django.conf.settings.PASSWORD_RESET_TIMEOUT_DAYS(). 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.conf.settings , or try the search function .

Example 1
Project: GTDWeb   Author: lanbing510   File: tokens.py    License: GNU General Public License v2.0 6 votes vote down vote up
def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
            return False

        return True 
Example 2
Project: fomalhaut-panel   Author: restran   File: tokens.py    License: MIT License 6 votes vote down vote up
def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
            return False

        return True 
Example 3
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: tokens.py    License: MIT License 6 votes vote down vote up
def _make_hash_value(self, user, timestamp):
        """
        Hash the user's primary key and some user state that's sure to change
        after a password reset to produce a token that invalidated when it's
        used:
        1. The password field will change upon a password reset (even if the
           same password is chosen, due to password salting).
        2. The last_login field will usually be updated very shortly after
           a password reset.
        Failing those things, settings.PASSWORD_RESET_TIMEOUT_DAYS eventually
        invalidates the token.

        Running this data through salted_hmac() prevents password cracking
        attempts using the reset token, provided the secret isn't compromised.
        """
        # Truncate microseconds so that tokens are consistent even if the
        # database doesn't support microseconds.
        login_timestamp = '' if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None)
        return str(user.pk) + user.password + str(login_timestamp) + str(timestamp) 
Example 4
Project: openhgsenti   Author: drexly   File: tokens.py    License: Apache License 2.0 6 votes vote down vote up
def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
            return False

        return True 
Example 5
Project: djongo   Author: nesdis   File: test_tokens.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_timeout(self):
        """
        The token is valid after n days, but no greater.
        """
        # Uses a mocked version of PasswordResetTokenGenerator so we can change
        # the value of 'today'
        class Mocked(PasswordResetTokenGenerator):
            def __init__(self, today):
                self._today_val = today

            def _today(self):
                return self._today_val

        user = User.objects.create_user('tokentestuser', 'test2@example.com', 'testpw')
        p0 = PasswordResetTokenGenerator()
        tk1 = p0.make_token(user)
        p1 = Mocked(date.today() + timedelta(settings.PASSWORD_RESET_TIMEOUT_DAYS))
        self.assertTrue(p1.check_token(user, tk1))
        p2 = Mocked(date.today() + timedelta(settings.PASSWORD_RESET_TIMEOUT_DAYS + 1))
        self.assertFalse(p2.check_token(user, tk1)) 
Example 6
Project: djongo   Author: nesdis   File: test_tokens.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_timeout(self):
        """
        The token is valid after n days, but no greater.
        """
        # Uses a mocked version of PasswordResetTokenGenerator so we can change
        # the value of 'today'
        class Mocked(PasswordResetTokenGenerator):
            def __init__(self, today):
                self._today_val = today

            def _today(self):
                return self._today_val

        user = User.objects.create_user('tokentestuser', 'test2@example.com', 'testpw')
        p0 = PasswordResetTokenGenerator()
        tk1 = p0.make_token(user)
        p1 = Mocked(date.today() + timedelta(settings.PASSWORD_RESET_TIMEOUT_DAYS))
        self.assertTrue(p1.check_token(user, tk1))
        p2 = Mocked(date.today() + timedelta(settings.PASSWORD_RESET_TIMEOUT_DAYS + 1))
        self.assertFalse(p2.check_token(user, tk1)) 
Example 7
Project: bioforum   Author: reBiocoder   File: tokens.py    License: MIT License 5 votes vote down vote up
def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        if not (user and token):
            return False
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
            return False

        return True 
Example 8
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: tokens.py    License: MIT License 5 votes vote down vote up
def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        if not (user and token):
            return False
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit. Timestamps are rounded to
        # midnight (server time) providing a resolution of only 1 day. If a
        # link is generated 5 minutes before midnight and used 6 minutes later,
        # that counts as 1 day. Therefore, PASSWORD_RESET_TIMEOUT_DAYS = 1 means
        # "at least 1 day, could be up to 2."
        if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
            return False

        return True 
Example 9
Project: python2017   Author: bpgc-cte   File: tokens.py    License: MIT License 5 votes vote down vote up
def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        if not (user and token):
            return False
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
            return False

        return True 
Example 10
Project: hypha   Author: OpenTechFund   File: utils.py    License: 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 11
Project: jorvik   Author: CroceRossaItaliana   File: viste.py    License: GNU General Public License v3.0 5 votes vote down vote up
def recupera_password_conferma(request, uidb64=None, token=None,
                           template='base_recupero_password_conferma.html',
                           contesto_extra=None):
    assert uidb64 is not None and token is not None  # checked by URLconf
    try:
        # urlsafe_base64_decode() decodes to bytestring on Python 3
        uid = force_text(urlsafe_base64_decode(uidb64))
        utente = Utenza.objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, Utenza.DoesNotExist):
        utente = None

    if utente is not None and default_token_generator.check_token(utente, token):
        link_valido = True
        titolo = 'Inserisci una nuova password'
        if request.method == 'POST':
            modulo = ModuloImpostaPassword(utente, request.POST)
            if modulo.is_valid():
                modulo.save()
                return HttpResponseRedirect(reverse('recupero_password_completo'))
        else:
            modulo = ModuloImpostaPassword(utente)
    else:
        link_valido = False
        modulo = None
        titolo = 'Errore nell\'impostazione della nuova password'
    contesto = {
        'modulo': modulo,
        'titolo': titolo,
        'link_valido': link_valido,
        "scadenza_token": django_settings.PASSWORD_RESET_TIMEOUT_DAYS * 24
    }
    if contesto_extra is not None:
        contesto.update(contesto_extra)

    return TemplateResponse(request, template, contesto) 
Example 12
Project: django-uniauth   Author: lgoodridge   File: models.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def clear_old_tmp_users(sender, instance, created, **kwargs):
    """
    Deletes temporary users more than PASSWORD_RESET_TIMEOUT_DAYS
    old when a User is created.

    Does nothing if the user model does not have date_joined field.
    """
    if created:
        user_model = get_user_model()
        if hasattr(user_model, 'date_joined'):
            timeout_days = timedelta(days=settings.PASSWORD_RESET_TIMEOUT_DAYS)
            tmp_expire_date = (timezone.now() - timeout_days).replace(
                    hour=0, minute=0, second=0, microsecond=0)
            user_model.objects.filter(username__startswith='tmp-',
                    date_joined__lt=tmp_expire_date).delete() 
Example 13
Project: django-uniauth   Author: lgoodridge   File: test_models.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_clear_old_tmp_users_signal(self):
        """
        Ensure old temporary users are deleted whenever
        a new User is created
        """
        User.objects.all().delete()
        User.objects.create(username="not-temporary-user")
        for i in range(10):
            User.objects.create(username="tmp-%d-days-ago"%i)
        # We must update the date_joined in a different for loop,
        # because otherwise, the users could get deleted on the
        # create signal we're trying to test!
        for i in range(10):
            date_joined = timezone.now() - timedelta(days=i)
            user = User.objects.get(username="tmp-%d-days-ago"%i)
            user.date_joined = date_joined
            user.save()
        # Create another object to (hopefully) trigger the tmp
        # user deletion signal
        User.objects.create(username="another-user")

        expected_num_users = 10 - (settings.PASSWORD_RESET_TIMEOUT_DAYS + 1) + 2
        self.assertEqual(User.objects.count(), expected_num_users)
        self.assertTrue(User.objects.filter(username="not-temporary-user")\
                .exists())
        self.assertTrue(User.objects.filter(username="another-user").exists())
        for i in range(settings.PASSWORD_RESET_TIMEOUT_DAYS + 1):
            self.assertTrue(User.objects.filter(username="tmp-%d-days-ago"%i)\
                    .exists())
        for i in range(settings.PASSWORD_RESET_TIMEOUT_DAYS + 1, 10):
            self.assertFalse(User.objects.filter(username="tmp-%d-days-ago"%i)\
                    .exists())