Integrations

Django

Protect Django signup views and expensive actions with the Python SDK.

Call isCredible from the Django view that creates accounts, before you save the user or send any email.

Install#

pip install is-credible

Add ISCREDIBLE_API_KEY to your server's environment. The package needs Python 3.9 or later and has no dependencies.

A small helper#

Create the client once at import time and reuse it. It is thread-safe.

import logging
import os

from iscredible import IsCredible, IsCredibleError, decide

log = logging.getLogger(__name__)
client = IsCredible(api_key=os.environ["ISCREDIBLE_API_KEY"], timeout=3, max_retries=1)


def client_ip(request):
    # Behind a proxy or load balancer, use the address it forwards. Otherwise REMOTE_ADDR.
    forwarded = request.META.get("HTTP_X_FORWARDED_FOR")
    return forwarded.split(",")[0].strip() if forwarded else request.META.get("REMOTE_ADDR")


def screen(data, scenario_id=None):
    """Returns APPROVE, REVIEW or DENY. Returns APPROVE when the check can't run (fail open)."""
    try:
        action, _reasons = decide(client.verify(data, scenario_id=scenario_id))
        return action
    except IsCredibleError as error:
        if error.status == 402:
            log.error("isCredible: no active plan, checks are paused (%s)", error.code)
        elif error.status == 429:
            log.warning("isCredible: rate limit or daily quota reached")
        else:
            log.warning("isCredible unavailable, allowing the request: %s", error)
    except ValueError as error:  # invalid input, e.g. a malformed email
        log.warning("isCredible input rejected: %s", error)
    return "APPROVE"

Only trust X-Forwarded-For when your app runs behind a proxy you control, because clients can set it themselves.

Protect the signup view#

from django.contrib.auth import get_user_model
from django.http import JsonResponse
from django.views.decorators.http import require_POST

from .risk import client_ip, screen


@require_POST
def signup(request):
    email = request.POST["email"]

    action = screen({
        "email": email,
        "ip": client_ip(request),
        "userAgent": request.META.get("HTTP_USER_AGENT"),
        "deviceId": request.POST.get("deviceId") or None,
        "accountCreation": True,
    })

    if action == "DENY":
        return JsonResponse({"error": "We couldn't create your account."}, status=403)

    user = get_user_model().objects.create_user(
        username=email, email=email, password=request.POST["password"],
        is_active=(action == "APPROVE"),  # REVIEW: activate after email verification
    )
    return JsonResponse({"id": user.pk})

None values are fine: fields you don't have are left out of the checks. Never send the password to isCredible.

Protect expensive actions#

Check usage before costly work. check_usage caches each answer and only calls the API when a check is due.

from iscredible import IsCredibleError
from .risk import client, client_ip


def generate(request):
    try:
        decision = client.check_usage(
            str(request.user.pk),
            {"metric": "ai_tokens", "used": tokens_used_this_month(request.user), "limit": 100000},
            {"ip": client_ip(request)},
        )
        if decision["action"] == "DENY":
            return JsonResponse({"error": "Free limit reached"}, status=429)
    except IsCredibleError:
        pass  # fail open
    ...

Acting on the decision#

DecisionSuggested action
APPROVECreate an active account
REVIEWCreate it inactive, or hold back free credits, until the email or phone is verified
DENYReturn a neutral error. Don't say which check fired

Errors and limits#

SituationWhat to do
Timeout, network error or 5xxThe SDK retries, then raises IsCredibleError. Fail open and log it
429 rate limit or daily quotaThe SDK retries with backoff, then raises. Fail open, and upgrade if it happens every day
402 with code trial_ended or subscription_endedYour account has no active plan. Fail open and choose a plan in the dashboard
401 or 403The key is wrong, revoked or missing. Fix it; fail open meanwhile

See the Python SDK for every option.