Python django.core.signing.dumps() Examples

The following are 30 code examples of django.core.signing.dumps(). 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 vote down vote up
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: models.py    From zentral with Apache License 2.0 6 votes vote down vote up
def serialize_catalog(self, tags=None):
        pkginfo_list = []

        # the repository catalogs
        for catalog in self.catalogs(tags):
            for pkginfo in catalog.iter_pkginfos():
                pkginfo_list.append(pkginfo)

        # the sub manifests attachments
        for sma in SubManifestAttachment.objects.newest().filter(sub_manifest__in=self.sub_manifests(tags)):
            pkginfo_list.append(sma.get_pkg_info())

        # the enrollment packages
        for enrollment_package in self.enrollment_packages(tags).values():
            pkginfo_list.append(enrollment_package.get_pkg_info())

        # include the catalog with all the printers for autoremove
        for printer in self.printer_set.all():
            pkginfo_list.append(printer.pkg_info)

        return plistlib.dumps(pkginfo_list)

    # the manifest 
Example #3
Source File: views.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #4
Source File: views.py    From django-register-sample with MIT License 6 votes vote down vote up
def form_valid(self, form):
        """仮登録と本登録用メールの発行."""
        # 仮登録と本登録の切り替えは、is_active属性を使うと簡単です。
        # 退会処理も、is_activeをFalseにするだけにしておくと捗ります。
        user = form.save(commit=False)
        user.is_active = False
        user.save()

        # アクティベーションURLの送付
        current_site = get_current_site(self.request)
        domain = current_site.domain
        context = {
            'protocol': 'https' if self.request.is_secure() else 'http',
            'domain': domain,
            'token': dumps(user.pk),
            'user': user,
        }

        subject = render_to_string('register/mail_template/create/subject.txt', context)
        message = render_to_string('register/mail_template/create/message.txt', context)

        user.email_user(subject, message)
        return redirect('register:user_create_done') 
Example #5
Source File: views.py    From django-register-sample with MIT License 6 votes vote down vote up
def form_valid(self, form):
        user = self.request.user
        new_email = form.cleaned_data['email']

        # URLの送付
        current_site = get_current_site(self.request)
        domain = current_site.domain
        context = {
            'protocol': 'https' if self.request.is_secure() else 'http',
            'domain': domain,
            'token': dumps(new_email),
            'user': user,
        }

        subject = render_to_string('register/mail_template/email_change/subject.txt', context)
        message = render_to_string('register/mail_template/email_change/message.txt', context)
        send_mail(subject, message, None, [new_email])

        return redirect('register:email_change_done') 
Example #6
Source File: views.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def add_opsgenie(request, code):
    project = _get_project_for_user(request, code)

    if request.method == "POST":
        form = forms.AddOpsGenieForm(request.POST)
        if form.is_valid():
            channel = Channel(project=project, kind="opsgenie")
            v = {"region": form.cleaned_data["region"], "key": form.cleaned_data["key"]}
            channel.value = json.dumps(v)
            channel.save()

            channel.assign_all_checks()
            return redirect("hc-p-channels", project.code)
    else:
        form = forms.AddOpsGenieForm()

    ctx = {"page": "channels", "project": project, "form": form}
    return render(request, "integrations/add_opsgenie.html", ctx) 
Example #7
Source File: views.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def add_pdc_complete(request, code, state):
    if "pd" not in request.session:
        return HttpResponseBadRequest()

    project = _get_project_for_user(request, code)

    session_state = request.session.pop("pd")
    if session_state != state:
        return HttpResponseBadRequest()

    if request.GET.get("error") == "cancelled":
        messages.warning(request, "PagerDuty setup was cancelled.")
        return redirect("hc-p-channels", project.code)

    channel = Channel(kind="pd", project=project)
    channel.value = json.dumps(
        {
            "service_key": request.GET.get("service_key"),
            "account": request.GET.get("account"),
        }
    )
    channel.save()
    channel.assign_all_checks()
    messages.success(request, "The PagerDuty integration has been added!")
    return redirect("hc-p-channels", project.code) 
