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
- Variables
- func ContextError(operation string, err error) error
- func IsEmailNotVerified(err error) bool
- func IsMFARequired(err error) bool
- func IsSensitiveField(name string, extraKeys ...string) bool
- func IsSensitiveHeader(name string) bool
- func PKCEChallenge(verifier string) string
- func ParseBool(s string) (bool, error)
- func ParseDuration(s string) (time.Duration, error)
- func ParseRetryAfter(value string, now time.Time) (time.Duration, bool)
- func PollUntil[T any](ctx context.Context, operation string, timeout, interval time.Duration, ...) (T, error)
- func RandomState() string
- func ReasonOf(err error) string
- func RedactFields(m map[string]any, extraKeys ...string) map[string]any
- func RedactHeaderMap(h map[string]string) map[string]string
- func RedactHeaders(h http.Header) http.Header
- func RedactText(text string, knownSecrets []string) string
- func RedactURL(raw string) string
- func TOTPCode(secret string, t time.Time) (string, error)
- type ApplicationInfo
- type AuthorizeURLInput
- type Client
- func (c *Client) AssignRoles(ctx context.Context, user string, roles []string, organization string) error
- func (c *Client) BuildAuthorizeURL(in AuthorizeURLInput) (string, error)
- func (c *Client) Close() error
- func (c *Client) Config() Config
- func (c *Client) EnsureApplication(ctx context.Context, in EnsureApplicationInput) (*ApplicationInfo, error)
- func (c *Client) EnsureEmailProvider(ctx context.Context, s SMTPSettings) (bool, error)
- func (c *Client) EnsureOrganization(ctx context.Context, in EnsureOrganizationInput) (bool, error)
- func (c *Client) EnsureRoles(ctx context.Context, names []string, organization string) ([]RoleInfo, error)
- func (c *Client) EnsureUser(ctx context.Context, in EnsureUserInput) (*User, error)
- func (c *Client) ExchangeCode(ctx context.Context, in ExchangeCodeInput) (*TokenSet, error)
- func (c *Client) ForgotPassword(ctx context.Context, email string) error
- func (c *Client) Health(ctx context.Context) (HealthStatus, error)
- func (c *Client) Ping(ctx context.Context) (time.Duration, error)
- func (c *Client) Refresh(ctx context.Context, refreshToken string) (*TokenSet, error)
- func (c *Client) ResetPassword(ctx context.Context, in ResetPasswordInput) error
- func (c *Client) SendEmailVerification(ctx context.Context, email string, purpose EmailPurpose) error
- func (c *Client) ServerVersion(ctx context.Context) (string, error)
- func (c *Client) SetupTOTP(ctx context.Context, accessToken string) (*TOTPSetup, error)
- func (c *Client) SignIn(ctx context.Context, in SignInInput) (*TokenSet, error)
- func (c *Client) SignOut(ctx context.Context, token string) error
- func (c *Client) SignUp(ctx context.Context, in SignUpInput) (*SignUpResult, error)
- func (c *Client) VerifyEmail(ctx context.Context, in VerifyEmailInput) error
- func (c *Client) VerifyTOTP(ctx context.Context, in VerifyTOTPInput) error
- type CommonConfig
- type Config
- type EmailPurpose
- type EnsureApplicationInput
- type EnsureOrganizationInput
- type EnsureUserInput
- type EnvReader
- func (r *EnvReader) Bool(name string, vendorNames ...string) (value, ok bool, err error)
- func (r *EnvReader) Duration(name string, vendorNames ...string) (time.Duration, bool, error)
- func (r *EnvReader) Int(name string, vendorNames ...string) (int, bool, error)
- func (r *EnvReader) String(name string, vendorNames ...string) (string, bool)
- type Error
- func ConfigError(message string) *Error
- func NewError(code ErrorCode, message string, cause error) *Error
- func NotFoundError(operation, reason string) *Error
- func StatusError(operation string, status int, requestID, vendorText string, ...) *Error
- func UnsupportedError(operation, reason string) *Error
- func ValidationError(operation, reason string) *Error
- type ErrorCode
- type ErrorDetail
- type ErrorInfo
- type ExchangeCodeInput
- type HealthStatus
- type Hooks
- type PKCE
- type RequestInfo
- type ResetPasswordInput
- type ResponseInfo
- type RetryPolicy
- type RoleInfo
- type SMTPSettings
- type Secret
- func (s Secret) Format(f fmt.State, _ rune)
- func (s Secret) GoString() string
- func (s Secret) IsZero() bool
- func (s Secret) LogValue() slog.Value
- func (s Secret) MarshalJSON() ([]byte, error)
- func (s Secret) MarshalText() ([]byte, error)
- func (s Secret) Reveal() string
- func (s Secret) String() string
- type SignInInput
- type SignUpInput
- type SignUpResult
- type TLSConfig
- type TOTPSetup
- type TokenSet
- type User
- type VendorEnv
- type VerifyEmailInput
- type VerifyTOTPInput
Constants ¶
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).
const ( DefaultConnectTimeout = 10 * time.Second DefaultRequestTimeout = 30 * time.Second DefaultTotalTimeout = 120 * time.Second )
Defaults of the common configuration fields (SPEC §2.2).
const ( DefaultMaxRetries = 3 DefaultInitialBackoff = 100 * time.Millisecond DefaultMaxBackoff = 10 * time.Second DefaultMultiplier = 2.0 DefaultMaxRetryAfter = 60 * time.Second )
Retry policy defaults (SPEC §2.3).
const DefaultScope = "openid profile email"
DefaultScope is the OAuth scope requested by sign-in and the authorize URL.
const DefaultURL = "http://127.0.0.1:8000"
DefaultURL is the default endpoint of Casdoor.
const EnvPrefix = "GROW_CASDOOR_"
EnvPrefix is the prefix of this package's environment variables.
const Redacted = "[REDACTED]"
Redacted replaces every sensitive value.
const UserAgent = "grow-codes-casdoor/" + Version + " (go)"
UserAgent is the standard User-Agent of this package.
const Version = "0.1.0" // x-release-please-version
Version is the package version (updated by release-please).
Variables ¶
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"} 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.
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 ¶
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 ¶
IsEmailNotVerified reports whether the user's e-mail address is not verified.
func IsMFARequired ¶
IsMFARequired reports whether sign-in needs a TOTP code or recovery code.
func IsSensitiveField ¶
IsSensitiveField reports whether a field or query name is sensitive. extraKeys are additional case-insensitive substrings.
func IsSensitiveHeader ¶
IsSensitiveHeader reports whether a header name carries credentials.
func PKCEChallenge ¶
PKCEChallenge returns base64url(sha256(verifier)).
func ParseDuration ¶
ParseDuration accepts integer milliseconds ("1500") or Go-style units ("500ms", "10s", "2m", "1h", "1m30s").
func ParseRetryAfter ¶
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 RedactFields ¶
RedactFields returns a deep copy of m with sensitive values replaced, recursing into nested maps and slices.
func RedactHeaderMap ¶
RedactHeaderMap is RedactHeaders for a plain map.
func RedactHeaders ¶
RedactHeaders returns a copy of h with sensitive header values replaced.
func RedactText ¶
RedactText replaces every known secret value (length ≥ 4) in text.
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 NewClientFromEnv ¶
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) 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 ¶
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 ¶
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 ¶
EnsureUser creates or aligns a user (verified e-mail unless Unverified, password, display name) and assigns its roles.
func (*Client) ExchangeCode ¶
ExchangeCode exchanges the authorization code of the browser redirect for tokens.
func (*Client) ForgotPassword ¶
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 ¶
Ping makes an authenticated round trip with the admin credentials (admin session or client credentials) and returns its latency.
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 ¶
ServerVersion returns the Casdoor version (/api/get-version-info, admin session).
func (*Client) SignIn ¶
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 ¶
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 ¶
ConfigFromEnv reads the configuration from the process environment.
func ConfigFromEnvWith ¶
ConfigFromEnvWith resolves explicit values > GROW_CASDOOR_* > platform variables (GROW_AUTH_*, CASDOOR_ADMIN_*) > defaults. env replaces the process environment when non-nil.
func (Config) MarshalJSON ¶
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.
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 ¶
NewEnvReader returns a reader over env. A nil env reads the process environment.
func (*EnvReader) Bool ¶
Bool parses a boolean variable (true/false/1/0/yes/no/on/off, case-insensitive).
func (*EnvReader) Duration ¶
Duration parses a duration variable (integer milliseconds or Go units such as 1m30s).
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 ¶
ConfigError returns a CONFIG error. The message must never contain a value.
func NotFoundError ¶
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 ¶
UnsupportedError returns an UNSUPPORTED error.
func ValidationError ¶
ValidationError returns a VALIDATION error for bad input caught client side.
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" ErrorCodeTimeout ErrorCode = "TIMEOUT" ErrorCodeUnsupported ErrorCode = "UNSUPPORTED" ErrorCodeCancelled ErrorCode = "CANCELLED" )
Canonical error codes (SPEC §2.1).
func CodeForStatus ¶
CodeForStatus maps an HTTP status to a canonical code (SPEC §2.1).
type ErrorDetail ¶
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.
type ExchangeCodeInput ¶
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 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 ¶
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 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 (Secret) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (Secret) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
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 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.
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 ¶
VerifyEmailInput is the input of VerifyEmail.
Source Files
¶
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: |