casdoor

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 35 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package casdoor is the Grow Codes SDK for Casdoor.

Create a client from the environment (GROW_CASDOOR_URL, GROW_CASDOOR_TOKEN, ...) or from a Config literal:

client, err := casdoor.NewClientFromEnv()
if err != nil {
	return err
}
defer client.Close()
status, err := client.Health(ctx)

Every error is an *Error; compare codes with errors.Is against the Err* sentinels (errors.Is(err, casdoor.ErrNotFound)). Credentials are wrapped in Secret and never appear in errors, hooks or logs.

Casdoor is a trademark of its owner (Casdoor / Casbin organization); this package is not affiliated with or endorsed by it.

Index

Constants

View Source
const (
	ReasonEmptyCredential    = "empty_credential"    //nolint:gosec // reason name, not a credential
	ReasonInvalidCredentials = "invalid_credentials" //nolint:gosec // reason name, not a credential
	ReasonLoginRequired      = "login_required"
	ReasonForbidden          = "forbidden"
	ReasonLocked             = "locked"
	ReasonRateLimited        = "rate_limited"
	ReasonNotFound           = "not_found"
	ReasonAlreadyExists      = "already_exists"
	ReasonNotEnabled         = "not_enabled"
	ReasonMFARequired        = "mfa_required"
	ReasonEmailNotVerified   = "email_not_verified"
	ReasonMaskedObject       = "masked_object"
	ReasonInvalidGrant       = "invalid_grant"
	ReasonInvalidClient      = "invalid_client"
	ReasonOther              = "other"
)

Reason values attached to normalized Casdoor errors (see ReasonOf).

View Source
const (
	DefaultConnectTimeout = 10 * time.Second
	DefaultRequestTimeout = 30 * time.Second
	DefaultTotalTimeout   = 120 * time.Second
)

Defaults of the common configuration fields (SPEC §2.2).

View Source
const (
	DefaultMaxRetries     = 3
	DefaultInitialBackoff = 100 * time.Millisecond
	DefaultMaxBackoff     = 10 * time.Second
	DefaultMultiplier     = 2.0
	DefaultMaxRetryAfter  = 60 * time.Second
)

Retry policy defaults (SPEC §2.3).

View Source
const DefaultScope = "openid profile email"

DefaultScope is the OAuth scope requested by sign-in and the authorize URL.

View Source
const DefaultURL = "http://127.0.0.1:8000"

DefaultURL is the default endpoint of Casdoor.

View Source
const EnvPrefix = "GROW_CASDOOR_"

EnvPrefix is the prefix of this package's environment variables.

View Source
const Redacted = "[REDACTED]"

Redacted replaces every sensitive value.

View Source
const UserAgent = "grow-codes-casdoor/" + Version + " (go)"

UserAgent is the standard User-Agent of this package.

View Source
const Version = "0.1.0" // x-release-please-version

Version is the package version (updated by release-please).

Variables

View Source
var (
	ErrConfig           = &Error{Code: ErrorCodeConfig, Message: "configuration error"}
	ErrAuthentication   = &Error{Code: ErrorCodeAuthentication, Message: "authentication failed"}
	ErrPermissionDenied = &Error{Code: ErrorCodePermissionDenied, Message: "permission denied"}
	ErrNotFound         = &Error{Code: ErrorCodeNotFound, Message: "not found"}
	ErrConflict         = &Error{Code: ErrorCodeConflict, Message: "conflict"}
	ErrRateLimited      = &Error{Code: ErrorCodeRateLimited, Message: "rate limited", Retryable: true}
	ErrValidation       = &Error{Code: ErrorCodeValidation, Message: "validation failed"}
	ErrUnavailable      = &Error{Code: ErrorCodeUnavailable, Message: "service unavailable", Retryable: true}
	ErrTimeout          = &Error{Code: ErrorCodeTimeout, Message: "timeout", Retryable: true}
	ErrUnsupported      = &Error{Code: ErrorCodeUnsupported, Message: "unsupported"}
	ErrCancelled        = &Error{Code: ErrorCodeCancelled, Message: "cancelled"}
)

Sentinels for errors.Is; (*Error).Is compares codes only.

