Python django.core.signing.TimestampSigner() Examples

The following are 30 code examples of django.core.signing.TimestampSigner(). 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.core.signing , or try the search function .
Example #1
Source File: test_unsubscribe_reports.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_it_unsubscribes(self):
        self.profile.next_report_date = now()
        self.profile.nag_period = td(hours=1)
        self.profile.next_nag_date = now()
        self.profile.save()

        sig = signing.TimestampSigner(salt="reports").sign("alice")
        url = "/accounts/unsubscribe_reports/%s/" % sig

        r = self.client.post(url)
        self.assertContains(r, "Unsubscribed")

        self.profile.refresh_from_db()
        self.assertFalse(self.profile.reports_allowed)
        self.assertIsNone(self.profile.next_report_date)

        self.assertEqual(self.profile.nag_period.total_seconds(), 0)
        self.assertIsNone(self.profile.next_nag_date) 
Example #2
Source File: views.py    From website with GNU General Public License v3.0 6 votes vote down vote up
def get_object(self):
        # Decode the timestamped data:
        # - the PK of the AlumSurveyTracker
        #
        # If the timestamp is older than 1 month, display an error message.
        #
        # Figure out which model is not null (alumni_info or intern_info) to use.
        # See if we already have an AlumSurvey that points to this survey tracker.
        # If not, create it.
        signer = TimestampSigner()
        try:
            this_pk = signer.unsign(self.kwargs['survey_slug'], max_age=timedelta(days=30))
        except SignatureExpired:
            raise PermissionDenied("The survey link has expired.")
        except BadSignature:
            raise PermissionDenied("Bad survey link.")

        try:
            return AlumSurvey.objects.get(survey_tracker__pk=this_pk)
        except AlumSurvey.DoesNotExist:
            tracker = get_object_or_404(AlumSurveyTracker, pk=this_pk)
            return AlumSurvey(survey_tracker=tracker, survey_date=datetime.now())

    # No need to override get_context because we can get everything from
    # form.instance.survey_tracker 
Example #3
Source File: views.py    From website with GNU General Public License v3.0 6 votes vote down vote up
def survey_opt_out(request, survey_slug):
    signer = TimestampSigner()
    try:
        this_pk = signer.unsign(survey_slug)
    except BadSignature:
        raise PermissionDenied("Bad survey opt-out link.")

    try:
        survey_tracker = AlumSurveyTracker.objects.get(pk=this_pk)
    except AlumSurveyTracker.DoesNotExist:
        raise PermissionDenied("Bad survey opt-out link.")

    if survey_tracker.alumni_info != None:
        survey_tracker.alumni_info.survey_opt_out = True
        survey_tracker.alumni_info.save()
    elif survey_tracker.intern_info != None:
        survey_tracker.intern_info.survey_opt_out = True
        survey_tracker.intern_info.save()

    return render(request, 'home/survey_opt_out_confirmation.html') 
Example #4
Source File: password_reset.py    From lego with MIT License 6 votes vote down vote up
def generate_reset_token(email):
        return TimestampSigner().sign(signing.dumps({"email": email})) 
Example #5
Source File: tests.py    From uclapi with MIT License 6 votes vote down vote up
def test_expired_signature(self, TimestampSigner):
        request = self.factory.get(
            '/oauth/shibcallback',
            {
                'appdata': "invalid"
            }
        )
        response = shibcallback(request)
        content = json.loads(response.content.decode())
        self.assertEqual(response.status_code, 400)
        self.assertEqual(
            content["error"],
            ("Login data has expired. Please attempt to log in again. "
             "If the issues persist please contact the UCL API "
             "Team to rectify this.")
        ) 
Example #6
Source File: models.py    From lego with MIT License 6 votes vote down vote up
def validate_token(token):
        """
        Validate token.

        returns MeetingInvitation or None
        """

        try:
            # Valid in 7 days
            valid_in = 60 * 60 * 24 * 7
            data = signing.loads(TimestampSigner().unsign(token, max_age=valid_in))

            return MeetingInvitation.objects.filter(
                user=int(data["user_id"]), meeting=int(data["meeting_id"])
            )[0]
        except (BadSignature, SignatureExpired):
            return None 
