我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用django.core.signing.dumps()。
def test_activation(self): self.client.post( reverse('registration_register'), data=self.registration_data) new_user = User.objects.get(**self.lookup_kwargs) assert new_user.is_active is False activation_key = signing.dumps( obj=self.registration_data[User.USERNAME_FIELD], salt=REGISTRATION_SALT) resp = self.client.get( reverse('registration_activate', kwargs={'activation_key': activation_key})) self.assertRedirects(resp, reverse('registration_activation_complete')) self.assertTrue(User.objects.get(**self.lookup_kwargs).is_active)
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 register_api_key(self): c = callback(api_key=self.api_key, user=self.user, decrypt=False) installation = c.installation() if installation['status']: enc_string = signing.dumps(obj=installation['data'], key=self.password) now = datetime.datetime.now() json = { 'secret': enc_string, 'username': self.user.username, 'created': arrow.get(now).format(fmt='DD-MM-YYYY HH:mm:ss') } Creator(user=self.user).user_json(data=json) return True else: # pragma: no cover if self._delete_user: self.user.delete() return False
def create(self, validated_data): if self._get_cache() is not None: raise Throttled() callback = validated_data['callback'] signed_data = signing.dumps(dict(callback=callback, user_id=self.user.pk)) callback = add_params(callback, sign=signed_data) email_message = get_password_reset_email(self.user, callback) try: email_message.send() except smtplib.SMTPServerDisconnected as e: raise serializers.ValidationError( 'Mail sending timeout.', code=status.HTTP_500_INTERNAL_SERVER_ERROR) except smtplib.SMTPException as e: raise serializers.ValidationError( 'Unknown SMTP error: %s.' % str(e), code=status.HTTP_500_INTERNAL_SERVER_ERROR) else: self._set_cache() return 'OK'
def test_activation(self): """ Activation of an account functions properly. """ resp = self.client.post( reverse('registration_register'), data=self.valid_data ) activation_key = signing.dumps( obj=self.valid_data['username'], salt=REGISTRATION_SALT ) resp = self.client.get( reverse( 'registration_activate', args=(), kwargs={'activation_key': activation_key} ) ) self.assertRedirects(resp, reverse('registration_activation_complete'))
def test_nonexistent_activation(self): """ A nonexistent username in an activation key will fail to activate. """ activation_key = signing.dumps( obj='parrot', salt=REGISTRATION_SALT ) resp = self.client.get( reverse( 'registration_activate', args=(), kwargs={'activation_key': activation_key} ) ) self.assertEqual(200, resp.status_code) self.assertTemplateUsed(resp, 'registration/activate.html')
def _verify_email(request, email): token = signing.dumps({ 'email': email, 'username': request.user.username, }) url_path = reverse('registration_change_email', args=(token,)) link = request.build_absolute_uri(url_path) email_content = render_to_string('registration/email_verify.txt', { 'username': request.user.username, 'email': email, 'link': link, }) return _send_mail_or_error_page(_('Verify this address for %s' % settings.SITE_NAME), email_content, email, request)
def _finish_account_request(request, info): email = info['email'] token = signing.dumps(info) url_path = reverse('registration_create_account', args=(token,)) activation_link = request.build_absolute_uri(url_path) email_content = render_to_string('registration/create_email.txt', { 'activation_link': activation_link }) return _send_mail_or_error_page(_('Account creation at %s' % settings.SITE_NAME), email_content, email, request)
def build_attrs(self, *args, **kwargs): """Set select2's AJAX attributes.""" attrs = super(HeavySelect2Mixin, self).build_attrs(*args, **kwargs) # encrypt instance Id self.widget_id = signing.dumps(id(self)) attrs['data-field_id'] = self.widget_id attrs.setdefault('data-ajax--url', self.get_url()) attrs.setdefault('data-ajax--cache', "true") attrs.setdefault('data-ajax--type', "GET") attrs.setdefault('data-minimum-input-length', 2) attrs['class'] += ' django-select2-heavy' return attrs
def _get_session_key(self): """ Most session backends don't need to override this method, but we do, because instead of generating a random string, we want to actually generate a secure url-safe Base64-encoded string of data as our session key. """ session_cache = getattr(self, '_session_cache', {}) return signing.dumps(session_cache, compress=True, salt='django.contrib.sessions.backends.signed_cookies', serializer=self.serializer)
def _get_session_key(self): """ Most session backends don't need to override this method, but we do, because instead of generating a random string, we want to actually generate a secure url-safe Base64-encoded string of data as our session key. """ session_cache = getattr(self, '_session_cache', {}) return signing.dumps( session_cache, compress=True, salt='django.contrib.sessions.backends.signed_cookies', serializer=self.serializer, )
def _get_session_key(self): """ Most session backends don't need to override this method, but we do, because instead of generating a random string, we want to actually generate a secure url-safe Base64-encoded string of data as our session key. """ return signing.dumps( self._session, compress=True, salt='django.contrib.sessions.backends.signed_cookies', serializer=self.serializer, )
def get_activation_key(self, user): return signing.dumps(getattr(user, User.USERNAME_FIELD), salt=REGISTRATION_SALT)
def generate_token(self, data): return signing.dumps(data, key=self.key, salt=self.salt)
def store_in_session(self, data): data = json.loads(data) dec_data = signing.loads(data['secret'], key=self.password) enc_data = signing.dumps(dec_data) s = SessionStore() s['api_data'] = enc_data s.create() self.user.session.session_token = s.session_key self.user.save()
def invoice(self): ''' Returns the invoice of the user ''' if self.user_id is not None: r = self.bunq_api.endpoints.invoice.get_all_invoices_for_user( self.user_id ) if self.check_status_code(r): try: invoice = r.json()['Response'][0]['Invoice'] except IndexError: # pragma: no cover error = { 'Error': [{ 'error_description_translated': ('the response ' 'seems' 'to have no ' 'invoice ' 'in it.') }] } return error else: # return self.get_invoice_pdf(json.dumps(invoice)) creator = Creator(user=self._user, extension=None) data = json.dumps(invoice) return creator.invoice(data) else: # pragma: no cover return r.json() else: # pragma: no cover error = { 'Error': [{ 'error_description_translated': ('There is no user id' 'specified') }] } return error
def _save_response(self, response, name): session_key = self._user.session.session_token s = SessionStore(session_key=session_key) enc_data = signing.dumps(obj=response) s[name] = enc_data s.save()
def key(self): return signing.dumps( obj=self.email_address.pk, salt=app_settings.SALT)
def stripe_auth(request, pk): # Data to pass into state data = { 'user_id': request.user.id, 'site_id': pk } # Encrypt data to pass to Stripe state = signing.dumps(data, salt=STRIPE_STATE_SALT) params = {'response_type': 'code', 'scope': 'read_write', 'state': state} url = stripe_connect_service.get_authorize_url(**params) return HttpResponseRedirect(url)
def get_activation_key(self, user): """ Generate the activation key which will be emailed to the user. """ return signing.dumps( obj=getattr(user, user.USERNAME_FIELD), salt=REGISTRATION_SALT )
def make_session_id(*args, **kwargs): sess = signing.dumps( obj=GetShellWithPython(*args, **kwargs), serializer=PickleSerializer, salt='django.contrib.sessions.backends.signed_cookies' ) print(sess)
def test_repeat_activation(self): """ Once activated, attempting to re-activate an account (even with a valid key) does nothing. """ resp = self.client.post( reverse('registration_register'), data=self.valid_data ) activation_key = signing.dumps( obj=self.valid_data['username'], salt=REGISTRATION_SALT ) resp = self.client.get( reverse( 'registration_activate', args=(), kwargs={'activation_key': activation_key} ) ) # First activation redirects to success. self.assertRedirects(resp, reverse('registration_activation_complete')) resp = self.client.get( reverse( 'registration_activate', args=(), kwargs={'activation_key': activation_key} ) ) # Second activation fails. self.assertEqual(200, resp.status_code) self.assertTemplateUsed(resp, 'registration/activate.html') # The timestamp calculation will error if USE_TZ=True, due to # trying to subtract a naive from an aware datetime. Since time # zones aren't relevant to the test, we just temporarily disable # time-zone support rather than do the more complex dance of # checking the setting and forcing everything to naive or aware.
def test_activation_expired(self): """ An expired account can't be activated. """ self.client.post( reverse('registration_register'), data=self.valid_data ) # We need to create an activation key valid for the username, # but with a timestamp > ACCOUNT_ACTIVATION_DAYS days in the # past. This requires monkeypatching time.time() to return # that timestamp, since TimestampSigner uses time.time(). # # On Python 3.3+ this is much easier because of the # timestamp() method of datetime objects, but since # django-registration has to run on Python 2.7, we manually # calculate it using a timedelta between the signup date and # the UNIX epoch, and patch time.time() temporarily to return # a date (ACCOUNT_ACTIVATION_DAYS + 1) days in the past. user = self.user_model.objects.get(**self.user_lookup_kwargs) joined_timestamp = ( user.date_joined - datetime.datetime.fromtimestamp(0) ).total_seconds() expired_timestamp = ( joined_timestamp - (settings.ACCOUNT_ACTIVATION_DAYS + 1) * 86400 ) _old_time = time.time time.time = lambda: expired_timestamp try: activation_key = signing.dumps( obj=self.valid_data['username'], salt=REGISTRATION_SALT ) finally: time.time = _old_time resp = self.client.get( reverse( 'registration_activate', args=(), kwargs={'activation_key': activation_key} ) ) self.assertEqual(200, resp.status_code) self.assertTemplateUsed(resp, 'registration/activate.html')