View Source
var DefaultSensitiveFields = []string{
	"password", "passwd", "secret", "token", "authorization", "cookie", "api_key", "apikey", "api-key",
	"access_key", "private_key", "client_secret", "credential", "session", "signature",
}

DefaultSensitiveFields are the case-insensitive substrings that mark a field or query parameter name as sensitive.

Functions

func ContextError

func ContextError(operation string, err error) error

ContextError maps a context error to CANCELLED (context.Canceled) or TIMEOUT (context.DeadlineExceeded); errors.Is(err, context.Canceled) stays true. It returns nil when err is nil and passes *Error values through.

func IsEmailNotVerified

func IsEmailNotVerified(err error) bool

IsEmailNotVerified reports whether the user's e-mail address is not verified.

func IsMFARequired

func IsMFARequired(err error) bool

IsMFARequired reports whether sign-in needs a TOTP code or recovery code.

func IsSensitiveField

func IsSensitiveField(name string, extraKeys ...string) bool

IsSensitiveField reports whether a field or query name is sensitive. extraKeys are additional case-insensitive substrings.

func IsSensitiveHeader

func IsSensitiveHeader(name string) bool

IsSensitiveHeader reports whether a header name carries credentials.

func PKCEChallenge

func PKCEChallenge(verifier string) string

PKCEChallenge returns base64url(sha256(verifier)).

func ParseBool

func ParseBool(s string) (bool, error)

ParseBool accepts true/false/1/0/yes/no/on/off (case-insensitive).

func ParseDuration

func ParseDuration(s string) (time.Duration, error)

ParseDuration accepts integer milliseconds ("1500") or Go-style units ("500ms", "10s", "2m", "1h", "1m30s").

func ParseRetryAfter

func ParseRetryAfter(value string, now time.Time) (time.Duration, bool)

ParseRetryAfter parses a Retry-After header (delta seconds or HTTP-date).

func PollUntil

func PollUntil[T any](ctx context.Context, operation string, timeout, interval time.Duration,
	fn func(ctx context.Context) (T, bool, error),
) (T, error)

PollUntil calls fn every interval until it reports done, the timeout passes (TIMEOUT error wrapping the last error) or ctx is cancelled (CANCELLED). Retryable errors from fn keep the poll going; other errors are returned at once.

func RandomState

func RandomState() string

RandomState returns a random URL-safe value for state or nonce.

func ReasonOf

func ReasonOf(err error) string

ReasonOf returns the Casdoor reason of err, or "".

func RedactFields

func RedactFields(m map[string]any, extraKeys ...string) map[string]any

RedactFields returns a deep copy of m with sensitive values replaced, recursing into nested maps and slices.

func RedactHeaderMap

func RedactHeaderMap(h map[string]string) map[string]string

RedactHeaderMap is RedactHeaders for a plain map.

func RedactHeaders

func RedactHeaders(h http.Header) http.Header

RedactHeaders returns a copy of h with sensitive header values replaced.

func RedactText

func RedactText(text string, knownSecrets []string) string

RedactText replaces every known secret value (length ≥ 4) in text.

func RedactURL

func RedactURL(raw string) string

RedactURL removes user info and replaces every query value with Redacted when its name is sensitive. Unparsable input is fully redacted.

func TOTPCode

func TOTPCode(secret string, t time.Time) (string, error)

TOTPCode returns the TOTP code (RFC 6238, SHA-1, 6 digits, 30 s) of a base32 secret at t; for tests and e2e helpers.

Types

type ApplicationInfo

type ApplicationInfo struct {
	Name         string
	Organization string
	ClientID     string
	ClientSecret Secret
	RedirectURIs []string
	Created      bool
}

ApplicationInfo is the result of EnsureApplication.

type AuthorizeURLInput

type AuthorizeURLInput struct {
	RedirectURI   string
	State         string
	CodeChallenge string
	Scope         string
	Nonce         string
	Extra         map[string]string
}

AuthorizeURLInput is the input of BuildAuthorizeURL.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the Casdoor client: user flows for backends-for-frontends and idempotent admin operations. Every Casdoor {"status":"error"} answer (HTTP 200) and every OAuth error becomes an *Error with the canonical code and a *ErrorDetail cause (ReasonOf). It is safe for concurrent use.