Example #7
Source File: models.py    From wagtail-torchbox with MIT License 5 votes vote down vote up
def get_preview_signer(cls):
        return TimestampSigner(salt='headlesspreview.token') 
Example #8
Source File: test_unsubscribe_reports.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_aged_signature_autosubmits(self):
        with patch("django.core.signing.time") as mock_time:
            mock_time.time.return_value = time.time() - 301
            signer = signing.TimestampSigner(salt="reports")
            sig = signer.sign("alice")

        url = "/accounts/unsubscribe_reports/%s/" % sig

        r = self.client.get(url)
        self.assertContains(r, "Please press the button below")
        self.assertContains(r, "submit()") 
Example #9
Source File: views.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def unsubscribe_email(request, code, signed_token):
    # Some email servers open links in emails to check for malicious content.
    # To work around this, on GET requests we serve a confirmation form.
    # If the signature is at least 5 minutes old, we also include JS code to
    # auto-submit the form.
    ctx = {}
    if ":" in signed_token:
        signer = signing.TimestampSigner(salt="alerts")
        # First, check the signature without looking at the timestamp:
        try:
            token = signer.unsign(signed_token)
        except signing.BadSignature:
            return render(request, "bad_link.html")

        # Check if timestamp is older than 5 minutes:
        try:
            signer.unsign(signed_token, max_age=300)
        except signing.SignatureExpired:
            ctx["autosubmit"] = True

    else:
        token = signed_token

    channel = get_object_or_404(Channel, code=code, kind="email")
    if channel.make_token() != token:
        return render(request, "bad_link.html")

    if request.method != "POST":
        return render(request, "accounts/unsubscribe_submit.html", ctx)

    channel.delete()
    return render(request, "front/unsubscribe_success.html") 
Example #10
Source File: test_unsubscribe_email.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_fresh_signature_does_not_autosubmit(self):
        signer = TimestampSigner(salt="alerts")
        signed_token = signer.sign(self.channel.make_token())

        url = "/integrations/%s/unsub/%s/" % (self.channel.code, signed_token)

        r = self.client.get(url)
        self.assertContains(
            r, "Please press the button below to unsubscribe", status_code=200
        )
        self.assertNotContains(r, "submit()", status_code=200) 
Example #11
Source File: test_unsubscribe_email.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_aged_signature_does_autosubmit(self):
        with patch("django.core.signing.time") as mock_time:
            mock_time.time.return_value = time.time() - 301
            signer = TimestampSigner(salt="alerts")
            signed_token = signer.sign(self.channel.make_token())

        url = "/integrations/%s/unsub/%s/" % (self.channel.code, signed_token)

        r = self.client.get(url)
        self.assertContains(
            r, "Please press the button below to unsubscribe", status_code=200
        )
        self.assertContains(r, "submit()", status_code=200) 
Example #12
Source File: models.py    From wagtail-headless-preview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_preview_signer(cls):
        return TimestampSigner(salt="headlesspreview.token") 
Example #13
Source File: activation_service.py    From della with MIT License 5 votes vote down vote up
def validate_key(key, user):
    signer = TimestampSigner(settings.SECRET_KEY)
    try:
        value = signer.unsign(key, max_age=settings.EMAIL_LINK_EXPIRY_DAYS)
        return str(user.id) == value
    except (BadSignature, SignatureExpired):
        return False 
Example #14
Source File: tests.py    From uclapi with MIT License 5 votes vote down vote up
def test_userallow_bad_but_signed_post_data(self):
        signer = signing.TimestampSigner()
        signed_data = signer.sign("")
        response = self.client.post(
            '/oauth/user/allow',
            {
                'signed_app_data': signed_data
            },
        )
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json()["error"],
                         ("The JSON data was not in the expected format. "
                          "Please contact us at "
                          "isd.apiteam@ucl.ac.uk or on github.")) 
