Python django.core.signing.SignatureExpired() Examples
The following are 19
code examples of django.core.signing.SignatureExpired().
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: verification.py From django-rest-registration with MIT License | 6 votes |
def verify(self): data = self._data signature = data.get(self.SIGNATURE_FIELD, None) if signature is None: raise BadSignature() expected_signature = self.calculate_signature() if not constant_time_compare(signature, expected_signature): raise BadSignature() valid_period = self.get_valid_period() if self.USE_TIMESTAMP and valid_period is not None: timestamp = data[self.TIMESTAMP_FIELD] timestamp = int(timestamp) current_timestamp = get_current_timestamp() valid_period_secs = valid_period.total_seconds() if current_timestamp - timestamp > valid_period_secs: raise SignatureExpired()
Example #2
Source File: views.py From django-register-sample with MIT License | 6 votes |
def get(self, request, **kwargs): token = kwargs.get('token') try: new_email = loads(token, max_age=self.timeout_seconds) # 期限切れ except SignatureExpired: return HttpResponseBadRequest() # tokenが間違っている except BadSignature: return HttpResponseBadRequest() # tokenは問題なし else: User.objects.filter(email=new_email, is_active=False).delete() request.user.email = new_email request.user.save() return super().get(request, **kwargs)
Example #3
Source File: views.py From Bitpoll with GNU General Public License v3.0 | 6 votes |
def change_email(request, token): try: data = signing.loads(token, max_age=TOKEN_MAX_AGE) except signing.SignatureExpired: return TemplateResponse(request, 'registration/token_expired.html') except signing.BadSignature: return TemplateResponse(request, 'registration/token_invalid.html') if request.user.username != data.get('username'): return TemplateResponse(request, 'registration/token_invalid.html') email = data.get('email') try: validate_email(email) except ValidationError: return TemplateResponse(request, 'registration/token_invalid.html') request.user.email = email request.user.save() messages.success(request, _('Your email address has been changed.')) return redirect('registration_account')
Example #4
Source File: models.py From lego with MIT License | 6 votes |
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 #5
Source File: views.py From website with GNU General Public License v3.0 | 6 votes |
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 #6
Source File: activation_service.py From della with MIT License | 5 votes |
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 #7
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_max_age_argument(self): value = 'hello' with freeze_time(123456789): response = HttpResponse() response.set_signed_cookie('c', value) request = HttpRequest() request.COOKIES['c'] = response.cookies['c'].value self.assertEqual(request.get_signed_cookie('c'), value) with freeze_time(123456800): self.assertEqual(request.get_signed_cookie('c', max_age=12), value) self.assertEqual(request.get_signed_cookie('c', max_age=11), value) with self.assertRaises(signing.SignatureExpired): request.get_signed_cookie('c', max_age=10)
Example #8
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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 #9
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_max_age_argument(self): value = 'hello' with freeze_time(123456789): response = HttpResponse() response.set_signed_cookie('c', value) request = HttpRequest() request.COOKIES['c'] = response.cookies['c'].value self.assertEqual(request.get_signed_cookie('c'), value) with freeze_time(123456800): self.assertEqual(request.get_signed_cookie('c', max_age=12), value) self.assertEqual(request.get_signed_cookie('c', max_age=11), value) with self.assertRaises(signing.SignatureExpired): request.get_signed_cookie('c', max_age=10)
Example #10
Source File: views.py From healthchecks with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #11
Source File: views.py From healthchecks with BSD 3-Clause "New" or "Revised" License | 5 votes |
def unsubscribe_reports(request, signed_username): # Some email servers open links in emails to check for malicious content. # To work around this, for GET requests we serve a confirmation form. # If the signature is more than 5 minutes old, we also include JS code to # auto-submit the form. ctx = {} signer = signing.TimestampSigner(salt="reports") # First, check the signature without looking at the timestamp: try: username = signer.unsign(signed_username) except signing.BadSignature: return render(request, "bad_link.html") # Check if timestamp is older than 5 minutes: try: username = signer.unsign(signed_username, max_age=300) except signing.SignatureExpired: ctx["autosubmit"] = True if request.method != "POST": return render(request, "accounts/unsubscribe_submit.html", ctx) user = User.objects.get(username=username) profile = Profile.objects.for_user(user) profile.reports_allowed = False profile.next_report_date = None profile.nag_period = td() profile.next_nag_date = None profile.save() return render(request, "accounts/unsubscribed.html")
Example #12
Source File: registrations.py From lego with MIT License | 5 votes |
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 #13
Source File: registrations.py From lego with MIT License | 5 votes |
def validate_registration_token(token): try: return signing.loads( TimestampSigner().unsign( token, max_age=settings.REGISTRATION_CONFIRMATION_TIMEOUT ) )["email"] except (BadSignature, SignatureExpired): return None
Example #14
Source File: password_reset.py From lego with MIT License | 5 votes |
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 #15
Source File: views.py From django_microsoft_auth with MIT License | 5 votes |
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 #16
Source File: views.py From django-register-sample with MIT License | 5 votes |
def get(self, request, **kwargs): """tokenが正しければ本登録.""" token = kwargs.get('token') try: user_pk = loads(token, max_age=self.timeout_seconds) # 期限切れ except SignatureExpired: return HttpResponseBadRequest() # tokenが間違っている except BadSignature: return HttpResponseBadRequest() # tokenは問題なし else: try: user = User.objects.get(pk=user_pk) except User.DoesNotExist: return HttpResponseBadRequest() else: if not user.is_active: # まだ仮登録で、他に問題なければ本登録とする user.is_active = True user.save() return super().get(request, **kwargs) return HttpResponseBadRequest()
Example #17
Source File: test_verification.py From django-rest-registration with MIT License | 5 votes |
def test_verify_expired(self): timestamp = int(time.time()) with patch('time.time', side_effect=lambda: timestamp): signer1 = self.create_signer({ 'email': self.test_email, }) signed_data = signer1.get_signed_data() signer2 = self.create_signer(signed_data) with patch('time.time', side_effect=lambda: timestamp + 3600 * 24 * 2): self.assertRaises(SignatureExpired, signer2.verify)
Example #18
Source File: verification.py From django-rest-registration with MIT License | 5 votes |
def verify_signer_or_bad_request(signer): try: signer.verify() except SignatureExpired: raise BadRequest(_("Signature expired")) except BadSignature: raise BadRequest(_("Invalid signature"))
Example #19
Source File: views.py From Bitpoll with GNU General Public License v3.0 | 4 votes |
def create_account(request, info_token): if request.user.is_authenticated: return redirect('home') try: info = signing.loads(info_token, max_age=TOKEN_MAX_AGE) except signing.SignatureExpired: return TemplateResponse(request, 'registration/token_expired.html') except signing.BadSignature: return TemplateResponse(request, 'registration/token_invalid.html') username = info['username'] if BitpollUser.objects.filter(username=username).exists(): messages.warning(request, _("This User already exists")) return redirect('login') if request.method == 'POST': # using None as User as we do not have the user, we can not call form.save() as a result form = SetPasswordForm(None, request.POST) if form.is_valid(): first_name = info.get('first_name') last_name = info.get('last_name') if not (first_name and last_name): return TemplateResponse(request, 'registration/token_invalid.html') email = info['email'] user = BitpollUser(username=username, email=email, first_name=first_name, last_name=last_name, email_invitation=info['email_invitation'], # TODO: more fields? ) user.set_password(form.cleaned_data['new_password2']) user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return redirect('home') else: form = SetPasswordForm(None) return TemplateResponse(request, 'registration/create_account.html', { 'form': form, 'username': username })