func NewClient

func NewClient(cfg Config) (*Client, error)

NewClient validates cfg and returns a client.

func NewClientFromEnv

func NewClientFromEnv() (*Client, error)

NewClientFromEnv builds a client from the environment (see ConfigFromEnv): GROW_CASDOOR_*, then GROW_AUTH_ISSUER|PUBLIC_URL, GROW_AUTH_CLIENT_ID/SECRET, GROW_AUTH_ORG/APP, GROW_AUTH_REDIRECT_URL, CASDOOR_ADMIN_PASSWORD.

func (*Client) AssignRoles

func (c *Client) AssignRoles(ctx context.Context, user string, roles []string, organization string) error

AssignRoles adds a user ("org/name", name or e-mail) to roles, creating missing roles (organization "" = config Organization).

func (*Client) BuildAuthorizeURL

func (c *Client) BuildAuthorizeURL(in AuthorizeURLInput) (string, error)

BuildAuthorizeURL returns the browser authorize URL on PublicURL (code flow, PKCE S256).

func (*Client) Close

func (c *Client) Close() error

Close releases resources. It is idempotent.

func (*Client) Config

func (c *Client) Config() Config

Config returns the effective configuration.

func (*Client) EnsureApplication

func (c *Client) EnsureApplication(ctx context.Context, in EnsureApplicationInput) (*ApplicationInfo, error)

EnsureApplication creates or aligns the OAuth application (exact redirect URIs, JWT tokens, password sign-in, lockout, pinned client credentials) and returns its client credentials.

func (*Client) EnsureEmailProvider

func (c *Client) EnsureEmailProvider(ctx context.Context, s SMTPSettings) (bool, error)

EnsureEmailProvider creates or aligns an SMTP e-mail provider and lists it on the configured application when that application exists. It reports whether the provider was created.

func (*Client) EnsureOrganization

func (c *Client) EnsureOrganization(ctx context.Context, in EnsureOrganizationInput) (bool, error)

EnsureOrganization creates the organization unless it exists, then aligns its password rules and TOTP offer. It reports whether it was created.

func (*Client) EnsureRoles

func (c *Client) EnsureRoles(ctx context.Context, names []string, organization string) ([]RoleInfo, error)

EnsureRoles creates every missing role (organization "" = config Organization).

func (*Client) EnsureUser

func (c *Client) EnsureUser(ctx context.Context, in EnsureUserInput) (*User, error)

EnsureUser creates or aligns a user (verified e-mail unless Unverified, password, display name) and assigns its roles.

func (*Client) ExchangeCode

func (c *Client) ExchangeCode(ctx context.Context, in ExchangeCodeInput) (*TokenSet, error)

ExchangeCode exchanges the authorization code of the browser redirect for tokens.

func (*Client) ForgotPassword

func (c *Client) ForgotPassword(ctx context.Context, email string) error

ForgotPassword mails a password reset code (NOT_FOUND for unknown e-mails; do not reveal that to the browser).

func (*Client) Health

func (c *Client) Health(ctx context.Context) (HealthStatus, error)

Health checks GET /api/health without credentials. It reports an unreachable or unhealthy service in the result; it fails only for CANCELLED and CONFIG.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) (time.Duration, error)

Ping makes an authenticated round trip with the admin credentials (admin session or client credentials) and returns its latency.

func (*Client) Refresh

func (c *Client) Refresh(ctx context.Context, refreshToken string) (*TokenSet, error)

Refresh returns new tokens for a refresh token.

func (*Client) ResetPassword

func (c *Client) ResetPassword(ctx context.Context, in ResetPasswordInput) error

ResetPassword sets a new password with the code from ForgotPassword (code check and password change share one Casdoor session).

func (*Client) SendEmailVerification

func (c *Client) SendEmailVerification(ctx context.Context, email string, purpose EmailPurpose) error

SendEmailVerification mails a verification code. Casdoor allows one code per address per 60 s (RATE_LIMITED with RetryAfter).

func (*Client) ServerVersion

func (c *Client) ServerVersion(ctx context.Context) (string, error)

ServerVersion returns the Casdoor version (/api/get-version-info, admin session).

func (*Client) SetupTOTP