Example #15
Source File: tests.py    From uclapi with MIT License 5 votes vote down vote up
def test_userdeny_bad_but_signed_post_data(self):
        signer = signing.TimestampSigner()
        signed_data = signer.sign("")
        response = self.client.post(
            '/oauth/user/deny',
            {
                'signed_app_data': signed_data
            },
        )
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json()["error"],
                         ("The JSON data was not in the expected format. "
                          "Please contact us at "
                          "isd.apiteam@ucl.ac.uk or on github.")) 
Example #16
Source File: tests.py    From uclapi with MIT License 5 votes vote down vote up
def test_userdeny_user_does_not_exist(self):
        dev_user_ = User.objects.create(
            email="testdev@ucl.ac.uk",
            cn="test",
            given_name="Test Dev",
            employee_id='testdev01'
        )
        app_ = App.objects.create(
            user=dev_user_,
            name="An App",
            callback_url="www.somecallbackurl.com/callback"
        )

        signer = signing.TimestampSigner()
        # Generate a random state for testing
        state = ''.join(
            random.choices(string.ascii_letters + string.digits, k=32)
        )

        response_data = {
            "client_id": app_.client_id,
            "state": state,
            "user_upi": "bogus"
        }

        response_data_str = json.dumps(response_data, cls=DjangoJSONEncoder)
        signed_data = signer.sign(response_data_str)

        response = self.client.post(
            '/oauth/user/deny',
            {
                'signed_app_data': signed_data
            },
        )

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json()["error"],
                         ("User does not exist. This should never occur. "
                          "Please contact us at "
                          "isd.apiteam@ucl.ac.uk or on github.")) 
Example #17
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_timestamp_signer(self):
        value = 'hello'
        with freeze_time(123456789):
            signer = signing.TimestampSigner('predictable-key')
            ts = signer.sign(value)
            self.assertNotEqual(ts, signing.Signer('predictable-key').sign(value))
            self.assertEqual(signer.unsign(ts), value)

        with freeze_time(123456800):
            self.assertEqual(signer.unsign(ts, max_age=12), value)
            # max_age parameter can also accept a datetime.timedelta object
            self.assertEqual(signer.unsign(ts, max_age=datetime.timedelta(seconds=11)), value)
            with self.assertRaises(signing.SignatureExpired):
                signer.unsign(ts, max_age=10) 
Example #18
Source File: activation_service.py    From della with MIT License 5 votes vote down vote up
def generate_key(user):
    signer = TimestampSigner(settings.SECRET_KEY)
    return signer.sign(str(user.id)) 
Example #19
Source File: views.py    From django_microsoft_auth with MIT License 5 votes vote down vote up
def _check_csrf(self, state):
        signer = TimestampSigner()

        if state is None:
            state = ""

        try:
            state = signer.unsign(state, max_age=300)
        except BadSignature:  # pragma: no branch
            logger.debug("state has been tempered with")
            state = ""
        except SignatureExpired:  # pragma: no cover
            logger.debug("state has expired")
            state = ""

        checks = (
            re.search("[a-zA-Z0-9]", state),
            len(state) == CSRF_TOKEN_LENGTH,
        )

        # validate state parameter
        if not all(checks):
            logger.debug("State validation failed:")
            logger.debug("state: {}".format(state))
            logger.debug("checks: {}".format(checks))
            self.context["message"] = {"error": "bad_state"} 
Example #20
Source File: models.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def reports_unsub_url(self):
        signer = TimestampSigner(salt="reports")
        signed_username = signer.sign(self.user.username)
        path = reverse("hc-unsubscribe-reports", args=[signed_username])
        return settings.SITE_ROOT + path 