Example #8
Source File: spam_util.py    From Bitpoll with GNU General Public License v3.0 6 votes vote down vote up
def create_anti_spam_challenge(poll_id: int) -> Dict:
    """Creates a anti spam challenge"""
    rand = random.SystemRandom()
    x = rand.randint(1, 10)
    y = rand.randint(1, 10)
    op = rand.choice(['+', '-', '*'])
    return {'key': signing.dumps({
                'type': 'anti_spam',
                'x': x,
                'y': y,
                'op': op,
                'poll_id': poll_id,
                'time': time.time()
            }),
        'x': x,
        'y': y,
        'op': op,
    } 
Example #9
Source File: utils.py    From karrot-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def generate_token(user, group=None, conversation=None, thread=None, notification_type=None):
    data = {'u': user.id}
    if group:
        data.update({
            'g': group.id,
            'gn': group.name,
        })
    if conversation:
        data.update({'c': conversation.id})
    elif thread:
        if not thread.is_first_in_thread():
            raise Exception('your thread is not a thread!')
        data.update({'t': thread.id})
    if notification_type:
        data.update({'n': notification_type})
    return signing.dumps(data) 
Example #10
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 #11
Source File: views.py    From zentral with Apache License 2.0 5 votes vote down vote up
def get_context_data(self, **kwargs):
        ctx = super().get_context_data()
        ctx["u2f_challenge_json"] = VerifyU2FForm(session=self.request.session).set_u2f_challenge()
        if "u2f_challenge" in self.request.session:
            ctx["u2f_challenge_json"] = json.dumps(self.request.session["u2f_challenge"])
        return ctx 
Example #12
Source File: test_add_telegram.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_it_works(self):
        payload = signing.dumps((123, "group", "My Group"))

        self.client.login(username="alice@example.org", password="password")
        form = {"project": str(self.project.code)}
        r = self.client.post(self.url + "?" + payload, form)
        self.assertRedirects(r, self.channels_url)

        c = Channel.objects.get()
        self.assertEqual(c.kind, "telegram")
        self.assertEqual(c.telegram_id, 123)
        self.assertEqual(c.telegram_type, "group")
        self.assertEqual(c.telegram_name, "My Group")
        self.assertEqual(c.project, self.project) 
Example #13
Source File: models.py    From zentral with Apache License 2.0 5 votes vote down vote up
def serialize(self, tags):
        data = {'catalogs': [self.get_catalog_munki_name()],
                'included_manifests': []}

        # include the sub manifests
        for sm in self.sub_manifests(tags):
            data['included_manifests'].append(sm.get_munki_name())

        # add default managed installs
        data['managed_installs'] = monolith_conf.get_default_managed_installs()

        # loop on the configured enrollment package builders
        enrollment_packages = self.enrollment_packages(tags)
        for builder, builder_config in monolith_conf.enrollment_package_builders.items():
            update_for = builder_config["update_for"]
            if builder in enrollment_packages:
                # add the package it is an update_for to the managed_installs
                if update_for not in data['managed_installs']:
                    data['managed_installs'].append(update_for)
            else:
                if update_for not in data['managed_installs']:
                    # the package it is an update_for is not in the managed_installs, remove it.
                    data.setdefault('managed_uninstalls', []).append(update_for)

        # include only the matching active printers as managed installs
        for printer in self.printers(tags):
            data.setdefault("managed_installs", []).append(printer.get_pkg_info_name())

        return plistlib.dumps(data) 