func (c *Client) SetupTOTP(ctx context.Context, accessToken string) (*TOTPSetup, error)

SetupTOTP starts TOTP enrollment for the user of the access token.

func (*Client) SignIn

func (c *Client) SignIn(ctx context.Context, in SignInInput) (*TokenSet, error)

SignIn is the headless password sign-in (code flow + PKCE inside the BFF). It returns a ReasonMFARequired error (IsMFARequired) when the user has TOTP and no code was given, and ReasonEmailNotVerified when the e-mail is not verified.

func (*Client) SignOut

func (c *Client) SignOut(ctx context.Context, token string) error

SignOut ends the Casdoor session of the token (/api/logout). Idempotent: an expired or revoked token counts as signed out.

func (*Client) SignUp

func (c *Client) SignUp(ctx context.Context, in SignUpInput) (*SignUpResult, error)

SignUp registers a user through /api/signup. Pass EmailCode when the application requires the e-mail code on sign-up.

func (*Client) VerifyEmail

func (c *Client) VerifyEmail(ctx context.Context, in VerifyEmailInput) error

VerifyEmail checks the code and marks the user's e-mail verified (full-object update-user with the admin credentials).

func (*Client) VerifyTOTP

func (c *Client) VerifyTOTP(ctx context.Context, in VerifyTOTPInput) error