Example #21
Source File: context_processors.py    From django_microsoft_auth with MIT License 5 votes vote down vote up
def microsoft(request):
    """ Adds global template variables for microsoft_auth """
    login_type = None
    if config.MICROSOFT_AUTH_LOGIN_TYPE == LOGIN_TYPE_XBL:
        login_type = _("Xbox Live")
    else:
        login_type = _("Microsoft")

    if config.DEBUG:  # pragma: no branch
        try:
            current_domain = Site.objects.get_current(request).domain
        except Site.DoesNotExist:
            logger.warning(
                "\nWARNING:\nThe domain configured for the sites framework "
                "does not match the domain you are accessing Django with. "
                "Microsoft authentication may not work.\n"
            )
        else:
            do_warning = get_scheme(
                request
            ) == "http" and not current_domain.startswith("localhost")
            if do_warning:  # pragma: no branch
                logger.warning(
                    "\nWARNING:\nYou are not using HTTPS. Microsoft "
                    "authentication only works over HTTPS unless the hostname "
                    "for your `redirect_uri` is `localhost`\n"
                )

    # initialize Microsoft client using CSRF token as state variable
    signer = TimestampSigner()
    state = signer.sign(get_token(request))
    microsoft = MicrosoftClient(state=state, request=request)
    auth_url = microsoft.authorization_url()[0]
    return {
        "microsoft_login_enabled": config.MICROSOFT_AUTH_LOGIN_ENABLED,
        "microsoft_authorization_url": mark_safe(auth_url),  # nosec
        "microsoft_login_type_text": login_type,
    } 
Example #22
Source File: upload.py    From zulip with Apache License 2.0 5 votes vote down vote up
def generate_unauthed_file_access_url(path_id: str) -> str:
    signed_data = TimestampSigner(salt=LOCAL_FILE_ACCESS_TOKEN_SALT).sign(path_id)
    token = base64.b16encode(signed_data.encode('utf-8')).decode('utf-8')

    filename = path_id.split('/')[-1]
    return reverse('zerver.views.upload.serve_local_file_unauthed', args=[token, filename]) 
Example #23
Source File: upload.py    From zulip with Apache License 2.0 5 votes vote down vote up
def get_local_file_path_id_from_token(token: str) -> Optional[str]:
    signer = TimestampSigner(salt=LOCAL_FILE_ACCESS_TOKEN_SALT)
    try:
        signed_data = base64.b16decode(token).decode('utf-8')
        path_id = signer.unsign(signed_data, max_age=timedelta(seconds=60))
    except (BadSignature, binascii.Error):
        return None

    return path_id 
Example #24
Source File: models.py    From lego with MIT License 5 votes vote down vote up
def token_query_param(self):
        """
        Return a token that can be used to access the token file.
        """
        return signing.TimestampSigner().sign(self.id) 
Example #25
Source File: models.py    From lego with MIT License 5 votes vote down vote up
def token_verify_query_param(self, token):
        """
        Verify token access based on the token query param.
        """
        try:
            # Valid in 10 min
            valid_in = 60 * 10
            data = signing.TimestampSigner().unsign(token, max_age=valid_in)
            return data == str(self.id)
        except signing.BadSignature:
            pass
        return False 
Example #26
Source File: password_reset.py    From lego with MIT License 5 votes vote down vote up
def validate_reset_token(token):
        try:
            return signing.loads(
                TimestampSigner().unsign(token, max_age=settings.PASSWORD_RESET_TIMEOUT)
            )["email"]
        except (BadSignature, SignatureExpired):
            return None 
Example #27
Source File: registrations.py    From lego with MIT License 5 votes vote down vote up
def generate_registration_token(email):
        return TimestampSigner().sign(signing.dumps({"email": email})) 
Example #28
Source File: registrations.py    From lego with MIT License 5 votes vote down vote up
def generate_student_confirmation_token(student_username, course, member):
        data = signing.dumps(
            {
                "student_username": student_username.lower(),
                "course": course,
                "member": member,
            }
        )
        token = TimestampSigner().sign(data)
        return token 
Example #29
Source File: registrations.py    From lego with MIT License 5 votes vote down vote up
def validate_student_confirmation_token(token):
        try:
            return signing.loads(
                TimestampSigner().unsign(
                    token, max_age=settings.STUDENT_CONFIRMATION_TIMEOUT
                )
            )
        except (BadSignature, SignatureExpired):
            return None 
Example #30
Source File: models.py    From lego with MIT License 5 votes vote down vote up
def generate_invitation_token(self):
        data = signing.dumps({"user_id": self.user.id, "meeting_id": self.meeting.id})

        token = TimestampSigner().sign(data)
        return token