我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用django.core.signing.BadSignature()。
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')
def post(self, request): errors = [] fatal = False token = request.data.get('token') password = request.data.get('password') if not token: errors.append('Invalid reset token.') fatal = True if not password: errors.append('No password provided.') signer = TimestampSigner(salt=settings.RESET_SALT) if token: try: user_uuid = signer.unsign(token, max_age=settings.RESET_TOKEN_LENGTH) except BadSignature: errors.append('Can not reset password because the reset link used was invalid.') fatal = True if len(errors) == 0: # set password user = PFBUser.objects.get(uuid=user_uuid) user.set_password(password) user.save() return Response({'status': 'Success'}) else: return Response({'errors': errors, 'fatal': fatal}, status.HTTP_400_BAD_REQUEST)
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None): """ Attempts to return a signed cookie. If the signature fails or the cookie has expired, raises an exception... unless you provide the default argument in which case that value will be returned instead. """ try: cookie_value = self.COOKIES[key] except KeyError: if default is not RAISE_ERROR: return default else: raise try: value = signing.get_cookie_signer(salt=key + salt).unsign( cookie_value, max_age=max_age) except signing.BadSignature: if default is not RAISE_ERROR: return default else: raise return value
def clean(self): cleaned_data = super(ConfirmEmailForm, self).clean() if self.errors: return cleaned_data user_id = cleaned_data['user'] code = cleaned_data['code'] for_subscription = cleaned_data['subscribe'] user = User.objects.filter(id=user_id).first() if not user: raise forms.ValidationError('Invalid Link') self.cleaned_data['user'] = user try: user_service.validate_key(key=code, user=user, for_subscription=for_subscription) except BadSignature: raise forms.ValidationError('Invalid Link') except SignatureExpired: raise forms.ValidationError('Link expired, please regenerate') return cleaned_data
def do_password_reset(request, token=None): try: email, timestamp = _password_reset_token_factory.parse_token(token) except (signing.BadSignature, signing.SignatureExpired): return render(request, 'users/password_reset/reset_token_invalid.html', {}) try: user = get_user(email) except User.DoesNotExist: raise Http404() profile = user.profile timestamp = datetime.utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc) if profile.last_password_change and profile.last_password_change > timestamp: return render(request, 'users/password_reset/token_already_used.html', {}) form = SetPasswordForm(user, request.POST or None) if form.is_valid(): form.save() profile.last_password_change = timezone.now() profile.save() return render(request, 'users/password_reset/reset_complete.html', {}) return render(request, 'users/password_reset/reset_form.html', { 'user': user, 'form': form, })
def store_in_session(data, password, username): user = User.objects.get(username=username) data = json.loads(data) try: dec_data = signing.loads(data['secret'], key=password) except signing.BadSignature: return None enc_data = signing.dumps(dec_data) s = SessionStore() s['api_data'] = enc_data s.create() user.session.session_token = s.session_key user.save() return True
def validate_key(self, activation_key): try: username = signing.loads( activation_key, salt=settings.REGISTRATION_SALT, max_age=settings.ACCOUNT_ACTIVATION_DAYS * 86400 ) return username # SignatureExpired is a subclass of BadSignature, so this will # catch either one. except signing.SignatureExpired: self.template_name = "accounts/activation_error.html" self.error_reason = "Your code has expired" return None except signing.BadSignature: self.template_name = "accounts/activation_error.html" self.error_reason = "Bad activation key" return None
def verify_signature(self, signature): """ Checks if the signature has been tampered with. :arg str signature: The signature to check, as generated by :func:`make_signature`. :returns: ``True`` if the signature has not been tampered with, ``False`` otherwise. :rtype: bool """ signer = Signer() value = "%s:%s" % (self.new_email, signature) try: signer.unsign(value) except BadSignature: return False return True
def validate_key(self, activation_key): """ Verify that the activation key is valid and within the permitted activation time window, returning the username if valid or ``None`` if not. """ try: username = signing.loads( activation_key, salt=REGISTRATION_SALT, max_age=settings.ACCOUNT_ACTIVATION_DAYS * 86400 ) return username # SignatureExpired is a subclass of BadSignature, so this will # catch either one. except signing.BadSignature: return None
def get_widget_or_404(self): """ Get and return widget from cache. Raises: Http404: If if the widget can not be found or no id is provided. Returns: ModelSelect2Mixin: Widget from cache. """ field_id = self.kwargs.get('field_id', self.request.GET.get('field_id', None)) if not field_id: raise Http404('No "field_id" provided.') try: key = signing.loads(field_id) except BadSignature: raise Http404('Invalid "field_id".') else: cache_key = '%s%s' % (settings.SELECT2_CACHE_PREFIX, key) widget_dict = cache.get(cache_key) if widget_dict is None: raise Http404('field_id not found') if widget_dict.pop('url') != self.request.path: raise Http404('field_id was issued for the view.') qs, qs.query = widget_dict.pop('queryset') self.queryset = qs.all() widget_dict['queryset'] = self.queryset widget_cls = widget_dict.pop('cls') return widget_cls(**widget_dict)
def change_email_step1done(request): signer = Signer('accounts.views.change-email') email_signed = urlsafe_base64_decode(request.GET.get('e', '')) try: email = signer.unsign(email_signed) except BadSignature: raise SuspiciousOperation('change_step1done received invalid signed email {}'.format(signer)) return render(request, 'accounts/change_email/step1done.html', {'email': email})
def forgot_step1done(request): if request.user.is_authenticated(): return redirect(_login_redirect_url(request)) signer = Signer('accounts.views.forgot-email') email_signed = urlsafe_base64_decode(request.GET.get('e', '')) try: email = signer.unsign(email_signed) except BadSignature: raise SuspiciousOperation('forgot_step1done received invalid signed email {}'.format(signer)) return render(request, 'accounts/forgot/step1done.html', {'email': email})
def validate_key(self, activation_key): try: username = signing.loads( activation_key, salt=REGISTRATION_SALT, max_age=ACCOUNT_ACTIVATION_DAYS * 86400) except signing.BadSignature: username = None return username
def unsubscribe_reports(request, username): try: signing.Signer().unsign(request.GET.get("token")) except signing.BadSignature: return HttpResponseBadRequest() user = User.objects.get(username=username) user.profile.reports_allowed = False user.profile.save() return render(request, "accounts/unsubscribed.html")
def value_from_datadict(self, data, files, name): value = super(SignedHiddenInput, self).value_from_datadict(data, files, name) try: value = signer.unsign(value) except BadSignature: raise SuspiciousOperation() if self.include_field_name: name_key = '{0}-'.format(name) if not value.startswith(name_key): raise SuspiciousOperation() value = value.replace(name_key, '', 1) return value
def check_signature(signature, filename, username): try: SIGNER.unsign(':'.join([filename, username, signature])) except BadSignature: return False return True
def load(self): """ We load the data from the key itself instead of fetching from some external data store. Opposite of _get_session_key(), raises BadSignature if signature fails. """ try: return signing.loads(self.session_key, serializer=self.serializer, # This doesn't handle non-default expiry dates, see #19201 max_age=settings.SESSION_COOKIE_AGE, salt='django.contrib.sessions.backends.signed_cookies') except (signing.BadSignature, ValueError): self.create() return {}
def activate(request, token=None): try: data = _registration_token_factory.parse_token(token) except (signing.BadSignature, signing.SignatureExpired): return render(request, 'users/registration/registration_token_invalid.html', {}) try: existing_user = get_user(data['email']) return render(request, 'users/registration/already_activated.html', { 'existing_user': existing_user, }) except User.DoesNotExist: pass form = ActivationForm(request.POST or None) if form.is_valid(): user = create_user(data['email'], first_name=data['first_name'], last_name=data['last_name']) user.set_password(form.cleaned_data['password']) user.save() # the userprofile is auto-created, we only have to update some fields. profile = user.profile profile.gender = data['gender'] profile.forward_messages_after_minutes = 5 profile.save() return render(request, 'users/registration/activation_complete.html', { 'activated_user': user, }) return render(request, 'users/registration/activation_form.html', { 'form': form, 'data': data, })
def get_identifier(self): """ Gets the instance, if token is valid. :param klass: the class (must be model.Model instance) May throw DoesNotExist :returns: instance if signature is ok, None else. """ try: payload = signing.Signer().unsign(self.token) except signing.BadSignature: return None else: d = json.loads(force_text(urlsafe_base64_decode(payload))) return d.get('identifier')
def from_key(cls, key): try: max_age = ( 60 * 60 * 24 * app_settings.EMAIL_CONFIRMATION_EXPIRE_DAYS) pk = signing.loads( key, max_age=max_age, salt=app_settings.SALT) ret = EmailConfirmationHMAC(EmailAddress.objects.get(pk=pk)) except (signing.SignatureExpired, signing.BadSignature, EmailAddress.DoesNotExist): ret = None return ret
def load_data(self): try: data = self.request.get_signed_cookie(self.prefix) except KeyError: data = None except BadSignature: raise SuspiciousOperation('WizardView cookie manipulated') if data is None: return None return json.loads(data, cls=json.JSONDecoder)
def validate_sign(self, value): try: self.signed_data = signing.loads(value, max_age=PASSWORD_RESET_SIGNING_EXPIRATION) except signing.SignatureExpired: raise serializers.ValidationError('Signature expired.') except signing.BadSignature: raise serializers.ValidationError('Bad signature.') try: self.user = User.objects.get(pk=self.signed_data.get('user_id', None)) except User.DoesNotExist: raise serializers.ValidationError('User does not exist.') return value
def load_data(self): try: data = self.request.get_signed_cookie(self.prefix) except KeyError: data = None except BadSignature: raise WizardViewCookieModified('WizardView cookie manipulated') if data is None: return None return json.loads(data, cls=json.JSONDecoder)
def activate(self, *args, **kwargs): # This is safe even if, somehow, there's no activation key, # because unsign() will raise BadSignature rather than # TypeError on a value of None. username = self.validate_key(kwargs.get('activation_key')) if username is not None: user = self.get_user(username) if user is not None: user.is_active = True user.save() return user return False
def unsign(self, signed_value): # This unsign is identical to subclass except for the lowercasing # See: https://github.com/django/django/blob/1.6.11/django/core/signing.py#L165-L172 signed_value = force_str(signed_value) if self.sep not in signed_value: raise BadSignature('No "%s" found in value' % self.sep) value, sig = signed_value.rsplit(self.sep, 1) if constant_time_compare(sig.lower(), self.signature(value)): return force_text(value) raise BadSignature('Signature "%s" does not match' % sig)
def check_token(user_id, token): try: key = '%s:%s' % (user_id, token) TimestampSigner().unsign(key, max_age=60 * 60 * 48) # Valid for 2 days except (BadSignature, SignatureExpired): return False return True
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
def email_confirm(request, template_name='registration/confirmed.html'): user = request.user email_confirm_value = request.GET.get('email_confirm_value', '-') email_confirm_value = user.email + ":" + email_confirm_value.replace(".", ":") success_url = request.GET.get('success_url', None) signer = TimestampSigner(salt=settings.EMAIL_CONFIRM_SALT) try: signer.unsign(email_confirm_value, max_age=timedelta(seconds=300)) registration, created = Registration.objects.get_or_create(user_id=user.id) # If this is a new registration make sure we at least save the email/username. if created: registration.email = user.username registration.email_confirmed = True registration.save() # Set a message. messages.success(request, 'Email has been confirmed.', extra_tags='success', fail_silently=True) except SignatureExpired: messages.error(request, 'This email confirmation code has expired, please try again.', extra_tags='danger', fail_silently=True) except BadSignature: messages.error(request, 'This email confirmation code is invalid, please try again.', extra_tags='danger', fail_silently=True) # Continue on to the next page, if passed. Otherwise render a default page. if success_url: return redirect(success_url) else: return render(request, template_name)
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': form = PasswordForm(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: weitere felder?? ) user.set_password(form.cleaned_data['password1']) user.save() user.backend='django.contrib.auth.backends.ModelBackend' login(request, user) return redirect('home') else: form = PasswordForm() return TemplateResponse(request, 'registration/create_account.html', { 'form': form, 'username': username })
def setup_totp(request): if twofa.models.TOTPDevice.objects.active_for_user(request.user).exists(): messages.error(request, _('You may not have multiple Google Authenticators attached to your account.')) return redirect('twofa:list') setup_signer = TimestampSigner('twofa.views.setup_totp:{}'.format(request.user.pk)) if request.method == 'POST' and 'secret' in request.POST: try: b32_secret = setup_signer.unsign(request.POST['secret'], max_age=600) except SignatureExpired: messages.error(request, _('That took too long and your challenge expired. Here\'s a new one.')) return redirect('twofa:setup-totp') except BadSignature: messages.error(request, _('Whoops - something went wrong. Please try again.')) return redirect('twofa:setup-totp') else: b32_secret = base64.b32encode(secrets.token_bytes(10)) signed_secret = setup_signer.sign(b32_secret) url = 'otpauth://totp/Sponge:{}?{}'.format( urlquote(request.user.username), urlencode({ 'secret': b32_secret, 'issuer': 'Sponge'})) img = qrcode.make(url, image_factory=qrcode.image.svg.SvgPathFillImage) img_buf = io.BytesIO() img.save(img_buf) device = twofa.models.TOTPDevice(base32_secret=b32_secret, owner=request.user) device.activated_at = timezone.now() # this won't be saved unless the form is valid form = device.verify_form(secret=signed_secret) if request.method == 'POST': form = device.verify_form(request.POST, secret=signed_secret) if form.is_valid(): # relying on verify_form to save the new device request.user.twofa_enabled = True request.user.save() messages.success(request, _('Your authenticator has been added to your account.')) return _generate_paper_codes_if_needed(request.user, reverse('twofa:list')) return render(request, 'twofa/setup/totp.html', { 'form': form, 'qr_code_svg': img_buf.getvalue(), 'b32_secret': b32_secret})
def serve_qr_code_image(request): """Serve an image that represents the requested QR code.""" text = base64.urlsafe_b64decode(request.GET.get('text', '')) size = request.GET.get('size', DEFAULT_MODULE_SIZE) border = request.GET.get('border', DEFAULT_BORDER_SIZE) version = request.GET.get('version', DEFAULT_VERSION) image_format = request.GET.get('image_format', DEFAULT_IMAGE_FORMAT) image_format = get_supported_image_format(image_format) # Handle view protection (we do not allow external requests for anyone). url_protection_options = get_url_protection_options(request.user) if not url_protection_options['ALLOWS_EXTERNAL_REQUESTS']: token = request.GET.get('token', '') signer = Signer(key=url_protection_options['SIGNING_KEY'], salt=url_protection_options['SIGNING_SALT']) try: # Check signature. url_protection_string = signer.unsign(token) # Check that the given token matches the request parameters. random_token = url_protection_string.split('.')[-1] if get_qr_url_protection_token(size, border, version, image_format, random_token) != url_protection_string: raise PermissionDenied("Request query does not match protection token.") except BadSignature: raise PermissionDenied("Wrong token signature.") img = make_qr_code_image(text, image_factory=SvgPathImage if image_format == SVG_FORMAT_NAME else PilImageOrFallback, size=size, border=border, version=version) # Warning: The largest QR codes, in version 40, with a border of 4 modules, and rendered in SVG format, are ~800 # KB large. This can be handled in memory but could cause troubles if the server needs to generate thousands of # those QR codes within a short interval! Note that this would also be a problem for the CPU. Such QR codes needs # 0.7 second to be generated on a powerful machine (2017), and probably more than one second on a cheap hosting. stream = BytesIO() if image_format == SVG_FORMAT_NAME: img.save(stream, kind=SVG_FORMAT_NAME.upper()) mime_type = 'image/svg+xml' else: img.save(stream, format=PNG_FORMAT_NAME.upper()) mime_type = 'image/png' # Go to the beginning of the stream. stream.seek(0) # Build the response. response = HttpResponse(content=stream, content_type=mime_type) return response
def decode(code, *, max_age): """ Decodes the code from the registration link and returns a tuple consisting of the verified email address and the associated user instance or ``None`` if no user was passed to ``send_registration_mail`` Pass the maximum age in seconds of the link as ``max_age``. This method raises ``ValidationError`` exceptions containing an translated message what went wrong suitable for presenting directly to the user. """ try: data = get_signer().unsign(code, max_age=max_age) except signing.SignatureExpired: raise ValidationError(_( 'The link is expired. Please request another registration link.' ), code='email_registration_expired') except signing.BadSignature: raise ValidationError(_( 'Unable to verify the signature. Please request a new' ' registration link.' ), code='email_registration_signature') parts = data.split(':') if len(parts) != 3: raise ValidationError(_( 'Something went wrong while decoding the' ' registration request. Please try again.' ), code='email_registration_broken') email, uid, timestamp = parts if uid and timestamp: try: user = User.objects.get(pk=uid) except (User.DoesNotExist, TypeError, ValueError): raise ValidationError(_( 'Something went wrong while decoding the' ' registration request. Please try again.' ), code='email_registration_invalid_uid') if timestamp != int_to_base36(get_last_login_timestamp(user)): raise ValidationError(_( 'The link has already been used.' ), code='email_registration_used') else: user = None return email, user