VerifyTOTP verifies the first code, then enables TOTP (Casdoor's enable call does not check the code itself).

type CommonConfig

type CommonConfig struct {
	// URL is the endpoint base URL.
	URL string
	// ConnectTimeout bounds connection setup (default 10 s).
	ConnectTimeout time.Duration
	// RequestTimeout bounds one attempt including the body (default 30 s).
	RequestTimeout time.Duration
	// TotalTimeout bounds a whole call including retries and backoff (default 120 s).
	TotalTimeout time.Duration
	// Retry is the retry policy; nil means DefaultRetryPolicy().
	Retry *RetryPolicy
	// TLS settings.
	TLS TLSConfig
	// Proxy is an explicit proxy URL. Environment proxies are ignored.
	Proxy string
	// Headers are extra request headers.
	Headers map[string]string
	// UserAgentSuffix is appended after the standard User-Agent.
	UserAgentSuffix string
	// Hooks observe every attempt.
	Hooks *Hooks
	// Logger receives debug output; nil discards.
	Logger *slog.Logger
}

CommonConfig holds the fields every service config shares. Service configs embed it. Zero values mean "use the default".

type Config

type Config struct {
	CommonConfig

	// PublicURL is the browser-facing Casdoor URL for BuildAuthorizeURL
	// (env GROW_CASDOOR_PUBLIC_URL, GROW_AUTH_PUBLIC_URL). Default: URL.
	PublicURL string
	// ClientID is the OAuth client id (env GROW_CASDOOR_CLIENT_ID, GROW_AUTH_CLIENT_ID).
	ClientID string
	// ClientSecret is the OAuth client secret (env GROW_CASDOOR_CLIENT_SECRET, GROW_AUTH_CLIENT_SECRET).
	ClientSecret Secret
	// Organization is the Casdoor organization (env GROW_CASDOOR_ORG, GROW_AUTH_ORG).
	Organization string
	// Application is the Casdoor application name (env GROW_CASDOOR_APP, GROW_AUTH_APP).
	Application string
	// RedirectURI is the default code-flow redirect URI (env GROW_CASDOOR_REDIRECT_URL, GROW_AUTH_REDIRECT_URL).
	RedirectURI string
	// Scope is the OAuth scope (env GROW_CASDOOR_SCOPE). Default DefaultScope.
	Scope string
	// AdminUsername is the built-in admin (env GROW_CASDOOR_ADMIN_USERNAME, CASDOOR_ADMIN_USERNAME). Default "admin".
	AdminUsername string
	// AdminPassword enables the admin session for admin operations (env GROW_CASDOOR_ADMIN_PASSWORD,
	// CASDOOR_ADMIN_PASSWORD). Without it admin operations use the client credentials (HTTP Basic).
	AdminPassword Secret
	// AdminOrganization of the admin user (env GROW_CASDOOR_ADMIN_ORG). Default "built-in".
	AdminOrganization string
	// AdminApplication of the admin user (env GROW_CASDOOR_ADMIN_APP). Default "app-built-in".
	AdminApplication string
	// AllowUnverifiedEmail accepts tokens of users whose e-mail is not verified
	// (env GROW_CASDOOR_REQUIRE_VERIFIED_EMAIL=false). Default false: EmailNotVerified errors.
	AllowUnverifiedEmail bool
}

Config configures a Client. Build it with a struct literal or ConfigFromEnv; zero values mean "use the default". Call Validate to check it.

func ConfigFromEnv

func ConfigFromEnv() (Config, error)

ConfigFromEnv reads the configuration from the process environment.

func ConfigFromEnvWith

func ConfigFromEnvWith(explicit Config, env map[string]string) (Config, error)

ConfigFromEnvWith resolves explicit values > GROW_CASDOOR_* > platform variables (GROW_AUTH_*, CASDOOR_ADMIN_*) > defaults. env replaces the process environment when non-nil.

func (Config) GoString

func (c Config) GoString() string

GoString renders the configuration with every credential redacted.

func (Config) MarshalJSON

func (c Config) MarshalJSON() ([]byte, error)

MarshalJSON encodes the configuration with credentials redacted, the same way String() does:

  • URL and Proxy lose user info, and sensitive query values become "[REDACTED]";
  • sensitive Headers values (Authorization, Cookie, *token*, ...) become "[REDACTED]";
  • Secret fields encode as "[REDACTED]";
  • Hooks and Logger (code, not data) encode as null.

The service's own fields are encoded as declared, with the same rules applied by name: string fields named like a URL or endpoint (…URL, …Endpoint, …Addr) lose user info and sensitive query values, string fields with a sensitive name (…Password, …Token, …APIKey; not …Path, …File, …Name, …ID) become "[REDACTED]", map[string]string fields named …Headers get sensitive values replaced, and function, channel and interface fields (callbacks, credential providers, SDK clients) encode as null.

Fields are encoded like encoding/json would (declaration order, embedded structs inlined, json tag names, "-" and omitempty), except that function and channel fields encode as null instead of failing the whole call.

func (Config) String

func (c Config) String() string

String renders the configuration with every credential redacted.

func (Config) Validate

func (c Config) Validate() error

Validate checks the configuration and returns a CONFIG error.

type EmailPurpose

type EmailPurpose string

EmailPurpose selects the kind of code SendEmailVerification sends.

const (
	// PurposeAuto sends a code to an existing user, else a sign-up code.
	PurposeAuto EmailPurpose = ""
	// PurposeSignUp sends a code for a new address (pass it to SignUp).
	PurposeSignUp EmailPurpose = "signup"
	// PurposeVerify sends a code to an existing user (then VerifyEmail).
	PurposeVerify EmailPurpose = "verify"
)

E-mail code purposes.

type EnsureApplicationInput

type EnsureApplicationInput struct {
	Name                   string
	Organization           string
	DisplayName            string
	ClientID               string
	ClientSecret           Secret
	RedirectURIs           []string
	GrantTypes             []string // default authorization_code, refresh_token
	DisableSignUp          bool
	SignUpEmailCode        bool
	Providers              []string
	ExpireInHours          int // default 1
	RefreshExpireInHours   int // default 168
	FailedSigninLimit      int // default 5
	FailedSigninFrozenTime int // default 15 (minutes)
	Cert                   string
}

EnsureApplicationInput configures EnsureApplication. Zero values use the config (name, organization, client credentials) or the documented defaults.

type EnsureOrganizationInput

type EnsureOrganizationInput struct {
	Name            string
	DisplayName     string
	PasswordOptions []string // default ["AtLeast8"]
	DisableTOTP     bool
}

EnsureOrganizationInput configures EnsureOrganization.

type EnsureUserInput

type EnsureUserInput struct {
	Email        string
	Username     string
	Password     Secret
	DisplayName  string
	Unverified   bool // default: e-mail verified
	Roles        []string
	Organization string
}

EnsureUserInput configures EnsureUser.

type EnvReader

type EnvReader struct {
	// contains filtered or unexported fields
}

EnvReader reads configuration variables: GROW_<KEY>_<NAME> first, then the vendor variables in the order given. Empty values count as unset. A present but invalid value yields a CONFIG error naming the variable, never its value.

func NewEnvReader

func NewEnvReader(prefix string, env map[string]string) *EnvReader

NewEnvReader returns a reader over env. A nil env reads the process environment.

func (*EnvReader) Bool

func (r *EnvReader) Bool(name string, vendorNames ...string) (value, ok bool, err error)

Bool parses a boolean variable (true/false/1/0/yes/no/on/off, case-insensitive).

func (*EnvReader) Duration

func (r *EnvReader) Duration(name string, vendorNames ...string) (time.Duration, bool, error)

Duration parses a duration variable (integer milliseconds or Go units such as 1m30s).

func (*EnvReader) Int

func (r *EnvReader) Int(name string, vendorNames ...string) (int, bool, error)

Int parses an integer variable.

func (*EnvReader) String

func (r *EnvReader) String(name string, vendorNames ...string) (string, bool)

String returns the value of GROW_<KEY>_<name> or the first set vendor variable.

type Error

type Error struct {
	// Code is the canonical error code.
	Code ErrorCode
	// Message is human text in the form "<operation>: <reason> (HTTP <status>)".
	// It never contains secrets, tokens, request bodies or unfiltered response bodies.
	Message string
	// HTTPStatus is the HTTP status when the error came from a response (0 otherwise).
	HTTPStatus int
	// RequestID is the vendor request id header when present.
	RequestID string
	// Retryable reports whether retrying the same call may succeed.
	Retryable bool
	// RetryAfter is the server-requested wait (RATE_LIMITED / UNAVAILABLE), 0 when unknown.
	RetryAfter time.Duration
	// Err is the underlying cause (already redacted).
	Err error
}

Error is the single error type returned by this package. Compare codes with errors.Is against the Err* sentinels, or extract it with errors.As.

func ConfigError

func ConfigError(message string) *Error

ConfigError returns a CONFIG error. The message must never contain a value.

func NewError

func NewError(code ErrorCode, message string, cause error) *Error

NewError returns an *Error with the code's default retryability.

func NotFoundError

func NotFoundError(operation, reason string) *Error

NotFoundError returns a NOT_FOUND error.

func StatusError

func StatusError(operation string, status int, requestID, vendorText string, knownSecrets []string) *Error

StatusError builds the error for an HTTP response. vendorText is the error text extracted from the body; it is redacted with knownSecrets and truncated.

func UnsupportedError

func UnsupportedError(operation, reason string) *Error

UnsupportedError returns an UNSUPPORTED error.

func ValidationError

func ValidationError(operation, reason string) *Error

ValidationError returns a VALIDATION error for bad input caught client side.

func (*Error) Error

func (e *Error) Error() string

Error implements error.

func (*Error) Is

func (e *Error) Is(target error) bool

Is reports whether target is an *Error with the same code.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the cause so errors.Is(err, context.Canceled) keeps working.

type ErrorCode

type ErrorCode string

ErrorCode is the canonical, language-independent error code (wire value).

const (
	ErrorCodeConfig           ErrorCode = "CONFIG"
	ErrorCodeAuthentication   ErrorCode = "AUTHENTICATION"
	ErrorCodePermissionDenied ErrorCode = "PERMISSION_DENIED"
	ErrorCodeNotFound         ErrorCode = "NOT_FOUND"
	ErrorCodeConflict         ErrorCode = "CONFLICT"
	ErrorCodeRateLimited      ErrorCode = "RATE_LIMITED"
	ErrorCodeValidation       ErrorCode = "VALIDATION"
	ErrorCodeUnavailable      ErrorCode = "UNAVAILABLE"
	ErrorCodeTimeout          ErrorCode = "TIMEOUT"
	ErrorCodeUnsupported      ErrorCode = "UNSUPPORTED"
	ErrorCodeCancelled        ErrorCode = "CANCELLED"
)

Canonical error codes (SPEC §2.1).

func CodeForStatus

func CodeForStatus(status int) ErrorCode

CodeForStatus maps an HTTP status to a canonical code (SPEC §2.1).

func CodeOf

func CodeOf(err error) ErrorCode

CodeOf returns the code of err when it is (or wraps) an *Error, or "" otherwise.

func (ErrorCode) Retryable

func (c ErrorCode) Retryable() bool

Retryable reports whether errors with this code are retryable by default.

type ErrorDetail

type ErrorDetail struct {
	Reason      string
	CasdoorCode string
	MFATypes    []string
}

ErrorDetail is the cause (Error.Err) of every normalized Casdoor error: errors.As(err, &detail) gives the reason, Casdoor's own code and, for ReasonMFARequired, the MFA types offered.

func (*ErrorDetail) Error

func (d *ErrorDetail) Error() string

Error implements error.

type ErrorInfo

type ErrorInfo struct {
	Method    string
	URL       string
	Err       error
	Attempt   int
	WillRetry bool
}

ErrorInfo describes a failed attempt.

type ExchangeCodeInput

type ExchangeCodeInput struct {
	Code         string
	CodeVerifier string
	RedirectURI  string
}

ExchangeCodeInput is the input of ExchangeCode.

type HealthStatus

type HealthStatus struct {
	// Healthy is true when the service answered and reports itself usable.
	Healthy bool `json:"healthy"`
	// Status is "ok", "degraded", "unhealthy", "unreachable" or the vendor's word.
	Status string `json:"status"`
	// Details holds extra vendor fields as strings.
	Details map[string]string `json:"details"`
}

HealthStatus is the result of Client.Health.

type Hooks

type Hooks struct {
	OnRequest  func(RequestInfo)
	OnResponse func(ResponseInfo)
	OnError    func(ErrorInfo)
}

Hooks observe every HTTP attempt. URLs and headers are redacted. Panics in hooks are recovered and ignored.

type PKCE

type PKCE struct {
	CodeVerifier        string
	CodeChallenge       string
	CodeChallengeMethod string
}

PKCE is a code verifier and its S256 challenge (RFC 7636).

func NewPKCE

func NewPKCE() PKCE

NewPKCE returns a new verifier (64 characters) and its S256 challenge.

type RequestInfo

type RequestInfo struct {
	Method  string
	URL     string
	Headers http.Header
	// Attempt starts at 1.
	Attempt int
}

RequestInfo describes an attempt that is about to be sent.

type ResetPasswordInput

type ResetPasswordInput struct {
	Email       string
	Code        string
	NewPassword string
}

ResetPasswordInput is the input of ResetPassword.

type ResponseInfo

type ResponseInfo struct {
	Method    string
	URL       string
	Status    int
	Duration  time.Duration
	Attempt   int
	RequestID string
}

ResponseInfo describes a received response.

type RetryPolicy

type RetryPolicy struct {
	// MaxRetries is the number of retries after the first attempt.
	MaxRetries int
	// InitialBackoff is the backoff cap of the first retry.
	InitialBackoff time.Duration
	// MaxBackoff caps every backoff.
	MaxBackoff time.Duration
	// Multiplier grows the cap per retry.
	Multiplier float64
	// MaxRetryAfter is the longest server-requested wait honoured.
	MaxRetryAfter time.Duration
	// Rand returns a number in [0, 1); nil uses math/rand/v2. Inject it in tests.
	Rand func() float64 `json:"-"`
}

RetryPolicy controls retries. Start from DefaultRetryPolicy(); zero durations and multiplier fall back to the defaults, MaxRetries is used as is (0 disables retries).

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns the default policy.

func (RetryPolicy) Backoff

func (p RetryPolicy) Backoff(n int) time.Duration

Backoff returns the full-jitter backoff for retry n: random(0, BackoffCap(n)).

func (RetryPolicy) BackoffCap

func (p RetryPolicy) BackoffCap(n int) time.Duration

BackoffCap returns min(MaxBackoff, InitialBackoff * Multiplier^n) for retry n (0-based).

type RoleInfo

type RoleInfo struct {
	Name    string
	Created bool
}

RoleInfo is one entry of EnsureRoles.

type SMTPSettings

type SMTPSettings struct {
	Name       string // default "provider-email"
	Host       string
	Port       int
	From       string
	FromName   string // default "Casdoor"
	Username   string // default From
	Password   Secret
	DisableSSL bool
	Title      string // default "Verification code"
	Content    string // default "Your verification code is %s"
}

SMTPSettings configures EnsureEmailProvider.

type Secret

type Secret struct {
	// contains filtered or unexported fields
}

Secret wraps a credential (token, password, key). Every printed, logged or JSON-encoded form is "[REDACTED]"; Reveal returns the value.

func NewSecret

func NewSecret(value string) Secret

NewSecret wraps value.

func (Secret) Format

func (s Secret) Format(f fmt.State, _ rune)

Format implements fmt.Formatter so every verb prints the redacted form.

func (Secret) GoString

func (s Secret) GoString() string

GoString implements fmt.GoStringer.

func (Secret) IsZero

func (s Secret) IsZero() bool

IsZero reports whether the secret is empty.

func (Secret) LogValue

func (s Secret) LogValue() slog.Value

LogValue implements slog.LogValuer.

func (Secret) MarshalJSON

func (s Secret) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Secret) MarshalText

