Python django.core.signing.loads() Examples
The following are 30
code examples of django.core.signing.loads().
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: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_decode_detects_tampering(self): "loads should raise exception for tampered objects" transforms = ( lambda s: s.upper(), lambda s: s + 'a', lambda s: 'a' + s[1:], lambda s: s.replace(':', ''), ) value = { 'foo': 'bar', 'baz': 1, } encoded = signing.dumps(value) self.assertEqual(value, signing.loads(encoded)) for transform in transforms: with self.assertRaises(signing.BadSignature): signing.loads(transform(encoded))
Example #2
Source File: views.py From healthchecks with BSD 3-Clause "New" or "Revised" License | 6 votes |
def telegram_bot(request): try: doc = json.loads(request.body.decode()) jsonschema.validate(doc, telegram_callback) except ValueError: return HttpResponseBadRequest() except jsonschema.ValidationError: # We don't recognize the message format, but don't want Telegram # retrying this over and over again, so respond with 200 OK return HttpResponse() if "/start" not in doc["message"]["text"]: return HttpResponse() chat = doc["message"]["chat"] name = max(chat.get("title", ""), chat.get("username", "")) invite = render_to_string( "integrations/telegram_invite.html", {"qs": signing.dumps((chat["id"], chat["type"], name))}, ) Telegram.send(chat["id"], invite) return HttpResponse()
Example #3
Source File: signed_cookies.py From python2017 with MIT License | 6 votes |
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 Exception: # BadSignature, ValueError, or unpickling exceptions. If any of # these happen, reset the session. self.create() return {}
Example #4
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 #5
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 #6
Source File: signed_cookies.py From bioforum with MIT License | 6 votes |
def load(self): """ Load the data from the key itself instead of fetching from some external data store. Opposite of _get_session_key(), raise 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 Exception: # BadSignature, ValueError, or unpickling exceptions. If any of # these happen, reset the session. self.create() return {}
Example #7
Source File: spam_util.py From Bitpoll with GNU General Public License v3.0 | 6 votes |
def check_anti_spam_challange(key: str, answer: str, poll_id: int) -> bool: """Checks if the anti spam cheallenge was solved and not expired""" try: spam_data = signing.loads(key) if spam_data.get('type') != 'anti_spam': raise ValidationError(_("Error while checking response")) except BadSignature: raise ValidationError(_("Error while checking response")) if spam_data['poll_id'] != poll_id: raise ValidationError(_("Error while checking response")) if spam_data['time'] <= time.time() - django_settings.ANTI_SPAM_CHALLENGE_TTL: raise ValidationError(_("Question Expired, please solve the new question.")) if answer is None: raise ValidationError(_('Field is required')) op = spam_data['op'] x = spam_data['x'] y = spam_data['y'] if op == '+': return answer == x + y if op == '-': return answer == x - y if op == '*': return answer == x * y raise ValidationError(_("Error while checking response"))
Example #8
Source File: signed_cookies.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def load(self): """ Load the data from the key itself instead of fetching from some external data store. Opposite of _get_session_key(), raise 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 Exception: # BadSignature, ValueError, or unpickling exceptions. If any of # these happen, reset the session. self.create() return {}
Example #9
Source File: utils.py From karrot-backend with GNU Affero General Public License v3.0 | 6 votes |
def parse_token(token): data = signing.loads(token) user = get_user_model().objects.get(pk=data['u']) result = {'user': user} if 'g' in data: result.update({'group': user.groups.get(pk=data['g'])}) if 'c' in data: result.update({'conversation': user.conversation_set.get(pk=data['c'])}) if 't' in data: result.update({'thread': ConversationMessage.objects.only_threads_with_user(user).get(pk=data['t'])}) if 'n' in data: result.update({'notification_type': data['n']}) return result
Example #10
Source File: signed_cookies.py From openhgsenti with Apache License 2.0 | 6 votes |
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 Exception: # BadSignature, ValueError, or unpickling exceptions. If any of # these happen, reset the session. self.create() return {}
Example #11
Source File: models.py From django-db-mailer with GNU General Public License v2.0 | 6 votes |
def track(cls, http_meta, encrypted): class Request(object): META = http_meta try: request = Request() mail_log_id = signing.loads(encrypted) mail_log = MailLog.objects.get(log_id=mail_log_id) track_log = MailLogTrack.objects.filter(mail_log=mail_log) if not track_log.exists(): MailLogTrack.objects.create( mail_log=mail_log, ip=get_ip(request), ua=request.META.get('HTTP_USER_AGENT'), is_read=True, ) else: track_log[0].save() except (signing.BadSignature, MailLog.DoesNotExist): pass
Example #12
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 #13
Source File: api_views.py From zentral with Apache License 2.0 | 5 votes |
def post(self, request, *args, **kwargs): payload = request.body if not payload: data = payload else: content_encoding = request.META.get('HTTP_CONTENT_ENCODING', None) if content_encoding: # try to decompress the payload. if content_encoding == "deflate" \ or "santa" in self.user_agent and content_encoding == "zlib" \ or self.user_agent == "Zentral/mnkpf 0.1" and content_encoding == "gzip": payload = zlib.decompress(payload) elif content_encoding == "gzip": payload = GzipFile(fileobj=request).read() else: return HttpResponse("Unsupported Media Type", status=415) try: payload = payload.decode(self.payload_encoding) except UnicodeDecodeError: err_msg_tmpl = 'Could not decode payload with encoding %s' logger.error(err_msg_tmpl, self.payload_encoding, extra={'request': request}) raise SuspiciousOperation(err_msg_tmpl % self.payload_encoding) try: data = json.loads(payload) except ValueError: raise SuspiciousOperation("Payload is not valid json") try: self.check_data_secret(data) except APIAuthError as auth_err: logger.error("APIAuthError %s", auth_err, extra={'request': request}) return HttpResponseForbidden(str(auth_err)) response_data = self.do_post(data) return JsonResponse(response_data)
Example #14
Source File: views.py From healthchecks with BSD 3-Clause "New" or "Revised" License | 5 votes |
def edit_webhook(request, code): channel = _get_channel_for_user(request, code) if channel.kind != "webhook": return HttpResponseBadRequest() if request.method == "POST": form = forms.WebhookForm(request.POST) if form.is_valid(): channel.name = form.cleaned_data["name"] channel.value = form.get_value() channel.save() return redirect("hc-p-channels", channel.project.code) else: def flatten(d): return "\n".join("%s: %s" % pair for pair in d.items()) doc = json.loads(channel.value) doc["headers_down"] = flatten(doc["headers_down"]) doc["headers_up"] = flatten(doc["headers_up"]) doc["name"] = channel.name form = forms.WebhookForm(doc) ctx = { "page": "channels", "project": channel.project, "channel": channel, "form": form, } return render(request, "integrations/webhook_form.html", ctx)
Example #15
Source File: conf.py From zentral with Apache License 2.0 | 5 votes |
def get_instance_with_secret(self, secret): try: data = signing.loads(secret, key=API_SECRET) except signing.BadSignature: raise APIAuthError("Bad secret signature") else: return self.instances[data["url"]]
Example #16
Source File: models.py From zentral with Apache License 2.0 | 5 votes |
def get_with_token(self, token): from zentral.utils.api_views import API_SECRET try: pk = int(signing.loads(token, salt="monolith", key=API_SECRET)["pk"]) except (AttributeError, KeyError, signing.BadSignature): logger.error("Bad ppd download URL signature") raise ValueError else: return self.get(pk=pk)
Example #17
Source File: forms.py From zentral with Apache License 2.0 | 5 votes |
def __init__(self, *args, **kwargs): self.session = kwargs.pop("session") self.user_agent = kwargs.pop("user_agent", None) token_data = signing.loads(self.session["verification_token"], salt="zentral_verify_token", key=django_settings.SECRET_KEY) self.redirect_to = token_data["redirect_to"] self.user = User.objects.get(pk=token_data["user_id"]) self.user.backend = token_data["auth_backend"] # used by contrib.auth.login super().__init__(*args, **kwargs)
Example #18
Source File: tokens.py From Spirit with MIT License | 5 votes |
def is_valid(self, user, signed_value): try: self.data = signing.loads(signed_value.replace(".", ":"), salt=__name__) except signing.BadSignature: return False if self.data['uid'] != self._uid(user): return False return True
Example #19
Source File: spam_util.py From Bitpoll with GNU General Public License v3.0 | 5 votes |
def get_spam_challenge_from_key(key: str, poll_id: int) -> Dict: """Returns the anti spam challenge from the key, or generates a new if it is not valid""" try: spam_data = signing.loads(key) if spam_data.get('type') != 'anti_spam' or spam_data['time'] <= time.time() - django_settings.ANTI_SPAM_CHALLENGE_TTL: return create_anti_spam_challenge(poll_id) spam_data['key'] = key return spam_data except BadSignature: return create_anti_spam_challenge(poll_id)
Example #20
Source File: views.py From django-user-management with BSD 2-Clause "Simplified" License | 5 votes |
def verify_token(self, request, *args, **kwargs): """ Use `token` to allow one-time access to a view. Set the user as a class attribute or raise an `InvalidExpiredToken`. Token expiry can be set in `settings` with `VERIFY_ACCOUNT_EXPIRY` and is set in seconds. """ User = get_user_model() try: max_age = settings.VERIFY_ACCOUNT_EXPIRY except AttributeError: max_age = self.DEFAULT_VERIFY_ACCOUNT_EXPIRY try: email_data = signing.loads(kwargs['token'], max_age=max_age) except signing.BadSignature: raise self.invalid_exception_class email = email_data['email'] try: self.user = User.objects.get_by_natural_key(email) except User.DoesNotExist: raise self.invalid_exception_class if self.user.email_verified: raise self.permission_denied_class
Example #21
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_dumps_loads(self): "dumps and loads be reversible for any JSON serializable object" objects = [ ['a', 'list'], 'a string \u2019', {'a': 'dictionary'}, ] for o in objects: self.assertNotEqual(o, signing.dumps(o)) self.assertEqual(o, signing.loads(signing.dumps(o))) self.assertNotEqual(o, signing.dumps(o, compress=True)) self.assertEqual(o, signing.loads(signing.dumps(o, compress=True)))
Example #22
Source File: views.py From allianceauth with GNU General Public License v2.0 | 5 votes |
def validate_key(self, activation_key): try: dump = signing.loads(activation_key, salt=REGISTRATION_SALT, max_age=settings.ACCOUNT_ACTIVATION_DAYS * 86400) return dump except signing.BadSignature: return None
Example #23
Source File: api_views.py From zentral with Apache License 2.0 | 5 votes |
def verify_secret(secret, module): data = {} if "$" in secret: # # There is no $ in the signed secret produced by the django signing module (base64 + :) # Try to verify a simple structure: # # secret = signed_secret$id_attribute$id_value # # Only used for now with id_attribute == SERIAL and id_value == machine serial number # Usefull to get the machine serial number when the signed_secret is shared # among a fleet of machines for easy deployment # try: secret, method, value = secret.split('$', 2) except ValueError: raise APIAuthError('Malformed secret') if method != 'SERIAL': raise APIAuthError('Invalid secret method') if not value: raise APIAuthError('Invalid secret value') data['machine_serial_number'] = value.strip().splitlines()[0] # NOT VERIFIED try: data.update(signing.loads(secret, key=API_SECRET)) except signing.BadSignature: raise APIAuthError('Bad secret signature') if data['module'] != module: raise APIAuthError('Invalid module') bu_k = data.pop('bu_k', None) if bu_k: # TODO: cache qs = BusinessUnit.objects.select_related('source') bu_list = list(qs.filter(key__startswith=bu_k, source__module='zentral.contrib.inventory').order_by('-id')) if not bu_list: logger.error('Unknown BU %s', bu_k) else: if len(bu_list) > 1: logger.error('Found multiple BU for key %s', bu_k) data['business_unit'] = bu_list[0] return data
Example #24
Source File: views.py From healthchecks with BSD 3-Clause "New" or "Revised" License | 5 votes |
def add_telegram(request): chat_id, chat_type, chat_name = None, None, None qs = request.META["QUERY_STRING"] if qs: try: chat_id, chat_type, chat_name = signing.loads(qs, max_age=600) except signing.BadSignature: return render(request, "bad_link.html") if request.method == "POST": project = _get_project_for_user(request, request.POST.get("project")) channel = Channel(project=project, kind="telegram") channel.value = json.dumps( {"id": chat_id, "type": chat_type, "name": chat_name} ) channel.save() channel.assign_all_checks() messages.success(request, "The Telegram integration has been added!") return redirect("hc-p-channels", project.code) ctx = { "page": "channels", "projects": request.profile.projects(), "chat_id": chat_id, "chat_type": chat_type, "chat_name": chat_name, "bot_name": settings.TELEGRAM_BOT_NAME, } return render(request, "integrations/add_telegram.html", ctx)
Example #25
Source File: JWT例子.py From Python_Master_Courses with GNU General Public License v3.0 | 5 votes |
def decrypt(src): """解密""" src = signing.b64_decode(src.encode()).decode() raw = signing.loads(src, key=KEY, salt=SALT) print(type(raw)) return raw
Example #26
Source File: models.py From django-db-mailer with GNU General Public License v2.0 | 5 votes |
def run_task(self): if self.done is False: from dbmail import tasks tasks.deferred_signal.apply_async( args=pickle.loads(self.args), kwargs=pickle.loads(self.kwargs), **pickle.loads(self.params) )
Example #27
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 #28
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 #29
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 #30
Source File: utils.py From karrot-backend with GNU Affero General Public License v3.0 | 5 votes |
def parse_local_part(part): # cut 'b32+' from beginning of local part signed_part = b32decode(part[4:], casefold=True) signed_part_decoded = signed_part.decode('utf8') parts = signing.loads(signed_part_decoded) if len(parts) == 2: parts.append(None) # in place of thread id return parts