API reference¶
Generated reference documentation for each package. The pages are rebuilt and published with this
site from main.
| Language | Reference | Generated by |
|---|---|---|
| TypeScript | TypeScript API | TypeDoc |
| Rust | Rust API · docs.rs | rustdoc |
| Go | pkg.go.dev | Go doc comments |
| Python | below | mkdocstrings |
| Java | Java API | Javadoc |
Build them locally with make docs (per language: make -C <lang> docs).
Python¶
Grow Codes SDK for Casdoor.
from grow_casdoor import CasdoorClient client = CasdoorClient.from_env() # doctest: +SKIP tokens = client.sign_in(username="ada@example.test", password="...") # doctest: +SKIP
PACKAGE_KEY
module-attribute
¶
Stack catalog key (value of GROW_SECRETS_PROVIDER / GROW_LOGGING_PROVIDER).
ApplicationInfo
dataclass
¶
Result of :meth:CasdoorClient.ensure_application.
AsyncCasdoorClient ¶
Asynchronous Casdoor client with the same methods as :class:CasdoorClient.
Calls run in a worker thread. Use async with or call :meth:aclose.
AsyncHttpTransport ¶
Asynchronous transport (one per async client); options as for :class:HttpTransport.
Cancelling the calling task raises :class:CancelledError (an asyncio.CancelledError
subclass) so asyncio's cancellation machinery keeps working. Every call after
:meth:aclose raises :class:CancelledError ("client is closed").
AuthenticationError ¶
Bases: CasdoorError
Credentials missing or rejected (HTTP 401).
BaseConfig
dataclass
¶
Common, immutable client settings. Durations are float seconds (timedelta accepted).
Service configs subclass this (@dataclass(frozen=True, repr=False)), override url
with the service default, add their own fields (Secret for credentials), extend
:meth:_env_values and :meth:validate, and list vendor variables in ENV_VENDOR.
CancelToken ¶
Thread-safe cancellation flag passed to sync calls as cancel=.
Cancelling interrupts an in-flight request (the call returns immediately with
:class:CancelledError; the abandoned HTTP exchange finishes in the background) and any
retry backoff sleep.
CancelledError ¶
Bases: CasdoorError, CancelledError
The caller cancelled the operation (task cancel, :class:CancelToken, client close).
Also an :class:asyncio.CancelledError so asyncio keeps treating the task as cancelled.
CasdoorClient ¶
Synchronous Casdoor client: user flows for BFFs and idempotent admin operations.
Every Casdoor {"status": "error"} answer (HTTP 200) and every OAuth error becomes a typed
:class:~grow_casdoor.CasdoorError subclass with casdoor_reason. Thread-safe; use as a
context manager or call :meth:close.
assign_roles ¶
assign_roles(user: str, roles: Sequence[str], *, organization: str | None = None, cancel: CancelToken | None = None) -> None
Add a user (org/name, name or e-mail) to roles, creating missing roles.
build_authorize_url ¶
build_authorize_url(*, redirect_uri: str, state: str, code_challenge: str, scope: str | None = None, nonce: str | None = None, extra: dict[str, str] | None = None) -> str
Browser authorize URL on public_url (code flow, PKCE S256).
ensure_application ¶
Create or align the OAuth application; returns its client credentials.
ensure_email_provider ¶
Create or align an SMTP provider and list it on the configured application.
ensure_organization ¶
Create the organization unless it exists; returns (name, created).
ensure_roles ¶
ensure_roles(names: Sequence[str], *, organization: str | None = None, cancel: CancelToken | None = None) -> list[RoleInfo]
Create every missing role.
ensure_user ¶
Create or align a user (verified e-mail by default) and assign its roles.
exchange_code ¶
exchange_code(*, code: str, code_verifier: str, redirect_uri: str, cancel: CancelToken | None = None) -> TokenSet
Exchange the authorization code from the browser redirect.
forgot_password ¶
Mail a password reset code (:class:NotFoundError for unknown e-mails).
from_env
classmethod
¶
Build from GROW_CASDOOR_* and the platform names (GROW_AUTH_ISSUER,
GROW_AUTH_CLIENT_ID/SECRET, GROW_AUTH_ORG/APP, CASDOOR_ADMIN_PASSWORD …).
health ¶
GET /api/health; never raises for an unhealthy or unreachable service.
ping ¶
Authenticated round trip with the admin credentials; latency in milliseconds.
refresh ¶
New tokens from a refresh token.
reset_password ¶
reset_password(*, email: str, code: str, new_password: str, cancel: CancelToken | None = None) -> None
Set a new password with the code from :meth:forgot_password.
send_email_verification ¶
send_email_verification(email: str, *, purpose: str = 'auto', cancel: CancelToken | None = None) -> None
Mail a verification code (purpose: auto, signup or verify).
server_version ¶
/api/get-version-info (needs the admin session).
setup_totp ¶
Start TOTP enrollment for the user of the access token.
sign_in ¶
sign_in(*, username: str, password: str, totp_code: str | None = None, recovery_code: str | None = None, redirect_uri: str | None = None, cancel: CancelToken | None = None) -> TokenSet
Headless password sign-in (code flow + PKCE). Raises :class:MfaRequiredError and
:class:EmailNotVerifiedError.
sign_out ¶
End the Casdoor session of the token. Idempotent.
sign_up ¶
sign_up(*, email: str, password: str, username: str | None = None, display_name: str | None = None, email_code: str | None = None, cancel: CancelToken | None = None) -> SignUpResult
Register a user (/api/signup); email_code when the application requires it.
verify_email ¶
Check the code and mark the user's e-mail verified.
verify_totp ¶
verify_totp(*, access_token: str, secret: str, code: str, recovery_code: str, cancel: CancelToken | None = None) -> None
Verify the first TOTP code, then enable TOTP.
CasdoorConfig
dataclass
¶
Bases: BaseConfig
Immutable settings for :class:~grow_casdoor.CasdoorClient.
Environment (from_env): GROW_CASDOOR_<NAME> first, then the platform names.
======================== ===========================================================
Field Variables (in order)
======================== ===========================================================
url URL, GROW_AUTH_ISSUER, GROW_AUTH_PUBLIC_URL,
CASDOOR_URL
public_url PUBLIC_URL, GROW_AUTH_PUBLIC_URL (default url)
client_id CLIENT_ID, GROW_AUTH_CLIENT_ID
client_secret CLIENT_SECRET, GROW_AUTH_CLIENT_SECRET
organization ORG, GROW_AUTH_ORG
application APP, GROW_AUTH_APP
redirect_uri REDIRECT_URL, GROW_AUTH_REDIRECT_URL
scope SCOPE (default openid profile email)
admin_username ADMIN_USERNAME, CASDOOR_ADMIN_USERNAME (default admin)
admin_password ADMIN_PASSWORD, CASDOOR_ADMIN_PASSWORD
admin_organization ADMIN_ORG (default built-in)
admin_application ADMIN_APP (default app-built-in)
require_verified_email REQUIRE_VERIFIED_EMAIL (default True)
======================== ===========================================================
CasdoorReason ¶
Machine-readable reasons attached to normalized Casdoor errors (err.casdoor_reason).
CasdoorUser
dataclass
¶
A Casdoor user (subset).
ConfigError ¶
Bases: CasdoorError
Invalid or missing configuration.
ConflictError ¶
Bases: CasdoorError
Conflict or failed precondition (HTTP 409, 412, CAS mismatch).
EmailNotVerifiedError ¶
EnvReader ¶
Reads GROW_<KEY_UPPER>_<NAME> and vendor variables from an injectable mapping.
Every getter returns None when no variable is set (empty strings count as unset). A
present but invalid value raises :class:ConfigError that names the variable, never its
value.
ErrorCode ¶
Bases: str, Enum
Canonical error codes; the value is the wire form used by the conformance suite.
ErrorInfo
dataclass
¶
Passed to Hooks.on_error; error is the (redacted) SDK error.
HealthStatus
dataclass
¶
Result of health(); status is ok/degraded/unhealthy/unreachable or a vendor word.
Hooks
dataclass
¶
Optional callbacks invoked on every attempt. Exceptions raised by hooks are ignored.
HttpTransport ¶
Synchronous transport (one per client).
Service options (all optional):
request_id_headers: vendor request id headers, checked before :data:REQUEST_ID_HEADERS.retry_after_headers: headers read (in order) for the delay a 429/503 response asks for; default("retry-after",), e.g.("retry-after", "x-ratelimit-reset"). See :func:retry_after_from_headers.error_mapper:mapper(error, response)returns a service-specific error for an HTTP error response (orNoneto keep the default). The mapped error is whatHooks.on_error, the retry planner (retry_after) and the caller see; whether a status is retried stays the SPEC rule. Exceptions raised by the mapper are logged and ignored.
Every call after :meth:close raises :class:CancelledError ("client is closed").
LoggerLike ¶
Bases: Protocol
Structured logger interface accepted in configuration (SPEC Logger).
MfaRequiredError ¶
NotFoundError ¶
Bases: CasdoorError
Missing record (HTTP 404).
PermissionDeniedError ¶
Bases: CasdoorError
Authenticated but not allowed (HTTP 403).
Pkce
dataclass
¶
A PKCE pair (RFC 7636, S256).
RateLimitError ¶
Bases: CasdoorError
Too many requests (HTTP 429); retry_after holds the requested delay when known.
Request
dataclass
¶
One logical API call (possibly several attempts).
path is joined to the base URL ({name} style values must already be encoded; use
:func:urllib.parse.quote); an absolute http:///https:// URL is used as is (for
pagination links the service returns; the default headers, config.headers included,
are sent there too, so only pass URLs of the same service). json is encoded when not
None; content sends raw bytes. idempotent overrides the method rule; an
idempotency_key sends the Idempotency-Key header and marks the request idempotent.
raise_for_status=False returns error responses instead of raising (retries still
apply). Statuses in allow_status are expected answers (a 404 that carries data, a
health endpoint's 503): the response is returned at once, like a success, without retries
or on_error.
RequestInfo
dataclass
¶
Passed to Hooks.on_request; url and headers are redacted.
ResourceRegistry ¶
Holds :class:Stoppable objects (or plain closers such as handle.shutdown);
:meth:stop_all stops each once, ignoring errors.
A client owns one registry and calls :meth:stop_all from close(). After that,
:meth:ensure_open and :meth:register with operation= raise :class:CancelledError
("<operation>: client is closed", SPEC 2.4): client-bound entry points that do no request
of their own, such as init_tracing or remote_sampler, use them to fail with
CANCELLED on a closed client.
ensure_open ¶
Raise :class:CancelledError ("<operation>: client is closed") once closed.
register ¶
Track item; when the registry is already closed the item is stopped now.
With operation a closed registry also raises :class:CancelledError after stopping
item, so a resource created while close() runs is never handed to the caller.
Response
dataclass
¶
A completed HTTP response (body fully read).
ResponseInfo
dataclass
¶
Passed to Hooks.on_response; headers are the redacted response headers (rate
limit headers and the like stay readable).
RetryPolicy
dataclass
¶
Retry settings. Durations are seconds (datetime.timedelta is accepted).
Backoff for retry n (0-based) is full jitter:
random(0, min(max_backoff, initial_backoff * multiplier ** n)).
random returns a float in [0, 1); inject it in tests for deterministic sleeps.
RoleInfo
dataclass
¶
Result entry of :meth:CasdoorClient.ensure_roles.
Secret ¶
Wraps a credential so it never shows up in str/repr/logs.
s = Secret("hunter2") str(s), s.reveal() ('[REDACTED]', 'hunter2')
SignUpResult
dataclass
¶
Result of :meth:CasdoorClient.sign_up.
SmtpSettings
dataclass
¶
SMTP settings for :meth:CasdoorClient.ensure_email_provider.
TimeoutError ¶
Bases: CasdoorError
A connect, request or total deadline was exceeded (also HTTP 408, 504).
TlsConfig
dataclass
¶
TLS settings. insecure_skip_verify is for tests only and logs a warning once.
TokenSet
dataclass
¶
OAuth tokens returned by sign-in, refresh and code exchange.
from_response
classmethod
¶
Build from a token endpoint body.
TotpSetup
dataclass
¶
Result of :meth:CasdoorClient.setup_totp (show the secret once, never log it).
UnavailableError ¶
Bases: CasdoorError
Network error or server unavailable (HTTP 500, 502, 503).
UnsupportedError ¶
Bases: CasdoorError
The service or deployment does not offer this capability (HTTP 501, missing API).
ValidationError ¶
Bases: CasdoorError
Bad input (HTTP 400, 413, 422, other 4xx, client-side validation).
apoll_until
async
¶
apoll_until(fn: Callable[[], Awaitable[T | None]], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', clock: Callable[[], float] = time.monotonic) -> T
Async :func:poll_until; fn is an async callable.
casdoor_reason ¶
The casdoor_reason of a normalized error, else None.
error_for_code ¶
Return the error class for a code (ErrorCode member or wire value).
error_from_status ¶
error_from_status(status: int, operation: str, *, content: bytes = b'', headers: Headers | None = None, known_secrets: list[str] | None = None, retry_after: float | None = None, request_id_headers: Sequence[str] = ()) -> ServiceError
Map an HTTP error status to the SPEC 2.1 error with a redacted, truncated message.
request_id_headers are checked before the default :data:REQUEST_ID_HEADERS.
get_logger ¶
The package logger (LOGGER_NAME), silent by default (NullHandler).
parse_bool ¶
Parse true/false/1/0/yes/no/on/off (case-insensitive); raise :class:ValueError.
parse_duration ¶
Parse a duration into seconds.
Accepts integer milliseconds ("1500" → 1.5) or Go-style units ("500ms", "10s",
"2m", "1h", "1m30s"). Raises :class:ValueError for anything else.
parse_retry_after ¶
Parse Retry-After as delta seconds or an HTTP-date; return seconds (>= 0) or None.
pkce_challenge ¶
S256 challenge of a verifier: base64url(sha256(verifier)).
poll_until ¶
poll_until(fn: Callable[[], T | None], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic) -> T
Call fn every interval_s until it returns a ready value; return that value.
A value is ready when it is not None and predicate(value) is true (without a
predicate: not an empty container). Retryable SDK errors raised by fn are remembered
and polling continues; other errors propagate. Raises :class:TimeoutError after timeout_s.
redact_fields ¶
Recursively redact values whose key looks sensitive in nested mappings and lists.
redact_headers ¶
Copy of headers with sensitive values replaced by [REDACTED].
redact_text ¶
Replace every known secret value (length >= 4) in text with [REDACTED].
redact_url ¶
Redact user info and every query value (all values, not only sensitive ones).
Query names are kept so the URL stays useful in logs.
retry_after_from_headers ¶
retry_after_from_headers(headers: Headers | Mapping[str, str], names: Sequence[str] = RETRY_AFTER_HEADERS, *, now: Callable[[], float] = time.time) -> float | None
Server requested delay in seconds from the first of names that parses.
Retry-After is delta seconds or an HTTP-date. Other headers (X-RateLimit-Reset,
RateLimit-Reset …) may be delta seconds or a Unix timestamp in seconds or milliseconds;
timestamps are turned into the remaining delay.
to_seconds ¶
Normalise a duration given as float seconds or :class:datetime.timedelta.
totp_code ¶
Current TOTP code (RFC 6238, SHA-1, 6 digits, 30 s) for tests and e2e helpers.
truncate ¶
Truncate text to limit characters (adds an ellipsis when cut).
user_agent ¶
grow-codes-<key>/<version> (python) plus <suffix> when given.