func (s Secret) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Secret) Reveal

func (s Secret) Reveal() string

Reveal returns the wrapped value.

func (Secret) String

func (s Secret) String() string

String implements fmt.Stringer.

type SignInInput

type SignInInput struct {
	Username     string // user name or e-mail
	Password     string
	TOTPCode     string
	RecoveryCode string
	RedirectURI  string // default: Config.RedirectURI
}

SignInInput is the input of SignIn.

type SignUpInput

type SignUpInput struct {
	Username    string
	Email       string
	Password    string
	DisplayName string
	// EmailCode from SendEmailVerification when the application requires it.
	EmailCode string
}

SignUpInput is the input of SignUp. Username is derived from the e-mail when empty.

type SignUpResult

type SignUpResult struct {
	UserID       string // "<organization>/<name>"
	Organization string
	Name         string
}

SignUpResult is the result of SignUp.

type TLSConfig

type TLSConfig struct {
	// CACertPath is a PEM bundle of trusted CAs (env CA_CERT).
	CACertPath string
	// CACertPEM is an inline PEM bundle of trusted CAs.
	CACertPEM string
	// ClientCertPath and ClientKeyPath enable mutual TLS; both or neither.
	ClientCertPath string
	ClientKeyPath  string
	// InsecureSkipVerify disables certificate checks (tests only; logs a warning once).
	InsecureSkipVerify bool
}