Example #14
Source File: models.py    From zentral with Apache License 2.0 5 votes vote down vote up
def serialize(self):
        condition_d = {}
        featured_items = set()
        included_sma_names = set()
        for key, key_d in self.pkg_info_dict()['keys'].items():
            for _, smo in key_d['key_list']:
                if smo.condition:
                    condition = smo.condition.predicate
                else:
                    condition = None
                name = smo.get_name()
                condition_d.setdefault(condition, {}).setdefault(key, []).append(name)
                if key != "managed_uninstalls" and smo.featured_item:
                    featured_items.add(name)
                if isinstance(smo, SubManifestAttachment):
                    included_sma_names.add(smo.name)
        data = {}
        if featured_items:
            data["featured_items"] = sorted(featured_items)
        for condition, condition_key_d in condition_d.items():
            if condition is None:
                data.update(condition_key_d)
            else:
                condition_key_d["condition"] = condition
                data.setdefault("conditional_items", []).append(condition_key_d)
        # force uninstall on the not included attachments
        qs = SubManifestAttachment.objects.filter(sub_manifest=self).exclude(name__in=included_sma_names)
        data.setdefault('managed_uninstalls', []).extend({sma.get_name() for sma in qs})
        return plistlib.dumps(data) 
Example #15
Source File: conf.py    From zentral with Apache License 2.0 5 votes vote down vote up
def get_instances_with_secrets(self):
        for instance in self.instances.values():
            secret = signing.dumps({"url": instance["puppetdb_url"]}, key=API_SECRET)
            path = reverse("puppet:post_report", args=(secret,))
            url = "{}{}".format(settings['api']['tls_hostname'], path)
            yield instance, url 
Example #16
Source File: api_views.py    From zentral with Apache License 2.0 5 votes vote down vote up
def make_secret(module, business_unit=None):
    data = {'module': module}
    if business_unit:
        data['bu_k'] = business_unit.get_short_key()
    return signing.dumps(data, key=API_SECRET) 
Example #17
Source File: views.py    From healthchecks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #18
Source File: views.py    From zentral with Apache License 2.0 5 votes vote down vote up
def get_context_data(self, **kwargs):
        ctx = super().get_context_data()
        ctx["u2f_challenge_json"] = json.dumps(self.request.session["u2f_challenge"])
        return ctx 
Example #19
Source File: tokens.py    From Spirit with MIT License 5 votes vote down vote up
def generate(self, user, data=None):
        """
        Django signer uses colon (:) for components separation
        JSON_object:hash_first_component:hash_secret, all base64 encoded
        that aint so url-safe, so Im replacing them by dots (.)

        base64 encode characters ref: 0-9, A-Z, a-z, _, -
        """
        data = data or {}
        data.update({'uid': self._uid(user), })
        return signing.dumps(data, salt=__name__).replace(":", ".") 
Example #20
Source File: forms.py    From ontask_b with MIT License 5 votes vote down vote up
def clean(self) -> Dict:
        """Store the fields in the Form Payload"""
        form_data = super().clean()

        if 'db_password' in self.fields:
            self.store_fields_in_dict([
                ('db_password', signing.dumps(form_data['db_password']))])

        if 'db_table' in self.fields:
            self.store_fields_in_dict([('db_table', None)])

        return form_data 
Example #21
Source File: signed_cookies.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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) 
Example #22
Source File: views.py    From Bitpoll with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #23
Source File: views.py    From Bitpoll with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #24
Source File: signed_cookies.py    From python2017 with MIT License 5 votes vote down vote up
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,
        ) 
Example #25
Source File: mixins.py    From django-user-management with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def generate_validation_token(self):
        """Generate user token for account validation."""
        data = {'email': self.email}
        return signing.dumps(data) 
Example #26
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #27
Source File: views.py    From allianceauth with GNU General Public License v2.0 5 votes vote down vote up
def get_activation_key(self, user):
        return signing.dumps(obj=[getattr(user, User.USERNAME_FIELD), user.email], salt=REGISTRATION_SALT) 
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: oauth.py    From heltour with MIT License 5 votes vote down vote up
def _encode_state(state):
    # This state isn't actually security critical, but it's just good practice to sign
    return signing.dumps(state) 
Example #30
Source File: forms.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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