TLSConfig configures TLS for the HTTP transport.

type TOTPSetup

type TOTPSetup struct {
	Secret        string
	URL           string
	RecoveryCodes []string
}

TOTPSetup is the result of SetupTOTP (show the secret once, never log it).

func (TOTPSetup) String

func (s TOTPSetup) String() string

String implements fmt.Stringer without the secret.

type TokenSet

type TokenSet struct {
	AccessToken  string
	RefreshToken string
	IDToken      string
	TokenType    string
	ExpiresIn    int
	ExpiresAt    time.Time
	Scope        string
}

TokenSet holds the OAuth tokens of sign-in, refresh and code exchange. Its String method never prints tokens.

func (TokenSet) String

func (t TokenSet) String() string

String implements fmt.Stringer without the tokens.

type User

type User struct {
	UserID        string
	Organization  string
	Name          string
	ID            string
	Email         string
	DisplayName   string
	EmailVerified bool
	IsForbidden   bool
	Created       bool
}

User is a Casdoor user (subset).

type VendorEnv

type VendorEnv struct {
	URL                []string
	CACert             []string
	ClientCert         []string
	ClientKey          []string
	InsecureSkipVerify []string
	Proxy              []string
}

VendorEnv lists vendor variable names consulted after GROW_<KEY>_* (in order).

type VerifyEmailInput

type VerifyEmailInput struct {
	Email string
	Code  string
}

VerifyEmailInput is the input of VerifyEmail.

type VerifyTOTPInput

type VerifyTOTPInput struct {
	AccessToken  string
	Secret       string
	Code         string
	RecoveryCode string
}

VerifyTOTPInput is the input of VerifyTOTP.

Directories

Path Synopsis
internal
tools/covergate command
Command covergate enforces the statement coverage gate on a Go cover profile and writes coverage/summary.json in the shared sdk-kit format:
Command covergate enforces the statement coverage gate on a Go cover profile and writes coverage/summary.json in the shared sdk-kit format:

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL