object

package
v1.31.35 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2026 License: Apache-2.0 Imports: 138 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultFailedSigninLimit      = 5
	DefaultFailedSigninFrozenTime = 15
)
View Source
const (
	MembershipRoleOwner  = "owner"
	MembershipRoleAdmin  = "admin"
	MembershipRoleMember = "member"
)

Coarse membership roles. These are the tenancy roles (who may administer the org), NOT the fine-grained authz roles in the Role catalog.

View Source
const (
	EmailType  = "email"
	SmsType    = "sms"
	TotpType   = "app"
	RadiusType = "radius"
	PushType   = "push"
)
View Source
const (
	MfaSessionUserId = "MfaSessionUserId"
	NextMfa          = "NextMfa"
	RequiredMfa      = "RequiredMfa"
)
View Source
const (
	ProviderTypeGoogleCloudStorage = "Google Cloud Storage"
	ProviderTypeTencentCloudCOS    = "Tencent Cloud COS"
	ProviderTypeAzureBlob          = "Azure Blob"
	ProviderTypeLocalFileSystem    = "Local File System"
	ProviderTypeMinIO              = "MinIO"
)
View Source
const (
	InvalidRequest       = "invalid_request"
	InvalidClient        = "invalid_client"
	InvalidGrant         = "invalid_grant"
	UnauthorizedClient   = "unauthorized_client"
	UnsupportedGrantType = "unsupported_grant_type"
	InvalidScope         = "invalid_scope"
	EndpointError        = "endpoint_error"
)
View Source
const (
	// DeviceCodeExpirySeconds bounds how long a device_code / user_code pair is
	// valid (RFC 8628 `expires_in`). It is the SINGLE source of truth for the
	// device grant's lifetime — the authorization handler, the token poll, and
	// the discovery response all read it, so they can never drift. 15 minutes
	// gives a human time to open the verification URL, authenticate via SSO,
	// and approve on a second device.
	DeviceCodeExpirySeconds = 900
	// DeviceCodePollInterval is the minimum seconds a client must wait between
	// token-endpoint polls (RFC 8628 `interval`).
	DeviceCodePollInterval = 5
)
View Source
const (
	UserPropertiesWechatUnionId = "wechatUnionId"
	UserPropertiesWechatOpenId  = "wechatOpenId"
)
View Source
const (
	ApprovalStatusProperty = "approvalStatus"
	ApprovalPending        = "pending"
	ApprovalApproved       = "approved"
)

ApprovalStatusProperty is the single authoritative user property that gates customer access behind the waitlist. Value "pending" ⇒ on the waitlist, no access; anything else (incl. absent/"approved") ⇒ approved. Absent defaults to APPROVED so every pre-existing user passes with no migration — only a user EXPLICITLY marked pending at waitlist-signup is gated. Set once at signup, flipped to "approved" by an admin from the waitlist queue.

View Source
const (
	VerifyTypePhone = "phone"
	VerifyTypeEmail = "email"
)
View Source
const (
	OidcPathAuthorize = "/v1/iam/oauth/authorize"
	OidcPathToken     = "/v1/iam/oauth/token"
	OidcPathUserinfo  = "/v1/iam/oauth/userinfo"
	OidcPathDevice    = "/v1/iam/oauth/device"
	// User-facing device-approval page (the SPA route), NOT the API path. RFC 8628
	// verification_uri must be a page a human opens, not the token-API endpoint.
	OidcPathDeviceVerify  = "/login/oauth/device"
	OidcPathRegister      = "/v1/iam/oauth/register"
	OidcPathIntrospect    = "/v1/iam/oauth/introspect"
	OidcPathRevoke        = "/v1/iam/oauth/revoke"
	OidcPathEndSession    = "/v1/iam/oauth/logout"
	OidcPathWellKnownBase = "/v1/iam/.well-known"
)

Canonical public OIDC paths. The IAM service publishes its discovery doc using ONLY these — external consumers (IdPs, SDKs, OIDC libraries) see exactly one shape per endpoint. /v1/iam/* is the law.

View Source
const DefaultProjectName = "default"

DefaultProjectName is the RESERVED name for the org-wide default scope. cloud's principal.IsDefaultProject and this repo's billingAccountClaim both treat an absent / "" / "default" project claim as the ONE default scope: keys stay un-suffixed and billing falls through to the org/person account. Any OTHER name is a real NAMED project scope. Create-on-demand no longer auto-seeds a row with this name — the org-level scope is the absent/"" claim — but the sentinel stays load-bearing so a project a user happens to name "default" still resolves to the org-wide scope rather than an unfunded project account.

View Source
const InternalServiceAppMarker = "hanzo:internal-service-identity"

InternalServiceAppMarker is the sentinel written to an internal machine app's Description at provisioning (cmd/iam/cli init-apps buildIAMServiceApp). It is the explicit, greppable predicate the public token endpoint gates on.

View Source
const MaxOrgDepth = 8

MaxOrgDepth bounds the reseller chain (tenant → reseller → distributor → …). It is a safety rail, not a product limit: it stops an unbounded/corrupt chain from turning an authz check into an unbounded walk.

View Source
const (
	MfaTotpPeriodInSeconds = 30
)
View Source
const MigrationUserTable = "user"

MigrationUserTable is the snake-cased name of the per-org User table (tableNamePrefix is "" in production). Rows in this table are routed to per-org engines; every other table goes to the global engine — exactly the runtime's orgEngine routing (orgEngine is called only from user.go).

View Source
const (

	// NotifyOTPEvent is the event-catalog identifier cloud's notify routes on.
	// The send carries event=iam.otp_sent with no template_id; cloud resolves the
	// channel + template from its built-in OTP registry.
	NotifyOTPEvent = "iam.otp_sent"
)
View Source
const ServiceAccountUserType = "service-account"

ServiceAccountUserType is the User.Type discriminator for a service account. Readers that need "is this a bot principal?" check IsServiceAccount, never the literal, so the value lives in exactly one place.

View Source
const (
	VerificationSuccess = iota
)

Variables

View Source
var (
	// CapUserPasswordAdmin gates resetting/overwriting ANOTHER user's
	// password without the old password or an emailed/SMS verification code
	// (the set-password endpoint). Allowlist: IAM_PASSWORD_ADMIN_APPS.
	CapUserPasswordAdmin = AppAdminCapability{Name: "password", EnvVar: "IAM_PASSWORD_ADMIN_APPS"}

	// CapUserAdmin gates sensitive cross-user account mutations:
	// update-user (password, is_admin, owner -> admin org == global admin,
	// email, phone, type, balance, access_key, ...), add-user and
	// delete-user. Allowlist: IAM_USER_ADMIN_APPS.
	CapUserAdmin = AppAdminCapability{Name: "user", EnvVar: "IAM_USER_ADMIN_APPS"}

	// CapAppAdmin gates application (OAuth client) mutations:
	// add/update/delete-application. This is the escalation vector that would
	// otherwise let an arbitrary app rotate an allowlisted app's clientSecret
	// and then authenticate as it, so it is gated with the same mechanism.
	// Allowlist: IAM_APP_ADMIN_APPS.
	CapAppAdmin = AppAdminCapability{Name: "application", EnvVar: "IAM_APP_ADMIN_APPS"}

	// CapKeyMint gates minting/revoking ANY user's hk- key on their behalf
	// (the per-tenant isolation layer is enforced by the trusted caller, e.g.
	// the console). This pre-existing gate (controllers/user.go
	// resolveTargetUserForKeys) is folded into the one helper so all
	// app-capability checks share a single mechanism. Allowlist:
	// IAM_KEY_MINT_ALLOWED_APPS.
	CapKeyMint = AppAdminCapability{Name: "key-mint", EnvVar: "IAM_KEY_MINT_ALLOWED_APPS"}

	// CapCertAdmin gates certificate mutations: add/update/delete-cert. This is
	// the HIGHEST-severity surface — a Cert holds the JWT *signing* private key,
	// so an app that could add/rotate/replace a cert could forge a token for any
	// user in any org (full account takeover, org-wide). Allowlist:
	// IAM_CERT_ADMIN_APPS. Deliberately EMPTY/unset in every environment
	// (fail-secure deny-all): NO confidential client should ever touch signing
	// material via an app credential — cert rotation is a real-global-admin USER
	// (human, User.IsSuperAdmin()) operation, and that human path is unaffected
	// by this gate.
	CapCertAdmin = AppAdminCapability{Name: "cert", EnvVar: "IAM_CERT_ADMIN_APPS"}

	// CapKeyAdmin gates Key-object mutations: add/update/delete-key. (Distinct
	// from CapKeyMint, which gates per-user hk- Cloud API key minting.) Allowlist:
	// IAM_KEY_ADMIN_APPS (empty/unset = deny all).
	CapKeyAdmin = AppAdminCapability{Name: "key", EnvVar: "IAM_KEY_ADMIN_APPS"}

	// CapOrgAdmin gates organization mutations: add/update/delete-organization.
	// Moving a user into the admin org == granting global admin, and deleting an
	// org is destructive, so org mutation is gated. UNLIKE the other new caps
	// this one is NOT empty by default: the brand consoles legitimately create
	// orgs via their app credential during onboarding, so the deploy allowlists
	// them (IAM_ORG_ADMIN_APPS=hanzo-console,lux-console,zoo-console,pars-console).
	// Note: project mutation (add/update/delete-project) is a SEPARATE,
	// un-gated surface — console onboarding's project creation is unaffected.
	CapOrgAdmin = AppAdminCapability{Name: "organization", EnvVar: "IAM_ORG_ADMIN_APPS"}

	// CapProviderAdmin gates provider mutations: add/update/delete-provider.
	// Providers hold OAuth/SMS/email/Web3 client secrets; a rogue provider can
	// redirect or intercept auth. Seeding at boot uses the in-process object
	// layer (object/init.go, init_data.json), NOT this HTTP controller, so the
	// deny-all default does not affect bootstrap. Allowlist: IAM_PROVIDER_ADMIN_APPS
	// (empty/unset = deny all; the optional init-providers reconcile Job, if used,
	// must be explicitly allowlisted here).
	CapProviderAdmin = AppAdminCapability{Name: "provider", EnvVar: "IAM_PROVIDER_ADMIN_APPS"}

	// CapSyncerAdmin gates syncer mutations: add/update/delete-syncer. A syncer
	// has DB credentials and can read/write the user store on a schedule.
	// Allowlist: IAM_SYNCER_ADMIN_APPS (empty/unset = deny all).
	CapSyncerAdmin = AppAdminCapability{Name: "syncer", EnvVar: "IAM_SYNCER_ADMIN_APPS"}

	// CapWebhookAdmin gates webhook mutations: add/update/delete-webhook. A
	// webhook can exfiltrate auth events to an attacker-controlled endpoint.
	// Allowlist: IAM_WEBHOOK_ADMIN_APPS (empty/unset = deny all).
	CapWebhookAdmin = AppAdminCapability{Name: "webhook", EnvVar: "IAM_WEBHOOK_ADMIN_APPS"}

	// CapTokenAdmin gates OAuth Token-object mutations: add/update/delete-token.
	// Forging a Token row mints a bearer token out of band. Allowlist:
	// IAM_TOKEN_ADMIN_APPS (empty/unset = deny all). (Normal token issuance via
	// the OAuth grant endpoints is unaffected — this gates only the admin CRUD.)
	CapTokenAdmin = AppAdminCapability{Name: "token", EnvVar: "IAM_TOKEN_ADMIN_APPS"}

	// CapMembershipAdmin gates the org-membership surface: reading another
	// user's membership set / an org's roster (get-memberships) and the invite
	// mutations (add-membership / delete-membership). Membership IS tenancy — a
	// row makes the org switchable in every token the user mints — so an app
	// that can write it can move users between tenants. The intended holder is
	// the platform team product (hanzo-team): its invite flow records the IAM
	// membership, and the per-tenant isolation is enforced by that trusted
	// caller, the same trust model as CapKeyMint. Allowlist:
	// IAM_MEMBERSHIP_ADMIN_APPS (empty/unset = deny all, fail-secure). Human
	// principals are unaffected: self-reads, org-admin roster reads, and
	// org-admin invites are authorized per-endpoint in
	// controllers/membership.go.
	CapMembershipAdmin = AppAdminCapability{Name: "membership", EnvVar: "IAM_MEMBERSHIP_ADMIN_APPS"}

	// CapServiceAccountRead gates LISTING service accounts — GET
	// /v1/iam/service-accounts?organization=<org> — which returns names +
	// metadata ONLY (accessKey/accessSecret masked by GetMaskedUsers, the
	// argon2id AccessSecretHash is json:"-" and never serializes). It is the
	// READ-ONLY counterpart to CapKeyMint: an app that only needs to enumerate
	// bots to sync them as hanzo.team members (hanzo-team) gets this instead of
	// the full mint-admin, so a leaked reader credential can never create,
	// rotate, or delete a service-account credential. Least privilege.
	//
	// A read grant is ALSO strictly org-scoped by the <org>-<app> naming
	// convention (controllers/service_account.go authorizeServiceAccountRead):
	// app/<org>-<app> may list ONLY organization=<org>, never another tenant's.
	// Allowlist: IAM_SA_LIST_ALLOWED_APPS (empty/unset = deny all, fail-secure).
	CapServiceAccountRead = AppAdminCapability{Name: "service-account-read", EnvVar: "IAM_SA_LIST_ALLOWED_APPS"}
)
View Source
var (
	ApiThroughput = metric.NewGaugeVec(metric.GaugeOpts{
		Name: "iam_api_throughput",
		Help: "The throughput of each api access",
	}, []string{"path", "method"})

	ApiLatency = metric.NewHistogramVec(metric.HistogramOpts{
		Name: "iam_api_latency",
		Help: "API processing latency in milliseconds",
	}, []string{"path", "method"})

	CpuUsage = metric.NewGaugeVec(metric.GaugeOpts{
		Name: "iam_cpu_usage",
		Help: "IAM cpu usage",
	}, []string{"cpuNum"})

	MemoryUsage = metric.NewGaugeVec(metric.GaugeOpts{
		Name: "iam_memory_usage",
		Help: "IAM memory usage in Byte",
	}, []string{"type"})

	TotalThroughput = metric.NewGauge(metric.GaugeOpts{
		Name: "iam_total_throughput",
		Help: "The total throughput of iam",
	})
)
View Source
var (
	DefaultApplication  = "hanzo-app"
	DefaultOrganization = "hanzo"
)
View Source
var DeviceAuthMap = sync.Map{}
View Source
var MigrationAuthzTables = []string{
	"authz_rule",
	"authz_user_rule",
	"authz_api_rule",
	"permission_rule",
}

MigrationAuthzTables enumerates the runtime-allocated authz adapter tables IAM creates OUTSIDE object/ormer.go's Sync2 registry (each is a flat (ptype, v0..v5) policy table). They are GLOBAL (authz is not per-org). The names match init.go's adapter inserts and permission_enforcer.go's `permission_rule` literal. authz_rule is the base adapter table created by the default `xorm.NewEngine`-backed authz.Enforcer; including it keeps the destination a strict superset so a source row in any of these tables is never silently dropped for "no destination table".

View Source
var OrgChildren = func(orgName string) ([]string, error) {
	orgs := []*Organization{}
	if err := ormer.Engine.Where("parent = ?", orgName).Find(&orgs); err != nil {
		return nil, err
	}
	names := make([]string, 0, len(orgs))
	for _, o := range orgs {
		names = append(names, o.Name)
	}
	return names, nil
}

OrgChildren returns the orgs whose Parent is orgName.

View Source
var (
	ResetLinkReg *regexp.Regexp
)
View Source
var (
	// SigningMethodMLDSA65 is the JWT signing method for ML-DSA-65.
	SigningMethodMLDSA65 *signingMethodMLDSA65
)
View Source
var (
	SiteMap = map[string]*Site{}
)
View Source
var UserAuthzEnforcerId = conf.AdminOrg + "/user-enforcer-" + conf.AdminApp

UserAuthzEnforcerId is the composite ID for the user authz enforcer in the admin org. Derived from conf.AdminOrg / conf.AdminApp at package init; immutable thereafter.

Functions

func AddAdapter

func AddAdapter(adapter *Adapter) (bool, error)

func AddApplication

func AddApplication(application *Application) (bool, error)

func AddCert

func AddCert(cert *Cert) (bool, error)

func AddEnforcer

func AddEnforcer(enforcer *Enforcer) (bool, error)

func AddForm

func AddForm(form *Form) (bool, error)

func AddGroup

func AddGroup(group *Group) (bool, error)

func AddGroups

func AddGroups(groups []*Group) (bool, error)

func AddGroupsInBatch

func AddGroupsInBatch(groups []*Group) (bool, error)

func AddInvitation

func AddInvitation(invitation *Invitation, lang string) (bool, error)

func AddKey

func AddKey(key *Key) (bool, error)

func AddLdap

func AddLdap(ldap *Ldap) (bool, error)

func AddMembership added in v1.31.31

func AddMembership(m *Membership) (bool, error)

AddMembership inserts a membership row.

func AddModel

func AddModel(model *Model) (bool, error)

func AddOrUpdateResource

func AddOrUpdateResource(resource *Resource) (bool, error)

func AddOrganization

func AddOrganization(organization *Organization) (bool, error)

func AddPermission

func AddPermission(permission *Permission) (bool, error)

func AddPermissions

func AddPermissions(permissions []*Permission) (bool, error)

func AddPermissionsInBatch

func AddPermissionsInBatch(permissions []*Permission) (bool, error)

func AddPolicy

func AddPolicy(id string, ptype string, policy []string) (bool, error)

func AddPrices

func AddPrices(price1 float64, price2 float64) float64

func AddProject

func AddProject(project *Project) (bool, error)

func AddProvider

func AddProvider(provider *Provider) (bool, error)

func AddRadiusAccounting

func AddRadiusAccounting(ra *RadiusAccounting) error

func AddRecord

func AddRecord(record *Record) bool

func AddResource

func AddResource(resource *Resource) (bool, error)

func AddRole

func AddRole(role *Role) (bool, error)

func AddRoles

func AddRoles(roles []*Role) bool

func AddRolesInBatch

func AddRolesInBatch(roles []*Role) bool

func AddRule

func AddRule(rule *Rule) (bool, error)

func AddServer

func AddServer(server *Server) (bool, error)

func AddSession

func AddSession(session *Session) (bool, error)

func AddSite

func AddSite(site *Site) (bool, error)

func AddSyncer

func AddSyncer(syncer *Syncer) (bool, error)

func AddTicket

func AddTicket(ticket *Ticket) (bool, error)

func AddTicketMessage

func AddTicketMessage(id string, message *TicketMessage) (bool, error)

func AddToVerificationRecord

func AddToVerificationRecord(user *User, provider *Provider, organization *Organization, remoteAddr, recordType, dest, code string) error

func AddToken

func AddToken(token *Token) (bool, error)

func AddUser

func AddUser(user *User, lang string) (bool, error)

func AddUserKeys

func AddUserKeys(user *User, isAdmin bool) (bool, error)

func AddUserToOriginalDatabase

func AddUserToOriginalDatabase(user *User) error

func AddUsers

func AddUsers(users []*User) (bool, error)

func AddUsersInBatch

func AddUsersInBatch(users []*User) (bool, error)
func AddWalletLink(link *WalletLink) (bool, error)

func AddWeb3Nonce added in v1.22.1

func AddWeb3Nonce(n *Web3Nonce) (bool, error)

func AddWebhook

func AddWebhook(webhook *Webhook) (bool, error)

func AdminAPIAdapterName added in v1.14.21

func AdminAPIAdapterName() string

func AdminAPIEnforcerName added in v1.14.21

func AdminAPIEnforcerName() string

func AdminAPIModelName added in v1.14.21

func AdminAPIModelName() string

func AdminAppOrganization added in v1.14.21

func AdminAppOrganization() string

AdminAppOrganization is the value to drop into Application.Organization / User.SignupApplication when wiring records to the admin app.

func AdminCertName added in v1.14.21

func AdminCertName() string

AdminCertName is the name of the JWT signing cert for the admin app.

func AdminPermissionName added in v1.14.21

func AdminPermissionName() string

AdminPermissionName is the name of the admin permission row.

func AdminUserAdapterName added in v1.14.21

func AdminUserAdapterName() string

AdminUserAdapterName / AdminAPIAdapterName are authz adapter names.

func AdminUserEnforcerName added in v1.14.21

func AdminUserEnforcerName() string

AdminUserEnforcerName / AdminAPIEnforcerName are authz enforcer names.

func AdminUserModelName added in v1.14.21

func AdminUserModelName() string

AdminUserModelName / AdminAPIModelName are authz model names.

func AdministersOrg added in v1.31.24

func AdministersOrg(user *User, targetOrg string) (bool, error)

AdministersOrg is the tenancy authz predicate: may user administer targetOrg?

super admin (owner == AdminOrg)       → everything
admin of an org at/above targetOrg    → that org and everything under it
anyone else                           → no

This is what makes a reseller's admin a real admin of the customers it onboarded, without handing them the platform.

func AppAllowedForCapability added in v1.25.4

func AppAllowedForCapability(principal string, cap AppAdminCapability) bool

AppAllowedForCapability reports whether the confidential-client principal ("app/<name>") is explicitly allowlisted for capability cap.

Fail-secure: an unset or empty allowlist denies every app. A principal that is not in "app/<name>" form returns false — this gate concerns app credentials only; human principals are authorized elsewhere and must NEVER be granted (or denied) by this function. The allowlist holds application NAMES, which equal the registered clientId for the synthetic app-user (see getUsernameByClientIdSecret), matching the IAM_BY_ATTRIBUTE_ALLOWLIST convention.

func AppNameFromPrincipal added in v1.25.4

func AppNameFromPrincipal(principal string) string

AppNameFromPrincipal returns the bare application name from an "app/<name>" principal, or "" if principal is not a confidential-client app principal.

func AppNameIsCapabilityReserved added in v1.28.18

func AppNameIsCapabilityReserved(appName string) bool

AppNameIsCapabilityReserved reports whether appName appears in ANY capability allowlist. Such a name is reserved for the admin-owned platform app; the client-credentials login path (getUsernameByClientIdSecret) refuses to mint an app principal for a NON-admin-owned application that collides one.

V5/Red#4 (capability name-collision escalation): without this, any authenticated customer could register <theirOrg>/<cap-app-name> (a fresh composite-PK row that passes validateAppName's "<org>-…" rule, e.g. organization=hanzo => name hanzo-console), authenticate with THEIR OWN clientSecret, resolve to principal "app/hanzo-console", and inherit the admin app's CapUserAdmin/CapKeyMint — reading any tenant's users + live hk- credentials cross-tenant. Reserving the name to admin-owned apps closes it: the admin-owned (admin, hanzo-console) row already occupies that identity, and a customer cannot create an admin-owned app.

func AppRouteAllowed added in v1.31.26

func AppRouteAllowed(appName, method, urlPath string) bool

AppRouteAllowed is the single coherent route-authorization decision for an "app/<name>" confidential-client principal. appName is the bare application name (the subName half of the "app/<name>" subject).

(1) capability-gated mutation -> allow iff allowlisted (controller re-checks)
(2) any other mutation        -> deny (an app is not an admin)
(3) everything else           -> allow (reads, OAuth/identity protocol,
                                  self-service, and the legitimate M2M
                                  surface: get-user money path, KMS reads,
                                  get-account, userinfo, token grants, ...)

func AuthorizeManagedRoleWrite added in v1.31.26

func AuthorizeManagedRoleWrite(caller CallerContext, targetOrg, targetName string, newUsers []string, isDelete bool) (managed bool, allowed bool, reason string)

AuthorizeManagedRoleWrite is the server-side authorization choke point for a single role mutation (add / update / delete). Contract:

managed=false            -> the target is not a team-managed role; the
                            caller proceeds with ordinary authz unchanged.
managed=true, allowed=false -> DENY (reason is safe to log).
managed=true, allowed=true  -> the mutation is authorized.

newUsers is the post-mutation membership (Role.Users) for add/update; it is used only for the org:owner orphan check. isDelete marks a delete.

It fails CLOSED: any error deriving the caller's authority denies.

func BackfillMemberships added in v1.31.31

func BackfillMemberships() (int, error)

BackfillMemberships records the HOME-org membership for every user that lacks one. One-shot, idempotent and live-safe — safe to run on every boot: users already carrying their home membership are skipped and no existing row is touched. It seeds ONLY the home org (User.Owner); team memberships are added explicitly. Returns the number of rows created.

func BatchEnforce

func BatchEnforce(permission *Permission, requests [][]string, permissionIds ...string) ([]bool, error)

func CheckAccountItemModifyRule

func CheckAccountItemModifyRule(accountItem *AccountItem, isAdmin bool, lang string) (bool, string)

func CheckApiPermission

func CheckApiPermission(userId string, organization string, path string, method string) (bool, error)

func CheckCasLogin

func CheckCasLogin(application *Application, lang string, service string) error

func CheckConsentRequired

func CheckConsentRequired(userObj *User, application *Application, scopeStr string) (bool, error)

CheckConsentRequired checks if user consent is required for the OAuth flow

func CheckEntryIp

func CheckEntryIp(clientIp string, user *User, application *Application, organization *Organization, lang string) error

func CheckFaceId

func CheckFaceId(user *User, faceId []float64, lang string) error

func CheckInvitationDefaultCode

func CheckInvitationDefaultCode(code string, defaultCode string, lang string) error

func CheckIpWhitelist

func CheckIpWhitelist(ipWhitelistStr string, lang string) error

func CheckLdapExist

func CheckLdapExist(ldap *Ldap) (bool, error)

func CheckLdapUserPassword

func CheckLdapUserPassword(user *User, password string, lang string, options ...bool) error

func CheckLoginPermission

func CheckLoginPermission(userId string, application *Application) (bool, error)

func CheckOrgParent added in v1.31.24

func CheckOrgParent(orgName, parent string) error

CheckOrgParent validates a proposed Parent for org before it is persisted. It is the ONLY place the forest invariant is enforced: no self-parent, the parent must exist, the parent must not be a descendant of org (that closes a cycle), and the resulting chain must fit MaxOrgDepth.

func CheckPassword

func CheckPassword(user *User, password string, lang string, options ...bool) error

func CheckPasswordComplexity

func CheckPasswordComplexity(user *User, password string, lang string) string

func CheckPasswordComplexityByOrg

func CheckPasswordComplexityByOrg(organization *Organization, password string, lang string) string

func CheckPasswordNotSameAsCurrent

func CheckPasswordNotSameAsCurrent(user *User, newPassword string, organization *Organization) bool

CheckPasswordNotSameAsCurrent checks if the new password is different from the current password

func CheckPermissionForUpdateUser

func CheckPermissionForUpdateUser(oldUser, newUser *User, isAdmin bool, isSuperAdmin bool, allowDisplayNameEmpty bool, lang string) (bool, string)

func CheckServiceAccountName added in v1.31.1

func CheckServiceAccountName(name string) string

CheckServiceAccountName validates that name is a well-formed IAM username (util.ReUserName: alphanumerics, single -/_/. separators, no leading / trailing / consecutive separators). Returns "" when valid, else a reason. The <org>-<agent> convention already satisfies this for well-formed org and agent segments; this guards against callers passing raw, unvalidated input.

func CheckSigninCode

func CheckSigninCode(user *User, dest, code, lang string) error

func CheckToEnableCaptcha

func CheckToEnableCaptcha(application *Application, organization, username string, clientIp string) (bool, error)

func CheckUpdateUser

func CheckUpdateUser(oldUser, user *User, lang string) string

func CheckUserEmailVerifiedRaw added in v1.31.33

func CheckUserEmailVerifiedRaw(owner, name string) bool

CheckUserEmailVerifiedRaw bypasses xorm and reads the email_verified boolean directly from the DB — the SAME xorm bool-deserialization nondeterminism that affects is_admin (CheckUserIsAdminRaw) also affects email_verified (Red MED: get-account read true while the login path read false). Callers that GATE a privilege on verification (e.g. org-scoped email-domain promotion) MUST use this authoritative read, never the possibly-misread user.EmailVerified. Fail-CLOSED: any DB error returns false (treated as unverified → not promoted).

func CheckUserIsAdminRaw

func CheckUserIsAdminRaw(owner, name string) bool

CheckUserIsAdminRaw bypasses xorm ORM and queries the database directly to check the is_admin boolean field. This works around a known issue where xorm may fail to correctly deserialize boolean columns from Postgres, causing user.IsAdmin to always read as false.

func CheckUserPermission

func CheckUserPermission(requestUserId, userId string, strict bool, lang string) (bool, error)

func CheckUserSignup

func CheckUserSignup(application *Application, organization *Organization, authForm *form.AuthForm, lang string) string

func CheckUsername

func CheckUsername(username string, lang string) string

func CheckUsernameWithEmail

func CheckUsernameWithEmail(username string, lang string) string

func CheckVerifyCodeWithLimit

func CheckVerifyCodeWithLimit(user *User, dest, code, lang string) error

func CleanupExpiredRevokedTokens

func CleanupExpiredRevokedTokens() (int64, error)

CleanupExpiredRevokedTokens removes revoked tokens that have passed their original expiration time. This prevents the revocation table from growing indefinitely.

func CleanupTokens

func CleanupTokens(tokenRetentionIntervalAfterExpiry int) error

func ClearThroughputPerSecond

func ClearThroughputPerSecond()

func ClearUserOAuthProperties

func ClearUserOAuthProperties(user *User, providerType string) (bool, error)

func ContextWithOrgEngine

func ContextWithOrgEngine(ctx context.Context, owner string) context.Context

ContextWithOrgEngine stores an org-scoped engine in the context.

func ConvertCurrency

func ConvertCurrency(amount float64, fromCurrency, toCurrency string) float64

ConvertCurrency converts an amount from one currency to another using exchange rates

func CopyUsersPerOrg added in v1.22.1

func CopyUsersPerOrg(target *MigrationTarget, rows []map[string]any) (copied, dropped int64, orgs int, err error)

CopyUsersPerOrg routes User rows to their per-org enveloped engines, grouped by the row's `owner` (the runtime's orgEngine routing). Each row is a column→value map whose values are already the faithful Go types (nil for NULL). Returns (copied, dropped, distinct-orgs, err); dropped counts duplicate-pkey rows that INSERT OR IGNORE skipped.

func CreateTables

func CreateTables()

func DeleteAdapter

func DeleteAdapter(adapter *Adapter) (bool, error)

func DeleteAllUserSessions

func DeleteAllUserSessions(owner string, name string) (bool, error)

func DeleteApplication

func DeleteApplication(application *Application, isSuperAdmin bool) (bool, error)

func DeleteBeegoSession

func DeleteBeegoSession(sessionIds []string)

func DeleteCert

func DeleteCert(cert *Cert) (bool, error)

func DeleteEnforcer

func DeleteEnforcer(enforcer *Enforcer) (bool, error)

func DeleteFile

func DeleteFile(provider *Provider, objectKey string, lang string) error

func DeleteForm

func DeleteForm(form *Form) (bool, error)

func DeleteGroup

func DeleteGroup(group *Group) (bool, error)

func DeleteGroupForUser

func DeleteGroupForUser(user string, group string) (bool, error)

func DeleteInvitation

func DeleteInvitation(invitation *Invitation) (bool, error)

func DeleteKey

func DeleteKey(key *Key) (bool, error)

func DeleteLdap

func DeleteLdap(ldap *Ldap) (bool, error)

func DeleteMembership added in v1.31.31

func DeleteMembership(userId, org string) (bool, error)

DeleteMembership removes a user from an org (revokes the ability to act in it).

func DeleteModel

func DeleteModel(model *Model) (bool, error)

func DeleteOrganization

func DeleteOrganization(organization *Organization) (bool, error)

func DeletePermission

func DeletePermission(permission *Permission) (bool, error)

func DeleteProject

func DeleteProject(project *Project) (bool, error)

func DeleteProvider

func DeleteProvider(provider *Provider) (bool, error)

func DeleteRadiusAccounting

func DeleteRadiusAccounting(ra *RadiusAccounting) error

func DeleteResource

func DeleteResource(resource *Resource) (bool, error)

func DeleteRole

func DeleteRole(role *Role) (bool, error)

func DeleteRule

func DeleteRule(rule *Rule) (bool, error)

func DeleteServer

func DeleteServer(server *Server) (bool, error)

func DeleteServiceAccount added in v1.31.1

func DeleteServiceAccount(user *User) (bool, error)

DeleteServiceAccount permanently removes the service-account principal (and, via DeleteUser, its associated rows). Prefer RevokeServiceAccountKey when you only need to disable the credential but keep the identity.

func DeleteSession

func DeleteSession(id, curSessionId string) (bool, error)

func DeleteSessionId

func DeleteSessionId(id string, sessionId string) (bool, error)

func DeleteSite

func DeleteSite(site *Site) (bool, error)

func DeleteSyncer

func DeleteSyncer(syncer *Syncer) (bool, error)

func DeleteTicket

func DeleteTicket(ticket *Ticket) (bool, error)

func DeleteToken

func DeleteToken(token *Token) (bool, error)

func DeleteUser

func DeleteUser(user *User) (bool, error)
func DeleteWalletLink(link *WalletLink) (bool, error)

func DeleteWebhook

func DeleteWebhook(webhook *Webhook) (bool, error)

func DeliverOTPViaNotify added in v1.18.7

func DeliverOTPViaNotify(ctx context.Context, in NotifySendInput) error

DeliverOTPViaNotify is the entry point the OTP senders call when NotifyDeliveryEnabled() is true. Returns nil on success, error otherwise.

func DeviceApprovalCrossTenantError added in v1.28.5

func DeviceApprovalCrossTenantError(user *User, deviceApp *Application) error

DeviceApprovalCrossTenantError refuses a device approval when the approving user's organization differs from the organization that owns the device authorization's application. The device_code carries the app it was issued for (DeviceAuthCache.ApplicationId, resolved to deviceApp); the approving identity comes from the browser session. A user in org A must never be able to approve a device sign-in bound to an app in org B (cross-tenant confused deputy — e.g. the same-named superuser seeded in every brand). This is also the invariant the downstream token mint depends on: GetDeviceCodeToken looks the approver up via GetUserByFields(deviceApp.Organization, UserName), which only resolves when the approver actually belongs to that org. Pure (no DB) so the tenant boundary is unit-testable. Fail-closed: a nil user/app, or an app with an empty organization, refuses.

func DialWithCert

func DialWithCert(SshUser string, CertId string, SshHost string, SshPort int) (*ssh.Client, error)

func DialWithPassword

func DialWithPassword(SshUser string, SshPassword string, SshHost string, SshPort int) (*ssh.Client, error)

func DialWithPrivateKey

func DialWithPrivateKey(SshUser string, PrivateKey []byte, SshHost string, SshPort int) (*ssh.Client, error)

func DisableVerificationCode

func DisableVerificationCode(dest string) error

func DisabledMultiFactorAuth

func DisabledMultiFactorAuth(user *User) error

func DownloadAndUpload

func DownloadAndUpload(url string, fullFilePath string, lang string) (err error)

func DropBogusEnforcerColumn added in v1.22.1

func DropBogusEnforcerColumn(global *xorm.Engine) error

DropBogusEnforcerColumn removes the spurious `enforcer TEXT NULL` column that xorm Sync2 adds to the `enforcer` table from object.Enforcer's anonymous *authz.Enforcer embed (no `xorm:"-"` tag). It is invisible on Postgres but materialises on SQLite and then triggers a cascade-scan failure. The Enforcer model lives on the GLOBAL engine, so the drop is applied there. A fresh Sync2 re-adds the column until the upstream struct tags the embed, hence this is re-applied by every migrator before copy. SELECTs from the source must also omit this column (the source — if it was itself migrated — may or may not have it; a per-column reader that reads the destination column set avoids it).

func DumpToFile

func DumpToFile(filePath string) error

func Enforce

func Enforce(permission *Permission, request []string, permissionIds ...string) (bool, error)

func EnforceNotifyDeliveryGuard added in v1.18.7

func EnforceNotifyDeliveryGuard()

EnforceNotifyDeliveryGuard runs at boot: validate config once, cache it, install the ZAP deliverer. IAM_NOTIFY_ZAP_ADDR=stub or "" disables delivery.

func EnforceOTPProviderGuard added in v1.18.4

func EnforceOTPProviderGuard()

EnforceOTPProviderGuard is a no-op. Kept so iamserver.Init() compiles unchanged after the env-direct provider paths were ripped.

func EnsureMembership added in v1.31.31

func EnsureMembership(userId, org, role string) (bool, error)

EnsureMembership records that userId may act in org with the given role. It is the ONE way a membership is created — composed into every org-birth path and the boot backfill. Idempotent: it ADDS a row only when the (user, org) pair is absent, and never downgrades an existing role (an existing owner stays owner even if re-ensured as member). Returns whether it created a row.

func EnsureTeamRolesForOrg added in v1.31.26

func EnsureTeamRolesForOrg(org string) error

EnsureTeamRolesForOrg idempotently seeds the app-scoped role catalog (and the bound Casbin permissions) for an org. It creates only what is missing, so it is safe to call on org creation and again on demand. Role creation is the hard requirement (membership + the guard depend on it); permission creation is best-effort defense-in-depth for the enforce path and never blocks role seeding.

func EvictAppCache

func EvictAppCache(owner, name string)

EvictAppCache removes a cached application. Call after any write.

func EvictAppCacheByClientId

func EvictAppCacheByClientId(clientId string)

EvictAppCacheByClientId removes a cached client_id mapping.

func EvictCertCache

func EvictCertCache(name string)

EvictCertCache removes a cached cert and its parsed key.

func EvictOrgCache

func EvictOrgCache(owner, name string)

EvictOrgCache removes a cached organization. Call after any write.

func EvictPermCache

func EvictPermCache(userId string)

EvictPermCache removes only the permission graph for userId. Call after any role/permission assignment change.

func EvictUserCache

func EvictUserCache(owner, name string)

EvictUserCache removes the user row and permission graph from cache. Call this after any write that modifies a User record.

func ExpireTokenByAccessToken

func ExpireTokenByAccessToken(accessToken string) (bool, *Application, *Token, error)

func ExpireTokenByUser

func ExpireTokenByUser(owner, username string) (bool, error)

func ExtendGroupWithUsers

func ExtendGroupWithUsers(group *Group) error

func ExtendGroupsWithUsers

func ExtendGroupsWithUsers(groups []*Group) error

func ExtendUserWithRolesAndPermissions

func ExtendUserWithRolesAndPermissions(user *User) (err error)

func FromProviderToIdpInfo

func FromProviderToIdpInfo(ctx *context.Context, provider *Provider) (*idp.ProviderInfo, error)

func GenerateCasToken

func GenerateCasToken(userId string, service string) (string, error)

func GenerateId

func GenerateId()

func GenerateIdForNewUser

func GenerateIdForNewUser(application *Application) (string, error)

func GenerateSamlRequest

func GenerateSamlRequest(id, relayState, host, lang string) (auth string, method string, err error)

func GetAccessTokenByUser

func GetAccessTokenByUser(user *User, host string) (string, error)

func GetAcmeClient

func GetAcmeClient(useProxy bool) (*lego.Client, error)

func GetAdapterCount

func GetAdapterCount(owner, field, value string) (int64, error)

func GetAllActions

func GetAllActions(userId string) ([]string, error)

func GetAllObjects

func GetAllObjects(userId string) ([]string, error)

func GetAllRoles

func GetAllRoles(userId string) ([]string, error)

func GetApiKeyToken

func GetApiKeyToken(application *Application, accessKey string, accessSecret string, scope string, host string) (*Token, *TokenError, error)

GetApiKeyToken exchanges a user's API key (access_key + access_secret) for a user-bound OAuth token. This enables machine-to-machine authentication using long-lived API keys instead of username/password (ROPC).

func GetApplicationCount

func GetApplicationCount(owner, field, value string) (int64, error)

func GetAuthorizationCodeToken

func GetAuthorizationCodeToken(application *Application, clientSecret string, code string, verifier string, resource string) (*Token, *TokenError, error)

GetAuthorizationCodeToken Authorization code flow

func GetBuiltInModel

func GetBuiltInModel(modelText string) (authzmodel.Model, error)

func GetCaptcha

func GetCaptcha() (string, []byte, error)

func GetCertCount

func GetCertCount(owner, field, value string) (int64, error)

func GetClientCredentialsToken

func GetClientCredentialsToken(application *Application, clientSecret string, scope string, resource string, host string) (*Token, *TokenError, error)

GetClientCredentialsToken Client Credentials flow GetClientCredentialsToken mints an OAuth2 client_credentials access token for a confidential client. `resource` is the RFC 8707 resource indicator: when set it becomes the token's sole `aud`, so a machine client can request a token scoped to a SPECIFIC resource server (e.g. IAM minting a token whose aud is "hanzo-cloud" to call cloud's notify surface) that lands deterministically in that server's fixed audience allowlist, independent of which app minted it. Empty `resource` preserves the default aud == the app's own clientId.

func GetDashboard

func GetDashboard(owner string) (*map[string][]int64, error)

func GetDeviceCodeToken added in v1.28.2

func GetDeviceCodeToken(application *Application, deviceAuth *DeviceAuthCache, nonce string, host string) (*TokenWrapper, *TokenError, error)

GetDeviceCodeToken issues a token for the user who approved a device authorization request (RFC 8628). Identity, scope, and approval all come from deviceAuth — the device-auth cache entry the controller consumed — and NEVER from request parameters: a caller cannot pass a username. The function is fail-closed and safe regardless of caller — it re-asserts the authorization was approved (deviceAuthApprovedError) before minting, so the "the controller already verified this" precondition is enforced here, not merely assumed. There is deliberately no secret/password check: the human authenticating and approving interactively at the verification URI is the authentication.

func GetDomainExpireTime

func GetDomainExpireTime(domainName string) (string, error)

func GetEnforcerCount

func GetEnforcerCount(owner, field, value string) (int64, error)

func GetExchangeRate

func GetExchangeRate(fromCurrency, toCurrency string) float64

GetExchangeRate returns the exchange rate from fromCurrency to toCurrency

func GetExistUuids

func GetExistUuids(owner string, uuids []string) ([]string, error)

func GetExportFilePath

func GetExportFilePath() string

func GetFailedSigninConfigByUser

func GetFailedSigninConfigByUser(user *User) (int, int, error)

func GetFaviconUrl

func GetFaviconUrl(htmlStr string) (string, error)

func GetFilteredPolicies

func GetFilteredPolicies(id string, ptype string, fieldIndex int, fieldValues ...string) ([]*util.AuthzRule, error)

func GetFilteredPoliciesMulti

func GetFilteredPoliciesMulti(id string, filters []Filter) ([]*util.AuthzRule, error)

GetFilteredPoliciesMulti applies multiple filters to policies Doing this in our loop is more efficient than using GetFilteredGroupingPolicy / GetFilteredPolicy which iterates over all policies again and again

func GetFormCount

func GetFormCount(owner string, field, value string) (int64, error)

func GetGlobalCertsCount

func GetGlobalCertsCount(field, value string) (int64, error)

func GetGlobalKeyCount

func GetGlobalKeyCount(field, value string) (int64, error)

func GetGlobalProviderCount

func GetGlobalProviderCount(field, value string) (int64, error)

func GetGlobalUserCount

func GetGlobalUserCount(field, value string) (int64, error)

func GetGroupCount

func GetGroupCount(owner, field, value string) (int64, error)

func GetGroupUserCount

func GetGroupUserCount(groupId string, field, value string) (int64, error)

func GetGroupWithPrefix

func GetGroupWithPrefix(group string) string

func GetGroupWithoutPrefix

func GetGroupWithoutPrefix(group string) string

func GetGroupsHaveChildrenMap

func GetGroupsHaveChildrenMap(groups []*Group) (map[string]*Group, error)

func GetIdvProviderFromProvider

func GetIdvProviderFromProvider(provider *Provider) idv.IdvProvider

func GetImplicitToken

func GetImplicitToken(application *Application, username string, scope string, nonce string, host string) (*Token, *TokenError, error)

GetImplicitToken Implicit flow

func GetInitDataDiagnostics

func GetInitDataDiagnostics() map[string]interface{}

GetInitDataDiagnostics returns a safe summary of init data sync status. Does NOT expose DB schema, indexes, raw SQL, or internal state in production.

func GetInvitationCount

func GetInvitationCount(owner, field, value string) (int64, error)

func GetJwksBytes added in v1.14.15

func GetJwksBytes(applicationName string) (body []byte, etag string, err error)

GetJwksBytes returns the JSON-encoded JWKS for the given application (empty == global). Reads are lock-free on a cache hit; misses do one computation under a single-flight mutex.

The returned []byte is owned by the cache — callers MUST NOT mutate it. Treat it as read-only.

func GetJwtBearerToken

func GetJwtBearerToken(application *Application, assertion string, scope string, nonce string, host string) (*Token, *TokenError, error)

GetJwtBearerToken RFC 7523

func GetKeyCount

func GetKeyCount(owner, field, value string) (int64, error)

func GetModelCount

func GetModelCount(owner, field, value string) (int64, error)

func GetOAuthToken

func GetOAuthToken(grantType string, clientId string, clientSecret string, code string, verifier string, scope string, nonce string, username string, password string, host string, refreshToken string, tag string, avatar string, lang string, subjectToken string, subjectTokenType string, assertion string, clientAssertion string, clientAssertionType string, audience string, resource string, accessKey string, accessSecret string) (interface{}, error)

func GetOnlineUserCount

func GetOnlineUserCount(owner string, isOnline int) (int64, error)

func GetOrgEngineFromContext

func GetOrgEngineFromContext(ctx context.Context) *xorm.Engine

GetOrgEngineFromContext retrieves the org-scoped engine from context. Falls back to the global engine if not set.

func GetOrganizationApplicationCount

func GetOrganizationApplicationCount(owner, organization, field, value string) (int64, error)

func GetOrganizationCount

func GetOrganizationCount(owner, name, field, value string) (int64, error)

func GetPasswordToken

func GetPasswordToken(application *Application, username string, password string, scope string, host string) (*Token, *TokenError, error)

GetPasswordToken Resource Owner Password Credentials flow

func GetPermissionCount

func GetPermissionCount(owner, field, value string) (int64, error)

func GetPolicies

func GetPolicies(id string) ([]*util.AuthzRule, error)

func GetProjectCount

func GetProjectCount(owner, field, value string) (int64, error)

func GetProviderCount

func GetProviderCount(owner, field, value string) (int64, error)

func GetRecordCount

func GetRecordCount(field, value string, filterRecord *Record) (int64, error)

func GetResourceCount

func GetResourceCount(owner, user, field, value string) (int64, error)

func GetRevokedTokenCount

func GetRevokedTokenCount(owner string, application string) (int64, error)

GetRevokedTokenCount returns the count of revoked tokens for an application.

func GetRoleCount

func GetRoleCount(owner, field, value string) (int64, error)

func GetRuleCount

func GetRuleCount(owner, field, value string) (int64, error)

func GetSamlRedirectAddress

func GetSamlRedirectAddress(owner string, application string, relayState string, samlRequest string, host string, username string, loginHint string) string

func GetSamlResponse

func GetSamlResponse(application *Application, user *User, samlRequest string, host string) (string, string, string, error)

GetSamlResponse generates a SAML2.0 response parameter samlRequest is saml request in base64 format

func GetServerCount

func GetServerCount(owner, field, value string) (int64, error)

func GetSession

func GetSession(owner string, offset, limit int, field, value, sortField, sortOrder string) *xorm.Session

func GetSessionCount

func GetSessionCount(owner, field, value string) (int64, error)

func GetSessionForUser

func GetSessionForUser(owner string, offset, limit int, field, value, sortField, sortOrder string) *xorm.Session

func GetSiteCount

func GetSiteCount(owner, field, value string) (int64, error)

func GetSyncerCount

func GetSyncerCount(owner, organization, field, value string) (int64, error)

func GetTicketCount

func GetTicketCount(owner, field, value string) (int64, error)

func GetTokenCount

func GetTokenCount(owner, organization, field, value string) (int64, error)

func GetTokenExchangeToken

func GetTokenExchangeToken(application *Application, clientSecret string, subjectToken string, subjectTokenType string, audience string, scope string, host string) (*Token, *TokenError, error)

GetTokenExchangeToken Token Exchange Grant (RFC 8693) Exchanges a subject token for a new token with different audience or scope

func GetTruncatedPath

func GetTruncatedPath(provider *Provider, fullFilePath string, limit int) string

func GetUploadFileUrl

func GetUploadFileUrl(provider *Provider, fullFilePath string, hasTimestamp bool) (string, string)

func GetUserCount

func GetUserCount(owner, field, value string, groupName string) (int64, error)

func GetUserField

func GetUserField(user *User, field string) string

func GetUserFieldStringValue

func GetUserFieldStringValue(user *User, fieldName string) (bool, string, error)

func GetUserOAuthAccessToken

func GetUserOAuthAccessToken(user *User, providerType string) string

GetUserOAuthAccessToken retrieves the OAuth access token for a specific provider

func GetUserOAuthRefreshToken

func GetUserOAuthRefreshToken(user *User, providerType string) string

GetUserOAuthRefreshToken retrieves the OAuth refresh token for a specific provider

func GetUserTeamRoleKeys added in v1.31.26

func GetUserTeamRoleKeys(userId, org string) ([]string, error)

GetUserTeamRoleKeys returns the catalog role keys the user holds within a given org. Only roles owned by `org` whose membership includes the user AND whose Name is a managed catalog key are returned. This is the caller's effective authority, fed into teamrole.CheckAssignment.

func GetValidationBySaml

func GetValidationBySaml(samlRequest string, host string) (string, string, error)

GetValidationBySaml * @ret1: saml response @ret2: the service URL who requested to issue this token @ret3: error

func GetVerificationCount

func GetVerificationCount(owner, field, value string) (int64, error)

func GetVerifyType

func GetVerifyType(username string) (verificationCodeType string)

func GetWebAuthnObject

func GetWebAuthnObject(host string) (*webauthn.WebAuthn, error)

func GetWebhookCount

func GetWebhookCount(owner, organization, field, value string) (int64, error)

func GetWechatMiniProgramToken

func GetWechatMiniProgramToken(application *Application, code string, host string, username string, avatar string, lang string) (*Token, *TokenError, error)

GetWechatMiniProgramToken Wechat Mini Program flow

func GroupChangeTrigger

func GroupChangeTrigger(oldName, newName string) error

func GroupPermissionsByModelAdapter

func GroupPermissionsByModelAdapter(permissions []*Permission) map[string][]string

GroupPermissionsByModelAdapter group permissions by model and adapter. Every model and adapter will be a key, and the value is a list of permission ids. With each list of permission ids have the same key, we just need to init the enforcer and do the enforce/batch-enforce once (with list of permission ids as the policyFilter when the enforcer load policy).

func HasRoleDefinition

func HasRoleDefinition(m authzmodel.Model) bool

func HasUserByField

func HasUserByField(organizationName string, field string, value string) bool

func InitAdapter

func InitAdapter()

func InitCleanupTokens

func InitCleanupTokens()

func InitConfig

func InitConfig()

func InitDb

func InitDb()

InitDb is the bootstrap entrypoint: it seeds the admin org, the IAM application, the bootstrap admin user, and the authz primitives (model, adapter, enforcer, permission). All seeds are idempotent — if a row already exists with the canonical (owner, name), the seed is skipped.

func InitDefaultStorageProvider

func InitDefaultStorageProvider()

func InitFlag

func InitFlag()

func InitFromFile

func InitFromFile()

func InitKMS

func InitKMS()

InitKMS connects to the native-ZAP base KMS plugin, fetches the bootstrap secrets, and overrides Beego config values for infrastructure secrets (e.g. dataSourceName). Must be called before InitAdapter().

When KMS_ADDR is unset, KMS is disabled and this function is a no-op. The caller is expected to fall back to plain environment variables in that case.

func InitLdapAutoSynchronizer

func InitLdapAutoSynchronizer()

func InitRuleMap

func InitRuleMap()

func InitSiteMap

func InitSiteMap()

func InitUserManager

func InitUserManager()

func InsertRows added in v1.22.1

func InsertRows(eng *xorm.Engine, table string, rows []map[string]any) (copied, dropped int64, err error)

InsertRows inserts faithfully-typed rows into the destination engine inside a single transaction. INSERT OR IGNORE drops a source-side duplicate-pkey row instead of aborting the whole table (the report surfaces the delta). Raw database/sql is used (NOT xorm.Session.Exec) so a Go nil is written as SQL NULL rather than coerced to ""/0/false — see the NULL-fidelity note at the top of this file. Each row's value for a column MUST already be the destination Go type produced by the source reader (nil | int64 | float64 | string | []byte); no coercion happens here, by design.

Returns (copied, dropped, err): copied = rows landed, dropped = duplicates.

func InterimUpdateRadiusAccounting

func InterimUpdateRadiusAccounting(oldRa *RadiusAccounting, newRa *RadiusAccounting, stop bool) error

func InvalidateJwksCache added in v1.14.15

func InvalidateJwksCache()

InvalidateJwksCache clears the cache, forcing the next GetJwksBytes call to recompute. Wire this into any code path that mutates a Cert row (key rotation, cert delete, application cert reassignment).

func IsAllowSend

func IsAllowSend(user *User, remoteAddr, recordType string, application *Application) error

func IsAncestorOrg added in v1.31.24

func IsAncestorOrg(ancestor, org string) (bool, error)

IsAncestorOrg reports whether ancestor is at or above org in the tenancy chain. Same-org is true: an org trivially administers itself, which keeps callers from special-casing the self check and accidentally dropping it.

func IsAppUser

func IsAppUser(userId string) bool

func IsClientCredentialsClaim added in v1.31.1

func IsClientCredentialsClaim(claims *Claims, application *Application) bool

IsClientCredentialsClaim reports whether verified `claims` (already signature-checked against `application`'s cert) is a genuine client_credentials confidential-client token — i.e. the synthetic application-user minted by GetClientCredentialsToken, not a human user JWT (authorization_code / password) that merely carries Type="application".

Pure: no DB, no session. `claims` MUST already be signature-verified by the caller; this only inspects the claim shape.

func IsGrantTypeValid

func IsGrantTypeValid(method string, grantTypes []string) bool

IsGrantTypeValid Check if grantType is allowed in the current application authorization_code is allowed by default

func IsInternalServiceApplication added in v1.31.17

func IsInternalServiceApplication(app *Application) bool

IsInternalServiceApplication reports whether app is an IAM-provisioned internal machine identity whose client_credentials grant must be refused on the PUBLIC token endpoint (minted in-process only).

It is TRUE when EITHER the explicit marker is present (primary) OR the app follows the reserved "<org>-iam" naming (fallback, so stripping the Description cannot re-open the public grant). Admin-only app creation owns this namespace.

func IsNeedPromptMfa

func IsNeedPromptMfa(org *Organization, user *User) bool

func IsOriginAllowed

func IsOriginAllowed(origin string) (bool, error)

func IsScopeValid

func IsScopeValid(scope string, application *Application) bool

IsScopeValid checks whether all space-separated scopes in the scope string are defined in the application's Scopes list (including regex expansion). If the application has no defined scopes, every scope is considered valid (backward-compatible behaviour).

func IsScopeValidAndExpand

func IsScopeValidAndExpand(scope string, application *Application) (string, bool)

IsScopeValidAndExpand expands any regex patterns in the space-separated scope string against the application's configured scopes. Literal scopes are kept as-is after verifying they exist in the allowed list. Regex scopes are matched against every allowed scope name; all matches replace the pattern. If the application has no defined scopes, the original scope string is returned unchanged (backward-compatible behaviour). Returns the expanded scope string and whether the scope is valid.

func IsServedHost added in v1.28.2

func IsServedHost(host string) bool

IsServedHost reports whether `host` belongs to a domain IAM is configured to serve. When no allowlist is configured (e.g. local dev) it returns true so behavior is unchanged. Used to reject an attacker-supplied X-Forwarded-Host.

func IsServiceAccount added in v1.31.1

func IsServiceAccount(u *User) bool

IsServiceAccount reports whether u is a service-account principal.

func IsSessionDuplicated

func IsSessionDuplicated(id string, sessionId string) (bool, error)

func IsSupportedWeb3Chain added in v1.22.1

func IsSupportedWeb3Chain(chain wc.Chain) bool

IsSupportedWeb3Chain reports whether a chain family is one this build knows. Per-chain *verifier* readiness is a separate gate (the frontend ENABLED_CHAINS list); an enabled-but-unverifiable chain fails closed in VerifyProof.

func IsTokenRevoked

func IsTokenRevoked(tokenValue string) (bool, error)

IsTokenRevoked checks if a token has been revoked.

func IsTokenRevokedByHash

func IsTokenRevokedByHash(tokenHash string) (bool, error)

IsTokenRevokedByHash checks if a token has been revoked by its hash.

func LinkUserAccount

func LinkUserAccount(user *User, field string, value string) (bool, error)

func MayLinkByVerifiedEmail added in v1.31.26

func MayLinkByVerifiedEmail(enableLinkWithEmail bool, email string, emailVerified bool) bool

MayLinkByVerifiedEmail reports whether a social ("OAuth") signup may attach its new provider identity to an EXISTING account located by email — i.e. whether the provider's email is trustworthy enough to prove the social user owns that account.

SECURITY (account takeover, Red HIGH-2): linking a new identity into an existing account is an account mutation that needs CONSENT. A provider email is consent ONLY when the provider ASSERTS it verified the user controls that address AND the deployment opted into email linking (EnableLinkWithEmail). An unverified provider email is attacker-controllable, so it must never resolve a login to an account that merely shares the address. This is the OAuth analogue of the wallet rule in web3_auth.go, which refuses to bind an identity by address alone.

DEPLOYMENT: emailVerified is only as trustworthy as the provider that asserts it (each idp/*.go sets it from its own verified-email signal — Google verifies its ID token's signature/issuer/audience, GitHub reads /user/emails verified). Enable EnableLinkWithEmail only for providers that actually confirm address ownership. A self-hosted OIDC/GitLab instance with email confirmation disabled can stamp a confirmed flag on an address its user never proved they own, which would then link into a matching local account; scope email linking to providers whose verification you trust. PURE — no DB — so it is unit-testable.

func MfaRecover

func MfaRecover(user *User, recoveryCode string) error

func MigratePhoneToE164 added in v1.18.7

func MigratePhoneToE164(engine *xorm.Engine) (updated, skipped int, err error)

MigratePhoneToE164 walks every user row whose `phone` does not start with '+' and rewrites it to its canonical E.164 form using the adjacent `country_code` column. Idempotent — re-running it is a cheap no-op once every row is already E.164.

Rows whose `(phone, country_code)` pair cannot be parsed by libphonenumber are LEFT UNCHANGED and logged. Those are typically fixture rows (e.g. `1337000001`, `9999999999`) that were never real dialable numbers; they continue to be reachable via the by-attribute endpoint's literal fallback, but they will not collide with new E.164 writes.

Schema change: NONE. The migration mutates row values inside the existing `phone` VARCHAR column; no DDL is required.

Returns (updated, skipped, error). `updated` is the count of rows whose phone was rewritten to E.164. `skipped` is the count of rows whose phone could not be parsed and was left alone.

func MintServiceAccountKey added in v1.31.1

func MintServiceAccountKey(user *User, isAdmin bool) (string, string, error)

MintServiceAccountKey (re)generates the service account's API key: a fresh hk- access key (the plaintext lookup handle) and a fresh hk- secret whose argon2id hash — NOT the secret itself — is persisted. The raw secret is returned once; any prior key is immediately invalidated (rotation).

The write is column-scoped to exactly the three credential columns so it can never re-run/re-validate the (org-prefixed) Name, matching the AddUserKeys rationale, and so it never touches password or profile fields.

func MoveUserToOrg

func MoveUserToOrg(user *User, newOrg string) (bool, error)

MoveUserToOrg changes a user's owner (organization) field. Since owner is part of the composite primary key in IAM, this uses xorm's Exec for a direct SQL UPDATE.

func NewSamlResponse

func NewSamlResponse(application *Application, user *User, host string, certificate string, destination string, iss string, requestId string, redirectUri []string) (*etree.Element, error)

NewSamlResponse returns a saml2 response

func NewSamlResponse11

func NewSamlResponse11(application *Application, user *User, requestID string, host string) (*etree.Element, error)

NewSamlResponse11 return a saml1.1 response(not 2.0)

func NotifyDeliveryEnabled added in v1.18.7

func NotifyDeliveryEnabled() bool

NotifyDeliveryEnabled returns true when EnforceNotifyDeliveryGuard resolved a usable ZAP address. The OTP senders branch on this before sending.

func NotifyIdempotencyKey added in v1.31.17

func NotifyIdempotencyKey(tenant, recipient, otp string) string

NotifyIdempotencyKey derives a stable per-OTP idempotency key from the tenant, recipient, and one-time code. The code is fresh per SendVerificationCode call, so this uniquely identifies ONE OTP send — and is identical across the deliverer's transport retry (same body), so cloud's notify dedupes the retry to AT-MOST-ONCE delivery (no duplicate SMS). Distinct OTPs get distinct keys and are never merged.

func OrgAncestors added in v1.31.24

func OrgAncestors(orgName string) ([]string, error)

OrgAncestors returns org's ancestors, nearest parent first, excluding org itself. The walk stops at the root, at MaxOrgDepth, or the moment it revisits an org (a cycle) — it never loops and never errors the caller into a fail-open.

func OrgIsolationEnabled

func OrgIsolationEnabled() bool

OrgIsolationEnabled returns true if per-org SQLite isolation is active.

func ParseJwtTokenWithoutValidation

func ParseJwtTokenWithoutValidation(token string) (*jwt.Token, error)

func ParseSamlResponse

func ParseSamlResponse(samlResponse string, provider *Provider, host string) (*idp.UserInfo, error)

func PromoteByEmailDomain added in v1.18.1

func PromoteByEmailDomain(user *User) (bool, error)

PromoteByEmailDomain applies the email-domain promotion rule to the given user. It is idempotent: if the user is already in the target org with the required IsAdmin flag, it is a no-op.

Returns true if any DB mutation occurred. Callers (HandleLoggedIn etc.) should log promotion events but MUST NOT fail the signin on promotion error — promotion is best-effort; an unexpected DB error here must not lock the user out of their session.

func ProvisionAuthzTables added in v1.22.1

func ProvisionAuthzTables(global *xorm.Engine) error

ProvisionAuthzTables creates the runtime-allocated authz adapter tables on the GLOBAL engine (authz is not per-org), exactly as the running IAM does on its first request. Idempotent: authzstore.New is a CREATE TABLE IF NOT EXISTS.

func PurgeExpiredWeb3Nonces added in v1.22.1

func PurgeExpiredWeb3Nonces() (int64, error)

PurgeExpiredWeb3Nonces is a janitor for a periodic task (optional).

func RefreshToken

func RefreshToken(application *Application, grantType string, refreshToken string, scope string, clientId string, clientSecret string, host string) (interface{}, error)

func RegisterDynamicClient

func RegisterDynamicClient(req *DynamicClientRegistrationRequest, organization string) (*DynamicClientRegistrationResponse, *DcrError, error)

RegisterDynamicClient creates a new application based on DCR request

func RemovePolicy

func RemovePolicy(id string, ptype string, policy []string) (bool, error)

func RenewCert

func RenewCert(cert *Cert) (bool, error)

func ResetLdapPassword

func ResetLdapPassword(user *User, oldPassword string, newPassword string, lang string) error

func RevokeServiceAccountKey added in v1.31.1

func RevokeServiceAccountKey(user *User, isAdmin bool) error

RevokeServiceAccountKey clears the service account's API key material so the key stops authenticating immediately, WITHOUT deleting the principal (so its identity/attribution history and hanzo.team membership survive a compromise rotation). Column-scoped for the same reason as MintServiceAccountKey.

func RevokeToken

func RevokeToken(tokenValue string, tokenType string, revokedBy string, clientId string, owner string, application string, expiresAt time.Time) error

RevokeToken revokes an OAuth2 token (access_token or refresh_token). This implements RFC 7009 - OAuth 2.0 Token Revocation.

func RevokeTokenByHash

func RevokeTokenByHash(tokenHash string, tokenType string, revokedBy string, clientId string, owner string, application string, expiresAt time.Time) error

RevokeTokenByHash revokes a token by its hash value.

func RevokeUserKeys added in v1.25.3

func RevokeUserKeys(user *User, isAdmin bool) (bool, error)

RevokeUserKeys clears a user's per-user hk- AccessKey/AccessSecret (the self-serve Cloud API key). Column-scoped for the same reason as AddUserKeys — it must never re-validate the (possibly email-named) `name`.

func RunSyncUsersJob

func RunSyncUsersJob()

func RunSyncer

func RunSyncer(syncer *Syncer) error

func SandboxOTPAllowed added in v1.18.4

func SandboxOTPAllowed() bool

SandboxOTPAllowed always returns true. See file comment above for the rationale — the authoritative SANDBOX_GLOBAL_OTP gate is the origin guard at boot, not a read-side mode check.

func SanitizePolicyJsonArrays added in v1.19.4

func SanitizePolicyJsonArrays(engine *xorm.Engine) (updated int, err error)

SanitizePolicyJsonArrays repairs PostgreSQL array-literal residue in the JSON-backed []string columns of the `permission` and `role` tables.

Background: these columns (users, roles, groups, domains, resources, actions) are declared `xorm:"mediumtext"` and stored as JSON. When a row was written under the Postgres driver and later migrated to SQLite verbatim, some values landed as Postgres array literals — e.g. the bytes `{admin/*}` instead of the JSON `["admin/*"]`. Go's encoding/json then chokes on the very first row scan with

invalid character 'a' looking for beginning of object key string

and because the Casbin enforcer / CheckApiPermission path wraps that scan error in panic(err), a SINGLE corrupt permission row takes down ALL authorization: every list endpoint (get-organizations, get-applications, get-permissions, get-roles, ...) returns the panic instead of data, and the login SPA's post-auth account/user fetches fail — stranding users on a dead-button "Binding providers" prompt.

This migration normalizes that residue back to valid JSON arrays so a lone bad row can never again poison the enforcer. It operates on RAW column text via the driver (Query/Exec), so it cannot itself trip the unmarshal panic it exists to prevent.

Idempotent: a value that is already valid JSON (`[...]`, `null`, or empty) is left untouched, so re-running on every boot is a cheap no-op once clean.

Schema change: NONE. Values are rewritten inside existing columns.

Returns (updated, error). `updated` counts the (row, column) cells rewritten.

func SendNotification

func SendNotification(provider *Provider, content string) error

func SendSsoLogoutNotifications

func SendSsoLogoutNotifications(user *User, sessionIds []string, tokens []*Token) error

SendSsoLogoutNotifications sends logout notifications to all notification providers configured in the user's signup application

func SendVerificationCodeToEmail

func SendVerificationCodeToEmail(organization *Organization, user *User, provider *Provider, remoteAddr string, dest string, _ string, _ string, _ string, application *Application) error

SendVerificationCodeToEmail generates an OTP and dispatches it via hanzoai/notify. The notify service owns the per-tenant template, the SendGrid/SMTP/Resend provider selection, retry, and metering — IAM only hands it the OTP and the recipient. The IAM-side verification record + rate limit run locally so DB consistency does not depend on notify's response shape.

`provider` is preserved in the signature for call-site source compatibility with the controller. Its Name/Category are recorded in the local verification record; everything else (Title, Content, ClientId/ClientSecret) is ignored — notify holds the canonical template + credentials.

Returns an error if notify delivery is disabled. There is no in-process fallback; refusing to send is the correct behaviour when the canonical send path is unavailable.

func SendVerificationCodeToPhone

func SendVerificationCodeToPhone(organization *Organization, user *User, provider *Provider, remoteAddr string, dest string, application *Application) error

SendVerificationCodeToPhone generates an OTP and dispatches it via hanzoai/notify. notify resolves the per-tenant SMS provider, renders the iam.otp_sent template, sends, and records a meter row. IAM owns the verification record + rate limiting.

Per-user pinned OTP (user.VerificationCode set, e.g. for sandbox users) skips the send entirely and just records the code — the pinned-OTP demo path is intentionally provider-independent.

`provider` is preserved in the signature for call-site source compatibility with the controller. Its Name/Category are recorded in the local verification record; everything else is ignored.

Returns an error if notify delivery is disabled and the user is not using a pinned OTP. There is no in-process fallback.

func SendWebhooks

func SendWebhooks(record *Record) error

func ServiceAccountName added in v1.31.1

func ServiceAccountName(org, agent string) string

ServiceAccountName returns the canonical <org>-<agent> handle for a service account. This is the User.Name — the stable, globally-unambiguous identity a Slack bot user / hanzo.team member maps to. Empty agent → error at the boundary (CreateServiceAccount), never a malformed name.

func SetNotifyDeliverer added in v1.18.7

func SetNotifyDeliverer(d notifyDeliverer) notifyDeliverer

SetNotifyDeliverer is a test seam. Production never calls it; the boot guard installs the ZAP deliverer once. Returns the previous deliverer.

func SetPreferredMultiFactorAuth

func SetPreferredMultiFactorAuth(user *User, mfaType string) error

func SetUserField

func SetUserField(user *User, field string, value string) (bool, error)

func SetUserOAuthProperties

func SetUserOAuthProperties(organization *Organization, user *User, providerType string, userInfo *idp.UserInfo, token *oauth2.Token, userMapping ...map[string]string) (bool, error)

func ShouldExportData

func ShouldExportData() bool

func SplitOriginList added in v1.14.24

func SplitOriginList(s string) []string

SplitOriginList parses a comma-separated origin config value into a slice of trimmed origins. Empty entries are dropped. Returns nil for empty input.

Multi-tenant IAM serves many host names from one backend, so `origin` (and `originFrontend`) in app.conf may be either a single origin or a CSV. The discovery endpoint must emit exactly one issuer per request — the one that matches the incoming host — not the entire CSV joined back together.

func StartMonitorSitesLoop

func StartMonitorSitesLoop()

func StoreCasTokenForPgt

func StoreCasTokenForPgt(token *CasAuthenticationSuccess, service, userId string) string

func StoreCasTokenForProxyTicket

func StoreCasTokenForProxyTicket(token *CasAuthenticationSuccess, targetService, userId string) string

func StringArrayToStruct

func StringArrayToStruct[T any](stringArray [][]string) ([]*T, error)

func SyncLdapGroups

func SyncLdapGroups(owner string, ldapGroups []LdapGroup, ldapId string) (newGroups int, updatedGroups int, err error)

SyncLdapGroups syncs LDAP groups/OUs to IAM groups with hierarchy

func SyncLdapUsers

func SyncLdapUsers(owner string, syncUsers []LdapUser, ldapId string) (existUsers []LdapUser, failedUsers []LdapUser, err error)

func TenantOrgForSignup added in v1.31.24

func TenantOrgForSignup(parentOrg string, username string) (string, error)

TenantOrgForSignup returns the org a new user signing up against parentOrg should be created in, creating that tenant if needed.

When parentOrg is a platform (SignupCreatesTenant), each signup gets its OWN org — its billing namespace, its balance, its payment methods — parented to the platform, so the platform's admins still administer it (AdministersOrg) and can roll usage up. Otherwise the user is created in parentOrg, exactly as before.

The tenant is named after the user (slugged, collision-suffixed by the caller's uniqueness check), because at signup time we do not yet know the company name; the onboarding step renames/creates the org the founder actually wants.

func TestSyncer

func TestSyncer(syncer Syncer) error

func TriggerWebhookForUser

func TriggerWebhookForUser(action string, user *User)

TriggerWebhookForUser triggers a webhook for user operations (add, update, delete) action: the action type, e.g., "new-user", "update-user", "delete-user" user: the user object

func UpdateAdapter

func UpdateAdapter(id string, adapter *Adapter) (bool, error)

func UpdateApplication

func UpdateApplication(id string, application *Application, isSuperAdmin bool, lang string) (bool, error)

func UpdateCert

func UpdateCert(id string, cert *Cert) (bool, error)

func UpdateEnforcer

func UpdateEnforcer(id string, enforcer *Enforcer) (bool, error)

func UpdateForm

func UpdateForm(id string, form *Form) (bool, error)

func UpdateGroup

func UpdateGroup(id string, group *Group) (bool, error)

func UpdateInvitation

func UpdateInvitation(id string, invitation *Invitation, lang string) (bool, error)

func UpdateKey

func UpdateKey(id string, key *Key) (bool, error)

func UpdateLdap

func UpdateLdap(ldap *Ldap) (bool, error)

func UpdateLdapSyncTime

func UpdateLdapSyncTime(ldapId string) error

func UpdateModel

func UpdateModel(id string, modelObj *Model) (bool, error)

func UpdateModelWithCheck

func UpdateModelWithCheck(id string, modelObj *Model) error

func UpdateOrganization

func UpdateOrganization(id string, organization *Organization, isSuperAdmin bool) (bool, error)

func UpdateOrganizationBalance

func UpdateOrganizationBalance(owner string, name string, balance float64, currency string, isOrgBalance bool, lang string) error

func UpdatePermission

func UpdatePermission(id string, permission *Permission) (bool, error)

func UpdatePolicy

func UpdatePolicy(id string, ptype string, oldPolicy []string, newPolicy []string) (bool, error)

func UpdateProject

func UpdateProject(id string, project *Project) (bool, error)

func UpdateProvider

func UpdateProvider(id string, provider *Provider) (bool, error)

func UpdateRadiusAccounting

func UpdateRadiusAccounting(id string, ra *RadiusAccounting) error

func UpdateResource

func UpdateResource(id string, resource *Resource) (bool, error)

func UpdateRole

func UpdateRole(id string, role *Role) (bool, error)

func UpdateRule

func UpdateRule(id string, rule *Rule) (bool, error)

func UpdateServer

func UpdateServer(id string, server *Server) (bool, error)

func UpdateSession

func UpdateSession(id string, session *Session) (bool, error)

func UpdateSite

func UpdateSite(id string, site *Site) (bool, error)

func UpdateSiteNoRefresh

func UpdateSiteNoRefresh(id string, site *Site) (bool, error)

func UpdateSyncer

func UpdateSyncer(id string, syncer *Syncer, isSuperAdmin bool, lang string) (bool, error)

func UpdateTicket

func UpdateTicket(id string, ticket *Ticket) (bool, error)

func UpdateToken

func UpdateToken(id string, token *Token, isSuperAdmin bool) (bool, error)

func UpdateUser

func UpdateUser(id string, user *User, columns []string, isAdmin bool) (bool, error)

func UpdateUserBalance

func UpdateUserBalance(owner string, name string, balance float64, currency string, lang string) error

func UpdateUserForAllFields

func UpdateUserForAllFields(id string, user *User) (bool, error)

func UpdateUserToOriginalDatabase

func UpdateUserToOriginalDatabase(user *User) error

func UpdateWebhook

func UpdateWebhook(id string, webhook *Webhook, isSuperAdmin bool, lang string) (bool, error)

func UploadFileSafe

func UploadFileSafe(provider *Provider, fullFilePath string, fileBuffer *bytes.Buffer, lang string) (string, string, error)

func UploadGroups

func UploadGroups(owner string, path string) (bool, error)

func UploadPermissions

func UploadPermissions(owner string, path string) (bool, error)

func UploadRoles

func UploadRoles(owner string, path string) (bool, error)

func UploadUsers

func UploadUsers(owner string, path string, userObj *User, lang string) (bool, error)

func ValidateKerberosToken

func ValidateKerberosToken(organization *Organization, spnegoTokenBase64 string) (string, error)

ValidateKerberosToken validates a base64-encoded SPNEGO token from the Authorization header and returns the authenticated Kerberos username.

func VerifyCaptcha

func VerifyCaptcha(id string, digits string) bool

func VerifyInvitation

func VerifyInvitation(id string) (attachInfo map[string]interface{}, err error)

func VerifySsoLogoutSignature

func VerifySsoLogoutSignature(clientSecret string, notification *SsoLogoutNotification) bool

VerifySsoLogoutSignature verifies the signature of an SSO logout notification This should be called by applications receiving logout notifications

func VerifyUserAccessSecret added in v1.31.1

func VerifyUserAccessSecret(user *User, presentedSecret string) bool

VerifyUserAccessSecret is the SINGLE choke point for validating a presented API secret against a stored user credential, for both service accounts and legacy hk- users. It decomplects "how the secret is stored" from every caller:

  • Service account (AccessSecretHash set): argon2id constant-time verify. The stored value is a hash; the plaintext is unrecoverable.
  • Legacy hk- user (AccessSecret set, no hash): constant-time compare against the stored plaintext secret. Preserves the pre-existing api_key grant behavior for users minted before hashing existed.

Returns false for any user with no secret material — a service account whose key was revoked (both columns empty) can never authenticate (fail-closed).

Types

type AccountItem

type AccountItem struct {
	Name       string `json:"name"`
	Visible    bool   `json:"visible"`
	ViewRule   string `json:"viewRule"`
	ModifyRule string `json:"modifyRule"`
	Regex      string `json:"regex"`
	Tab        string `json:"tab"`
}

func GetAccountItemByName

func GetAccountItemByName(name string, organization *Organization) *AccountItem

type ActiveDirectorySyncerProvider

type ActiveDirectorySyncerProvider struct {
	Syncer *Syncer
}

ActiveDirectorySyncerProvider implements SyncerProvider for Active Directory LDAP-based syncers

func (*ActiveDirectorySyncerProvider) AddUser

AddUser adds a new user to Active Directory (not supported for read-only LDAP)

func (*ActiveDirectorySyncerProvider) Close

Close closes any open connections (no-op for Active Directory LDAP-based syncer)

func (*ActiveDirectorySyncerProvider) GetOriginalGroups

func (p *ActiveDirectorySyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error)

GetOriginalGroups retrieves all groups from Active Directory (not implemented yet)

func (*ActiveDirectorySyncerProvider) GetOriginalUserGroups

func (p *ActiveDirectorySyncerProvider) GetOriginalUserGroups(userId string) ([]string, error)

GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)

func (*ActiveDirectorySyncerProvider) GetOriginalUsers

func (p *ActiveDirectorySyncerProvider) GetOriginalUsers() ([]*OriginalUser, error)

GetOriginalUsers retrieves all users from Active Directory via LDAP

func (*ActiveDirectorySyncerProvider) InitAdapter

func (p *ActiveDirectorySyncerProvider) InitAdapter() error

InitAdapter initializes the Active Directory syncer (no database adapter needed)

func (*ActiveDirectorySyncerProvider) TestConnection

func (p *ActiveDirectorySyncerProvider) TestConnection() error

TestConnection tests the Active Directory LDAP connection

func (*ActiveDirectorySyncerProvider) UpdateUser

func (p *ActiveDirectorySyncerProvider) UpdateUser(user *OriginalUser) (bool, error)

UpdateUser updates an existing user in Active Directory (not supported for read-only LDAP)

type Adapter

type Adapter struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	Table        string `xorm:"varchar(100)" json:"table"`
	UseSameDb    bool   `json:"useSameDb"`
	Type         string `xorm:"varchar(100)" json:"type"`
	DatabaseType string `xorm:"varchar(100)" json:"databaseType"`
	Host         string `xorm:"varchar(100)" json:"host"`
	Port         int    `json:"port"`
	User         string `xorm:"varchar(100)" json:"user"`
	Password     string `xorm:"varchar(150)" json:"password"`
	Database     string `xorm:"varchar(100)" json:"database"`

	*authzstore.Adapter `xorm:"-" json:"-"`
	// contains filtered or unexported fields
}

func GetAdapter

func GetAdapter(id string) (*Adapter, error)

func GetAdapters

func GetAdapters(owner string) ([]*Adapter, error)

func GetPaginationAdapters

func GetPaginationAdapters(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Adapter, error)

func (*Adapter) GetId

func (adapter *Adapter) GetId() string

func (*Adapter) InitAdapter

func (adapter *Adapter) InitAdapter() error

type Address

type Address struct {
	Tag     string `xorm:"varchar(100)" json:"tag"`
	Line1   string `xorm:"varchar(100)" json:"line1"`
	Line2   string `xorm:"varchar(100)" json:"line2"`
	City    string `xorm:"varchar(100)" json:"city"`
	State   string `xorm:"varchar(100)" json:"state"`
	ZipCode string `xorm:"varchar(100)" json:"zipCode"`
	Region  string `xorm:"varchar(100)" json:"region"`
}

type Affiliation

type Affiliation struct {
	Id   int    `xorm:"int notnull pk autoincr" json:"id"`
	Name string `xorm:"varchar(128)" json:"name"`
}

type AppAdminCapability added in v1.25.4

type AppAdminCapability struct {
	// Name is a short, stable identifier (used in logs/audit/errors).
	Name string
	// EnvVar is the environment variable holding the comma-separated
	// allowlist of application names permitted to exercise this capability
	// via an "app/<name>" credential. Empty/unset = deny all (fail-secure).
	EnvVar string
}

AppAdminCapability names a sensitive, app-gated capability and the env var holding its fail-secure allowlist of application names.

type Application

type Application struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	DisplayName                  string          `xorm:"varchar(100)" json:"displayName"`
	Category                     string          `xorm:"varchar(20)" json:"category"`
	Type                         string          `xorm:"varchar(20)" json:"type"`
	Scopes                       []*ScopeItem    `xorm:"mediumtext" json:"scopes"`
	Title                        string          `xorm:"varchar(100)" json:"title"`
	Favicon                      string          `xorm:"varchar(200)" json:"favicon"`
	Order                        int             `json:"order"`
	HomepageUrl                  string          `xorm:"varchar(100)" json:"homepageUrl"`
	Description                  string          `xorm:"varchar(100)" json:"description"`
	Organization                 string          `xorm:"varchar(100)" json:"organization"`
	Cert                         string          `xorm:"varchar(100)" json:"cert"`
	DefaultGroup                 string          `xorm:"varchar(100)" json:"defaultGroup"`
	HeaderHtml                   string          `xorm:"mediumtext" json:"headerHtml"`
	EnablePassword               bool            `xorm:"bool" json:"enablePassword"`
	EnableSignUp                 bool            `xorm:"bool" json:"enableSignUp"`
	DisableSignin                bool            `xorm:"bool" json:"disableSignin"`
	EnableSigninSession          bool            `xorm:"bool" json:"enableSigninSession"`
	EnableAutoSignin             bool            `xorm:"bool" json:"enableAutoSignin"`
	EnableCodeSignin             bool            `xorm:"bool" json:"enableCodeSignin"`
	EnableExclusiveSignin        bool            `xorm:"bool" json:"enableExclusiveSignin"`
	EnableSamlCompress           bool            `xorm:"bool" json:"enableSamlCompress"`
	EnableSamlC14n10             bool            `xorm:"bool" json:"enableSamlC14n10"`
	EnableSamlPostBinding        bool            `xorm:"bool" json:"enableSamlPostBinding"`
	DisableSamlAttributes        bool            `xorm:"bool" json:"disableSamlAttributes"`
	EnableSamlAssertionSignature bool            `xorm:"bool" json:"enableSamlAssertionSignature"`
	UseEmailAsSamlNameId         bool            `xorm:"bool" json:"useEmailAsSamlNameId"`
	EnableWebAuthn               bool            `xorm:"bool" json:"enableWebAuthn"`
	EnableGuestSignin            bool            `xorm:"bool" json:"enableGuestSignin"`
	EnableLinkWithEmail          bool            `xorm:"bool" json:"enableLinkWithEmail"`
	OrgChoiceMode                string          `json:"orgChoiceMode"`
	SamlReplyUrl                 string          `xorm:"varchar(500)" json:"samlReplyUrl"`
	Providers                    []*ProviderItem `xorm:"mediumtext" json:"providers"`
	SigninMethods                []*SigninMethod `xorm:"mediumtext" json:"signinMethods"`
	SignupItems                  []*SignupItem   `xorm:"mediumtext" json:"signupItems"`
	SigninItems                  []*SigninItem   `xorm:"mediumtext" json:"signinItems"`
	GrantTypes                   []string        `xorm:"mediumtext" json:"grantTypes"`
	OrganizationObj              *Organization   `xorm:"-" json:"organizationObj"`
	CertPublicKey                string          `xorm:"-" json:"certPublicKey"`
	Tags                         []string        `xorm:"mediumtext" json:"tags"`
	SamlAttributes               []*SamlItem     `xorm:"mediumtext" json:"samlAttributes"`
	SamlHashAlgorithm            string          `xorm:"varchar(20)" json:"samlHashAlgorithm"`
	IsShared                     bool            `xorm:"bool" json:"isShared"`
	IpRestriction                string          `json:"ipRestriction"`

	ClientId                string     `xorm:"varchar(100)" json:"clientId"`
	ClientSecret            string     `xorm:"varchar(100)" json:"clientSecret"`
	ClientCert              string     `xorm:"varchar(100)" json:"clientCert"`
	RedirectUris            []string   `xorm:"mediumtext" json:"redirectUris"`
	ForcedRedirectOrigin    string     `xorm:"varchar(100)" json:"forcedRedirectOrigin"`
	TokenFormat             string     `xorm:"varchar(100)" json:"tokenFormat"`
	TokenSigningMethod      string     `xorm:"varchar(100)" json:"tokenSigningMethod"`
	TokenFields             []string   `xorm:"mediumtext" json:"tokenFields"`
	TokenAttributes         []*JwtItem `xorm:"mediumtext" json:"tokenAttributes"`
	ExpireInHours           float64    `json:"expireInHours"`
	RefreshExpireInHours    float64    `json:"refreshExpireInHours"`
	CookieExpireInHours     int64      `json:"cookieExpireInHours"`
	SignupUrl               string     `xorm:"varchar(200)" json:"signupUrl"`
	SigninUrl               string     `xorm:"varchar(200)" json:"signinUrl"`
	ForgetUrl               string     `xorm:"varchar(200)" json:"forgetUrl"`
	AffiliationUrl          string     `xorm:"varchar(100)" json:"affiliationUrl"`
	IpWhitelist             string     `xorm:"varchar(200)" json:"ipWhitelist"`
	TermsOfUse              string     `xorm:"varchar(200)" json:"termsOfUse"`
	SignupHtml              string     `xorm:"mediumtext" json:"signupHtml"`
	SigninHtml              string     `xorm:"mediumtext" json:"signinHtml"`
	ThemeData               *ThemeData `xorm:"json" json:"themeData"`
	FooterHtml              string     `xorm:"mediumtext" json:"footerHtml"`
	FormCss                 string     `xorm:"text" json:"formCss"`
	FormCssMobile           string     `xorm:"text" json:"formCssMobile"`
	FormOffset              int        `json:"formOffset"`
	FormSideHtml            string     `xorm:"mediumtext" json:"formSideHtml"`
	FormBackgroundUrl       string     `xorm:"varchar(200)" json:"formBackgroundUrl"`
	FormBackgroundUrlMobile string     `xorm:"varchar(200)" json:"formBackgroundUrlMobile"`

	FailedSigninLimit      int `json:"failedSigninLimit"`
	FailedSigninFrozenTime int `json:"failedSigninFrozenTime"`
	CodeResendTimeout      int `json:"codeResendTimeout"`

	CustomScopes []*ScopeDescription `xorm:"mediumtext" json:"customScopes"`

	Environment string `xorm:"varchar(50)" json:"environment"` // dev, staging, production
	Project     string `xorm:"varchar(100)" json:"project"`    // project within org

	// Reverse proxy fields
	Domain       string   `xorm:"varchar(100)" json:"domain"`
	OtherDomains []string `xorm:"mediumtext" json:"otherDomains"`
	UpstreamHost string   `xorm:"varchar(100)" json:"upstreamHost"`
	SslMode      string   `xorm:"varchar(100)" json:"sslMode"`
	SslCert      string   `xorm:"varchar(100)" json:"sslCert"`

	CertObj *Cert `xorm:"-"`
}

func CheckOAuthLogin

func CheckOAuthLogin(clientId string, responseType string, redirectUri string, scope string, state string, lang string) (string, *Application, error)

func FindApplicationByName added in v1.14.6

func FindApplicationByName(name, orgHint string) (*Application, error)

FindApplicationByName resolves an application by its name across the configured admin namespace and a tenant org. Tries `<adminOrg>/<name>` first (system apps + the legacy seed location), then `<orgHint>/<name>` (apps owned by a tenant org), then a global by-name lookup so a caller that doesn't know the owner can still find the row. Returns (nil, nil) if no match.

Use this everywhere a controller currently does `GetApplication("admin/" + appName)` — that hardcoded `admin/` lookup breaks the moment an app is owned by a tenant org (which is the post-init steady state for everything except the admin-owned IAM app).

func GetAllowedApplications

func GetAllowedApplications(applications []*Application, userId string, lang string) ([]*Application, error)

func GetApplication

func GetApplication(id string) (*Application, error)

func GetApplicationByClientId

func GetApplicationByClientId(clientId string) (*Application, error)

func GetApplicationByOrganizationName

func GetApplicationByOrganizationName(organization string) (*Application, error)

func GetApplicationByUser

func GetApplicationByUser(user *User) (*Application, error)

func GetApplicationByUserId

func GetApplicationByUserId(userId string) (application *Application, err error)

func GetApplications

func GetApplications(owner string) ([]*Application, error)

func GetDefaultApplication

func GetDefaultApplication(id string) (*Application, error)

func GetMaskedApplication

func GetMaskedApplication(application *Application, userId string) *Application

func GetMaskedApplications

func GetMaskedApplications(applications []*Application, userId string) []*Application

func GetOrganizationApplications

func GetOrganizationApplications(owner string, organization string) ([]*Application, error)

func GetPaginationApplications

func GetPaginationApplications(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Application, error)

func GetPaginationOrganizationApplications

func GetPaginationOrganizationApplications(owner, organization string, offset, limit int, field, value, sortField, sortOrder string) ([]*Application, error)

func NewAdminApp added in v1.14.21

func NewAdminApp() *Application

NewAdminApp returns the IAM application placeholder owned by the admin org.

func ResolveDeviceApprovalApp added in v1.28.5

func ResolveDeviceApprovalApp(userCode string) (*Application, bool)

ResolveDeviceApprovalApp resolves the application a pending device user_code is bound to, for the anonymous GET /v1/iam/get-app-login device lookup. It is deliberately NON-DIFFERENTIAL: every failure mode — unknown code, expired code, or an unresolvable/absent application — collapses to (nil, false) so the caller can render ONE generic error and never leak exists-vs-not or the bound app/org to a caller grinding user_codes. Holding a valid, unexpired user_code IS the RFC 8628 proof the legit SPA presents to render the approval page, so the (app, true) path returns the app; the 40-bit crypto user_code and the per-IP throttle are the backstops against guessing one. The load and expiry checks are pure (no DB), so the non-differential contract is unit-testable.

func ValidateClientAssertion

func ValidateClientAssertion(clientAssertion string, host string) (bool, *Application, error)

func (*Application) GetEmailProvider

func (application *Application) GetEmailProvider(method string) (*Provider, error)

func (*Application) GetId

func (application *Application) GetId() string

func (*Application) GetProviderByCategory

func (application *Application) GetProviderByCategory(category string) (*Provider, error)

func (*Application) GetProviderByCategoryAndRule

func (application *Application) GetProviderByCategoryAndRule(category string, method string, countryCode string) (*Provider, error)

func (*Application) GetProviderItem

func (application *Application) GetProviderItem(providerName string) *ProviderItem

func (*Application) GetProviderItemByType

func (application *Application) GetProviderItemByType(providerType string) *ProviderItem

func (*Application) GetSignupItemRule

func (application *Application) GetSignupItemRule(itemName string) string

func (*Application) GetSmsProvider

func (application *Application) GetSmsProvider(method string, countryCode string) (*Provider, error)

func (*Application) GetStorageProvider

func (application *Application) GetStorageProvider() (*Provider, error)

func (*Application) HasPromptPage

func (application *Application) HasPromptPage() bool

func (*Application) IsCodeSigninViaEmailEnabled

func (application *Application) IsCodeSigninViaEmailEnabled() bool

func (*Application) IsCodeSigninViaSmsEnabled

func (application *Application) IsCodeSigninViaSmsEnabled() bool

func (*Application) IsFaceIdEnabled

func (application *Application) IsFaceIdEnabled() bool

func (*Application) IsLdapEnabled

func (application *Application) IsLdapEnabled() bool

func (*Application) IsPasswordEnabled

func (application *Application) IsPasswordEnabled() bool

func (*Application) IsPasswordWithLdapEnabled

func (application *Application) IsPasswordWithLdapEnabled() bool

func (*Application) IsRedirectUriValid

func (application *Application) IsRedirectUriValid(redirectUri string) bool

IsRedirectUriValid reports whether redirectUri is EXACTLY one of the application's registered redirect URIs (RFC 6749 §3.1.2.3). It is the sole authority for OAuth redirect_uri, SAML AuthnRequest Issuer, and CAS service validation.

Match is exact string equality and NOTHING else — deliberately de-braided from origin/CORS trust (util.IsValidOrigin):

  • A trusted origin means "this host may make a credentialed cross-origin request". It must NEVER imply "OAuth codes/tokens may be delivered to any URL on that host". The prior IsValidOrigin short-circuit made every app's registered redirectUris DECORATIVE: any authenticated user could host a page on a trusted-suffix subdomain (e.g. s3.hanzo.ai/hanzo-sites/*), point authorize's redirect_uri at it, and receive another user's authorization code — a one-click SSO account takeover across every brand.
  • The prior strings.Contains fallback accepted attacker URLs that merely embedded a registered URI (e.g. https://attacker.com/https://app/callback).
  • The prior regexp.Compile("^"+uri+"$") treated every "." in a registered host as "any char", so https://cloudXhanzo.ai/cb matched a https://cloud.hanzo.ai/cb entry, and an unescaped "*"→".*" allowed path/host-crossing open redirects.

Registered redirect URIs are the only allowlist. New callbacks are added by registering the exact URI (init_data.json / IAM admin API) — never by trusting a host suffix or a substring. Localhost dev callbacks are registered exactly too (host+port+path), never blanket-allowed.

func (*Application) IsSignupItemRequired

func (application *Application) IsSignupItemRequired(itemName string) bool

func (*Application) IsSignupItemVisible

func (application *Application) IsSignupItemVisible(itemName string) bool

type Attribute

type Attribute struct {
	// XMLName      xml.Name
	Xmlns        string   `xml:"xmlns,attr"`
	Name         string   `xml:"Name,attr"`
	NameFormat   string   `xml:"NameFormat,attr"`
	FriendlyName string   `xml:"FriendlyName,attr"`
	Values       []string `xml:"AttributeValue"`
}

type AwsIamSyncerProvider

type AwsIamSyncerProvider struct {
	Syncer *Syncer
	// contains filtered or unexported fields
}

AwsIamSyncerProvider implements SyncerProvider for AWS IAM API-based syncers

func (*AwsIamSyncerProvider) AddUser

func (p *AwsIamSyncerProvider) AddUser(user *OriginalUser) (bool, error)

AddUser adds a new user to AWS IAM (not supported for read-only API)

func (*AwsIamSyncerProvider) Close

func (p *AwsIamSyncerProvider) Close() error

Close closes any open connections

func (*AwsIamSyncerProvider) GetOriginalGroups

func (p *AwsIamSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error)

GetOriginalGroups retrieves all groups from AWS IAM

func (*AwsIamSyncerProvider) GetOriginalUserGroups

func (p *AwsIamSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error)

GetOriginalUserGroups retrieves the group IDs that a user belongs to

func (*AwsIamSyncerProvider) GetOriginalUsers

func (p *AwsIamSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error)

GetOriginalUsers retrieves all users from AWS IAM API

func (*AwsIamSyncerProvider) InitAdapter

func (p *AwsIamSyncerProvider) InitAdapter() error

InitAdapter initializes the AWS IAM syncer

func (*AwsIamSyncerProvider) TestConnection

func (p *AwsIamSyncerProvider) TestConnection() error

TestConnection tests the AWS IAM API connection

func (*AwsIamSyncerProvider) UpdateUser

func (p *AwsIamSyncerProvider) UpdateUser(user *OriginalUser) (bool, error)

UpdateUser updates an existing user in AWS IAM (not supported for read-only API)

type AzureAdAccessTokenResp

type AzureAdAccessTokenResp struct {
	TokenType   string `json:"token_type"`
	ExpiresIn   int    `json:"expires_in"`
	AccessToken string `json:"access_token"`
	Error       string `json:"error"`
	ErrorDesc   string `json:"error_description"`
}

type AzureAdSyncerProvider

type AzureAdSyncerProvider struct {
	Syncer *Syncer
}

AzureAdSyncerProvider implements SyncerProvider for Azure AD API-based syncers

func (*AzureAdSyncerProvider) AddUser

func (p *AzureAdSyncerProvider) AddUser(user *OriginalUser) (bool, error)

AddUser adds a new user to Azure AD (not supported for read-only API)

func (*AzureAdSyncerProvider) Close

func (p *AzureAdSyncerProvider) Close() error

Close closes any open connections (no-op for Azure AD API-based syncer)

func (*AzureAdSyncerProvider) GetOriginalGroups

func (p *AzureAdSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error)

GetOriginalGroups retrieves all groups from Azure AD (not implemented yet)

func (*AzureAdSyncerProvider) GetOriginalUserGroups

func (p *AzureAdSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error)

GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)

func (*AzureAdSyncerProvider) GetOriginalUsers

func (p *AzureAdSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error)

GetOriginalUsers retrieves all users from Azure AD API

func (*AzureAdSyncerProvider) InitAdapter

func (p *AzureAdSyncerProvider) InitAdapter() error

InitAdapter initializes the Azure AD syncer (no database adapter needed)

func (*AzureAdSyncerProvider) TestConnection

func (p *AzureAdSyncerProvider) TestConnection() error

TestConnection tests the Azure AD API connection

func (*AzureAdSyncerProvider) UpdateUser

func (p *AzureAdSyncerProvider) UpdateUser(user *OriginalUser) (bool, error)

UpdateUser updates an existing user in Azure AD (not supported for read-only API)

type AzureAdUser

type AzureAdUser struct {
	Id                string `json:"id"`
	UserPrincipalName string `json:"userPrincipalName"`
	DisplayName       string `json:"displayName"`
	GivenName         string `json:"givenName"`
	Surname           string `json:"surname"`
	Mail              string `json:"mail"`
	MobilePhone       string `json:"mobilePhone"`
	JobTitle          string `json:"jobTitle"`
	OfficeLocation    string `json:"officeLocation"`
	PreferredLanguage string `json:"preferredLanguage"`
	AccountEnabled    bool   `json:"accountEnabled"`
}

type AzureAdUserListResp

type AzureAdUserListResp struct {
	OdataContext  string         `json:"@odata.context"`
	OdataNextLink string         `json:"@odata.nextLink"`
	Value         []*AzureAdUser `json:"value"`
}

type CallerContext added in v1.31.26

type CallerContext struct {
	UserId        string // "org/name"
	Org           string // caller's org (User.Owner)
	IsGlobalAdmin bool   // platform superuser (User.IsGlobalAdmin)
	IsOrgAdmin    bool   // admin of Org (User.IsAdmin) — org-wide authority in own org
}

CallerContext is the authenticated caller's identity, derived by the controller from the session/JWT — NEVER from the request body.

type CasAnyAttribute

type CasAnyAttribute struct {
	XMLName xml.Name
	Value   string `xml:",chardata"`
}

type CasAttributes

type CasAttributes struct {
	XMLName                                xml.Name  `xml:"cas:attributes" json:"-"`
	AuthenticationDate                     time.Time `xml:"cas:authenticationDate"`
	LongTermAuthenticationRequestTokenUsed bool      `xml:"cas:longTermAuthenticationRequestTokenUsed"`
	IsFromNewLogin                         bool      `xml:"cas:isFromNewLogin"`
	MemberOf                               []string  `xml:"cas:memberOf"`
	FirstName                              string    `xml:"cas:firstName,omitempty"`
	LastName                               string    `xml:"cas:lastName,omitempty"`
	Title                                  string    `xml:"cas:title,omitempty"`
	Email                                  string    `xml:"cas:email,omitempty"`
	Affiliation                            string    `xml:"cas:affiliation,omitempty"`
	Avatar                                 string    `xml:"cas:avatar,omitempty"`
	Phone                                  string    `xml:"cas:phone,omitempty"`
	DisplayName                            string    `xml:"cas:displayName,omitempty"`
	UserAttributes                         *CasUserAttributes
	ExtraAttributes                        []*CasAnyAttribute `xml:",any"`
}

func (*CasAttributes) DeepCopy

func (c *CasAttributes) DeepCopy() CasAttributes

type CasAuthenticationFailure

type CasAuthenticationFailure struct {
	XMLName xml.Name `xml:"cas:authenticationFailure" json:"-"`
	Code    string   `xml:"code,attr"`
	Message string   `xml:",innerxml"`
}

type CasAuthenticationSuccess

type CasAuthenticationSuccess struct {
	XMLName             xml.Name           `xml:"cas:authenticationSuccess" json:"-"`
	User                string             `xml:"cas:user"`
	ProxyGrantingTicket string             `xml:"cas:proxyGrantingTicket,omitempty"`
	Proxies             *CasProxies        `xml:"cas:proxies"`
	Attributes          *CasAttributes     `xml:"cas:attributes"`
	ExtraAttributes     []*CasAnyAttribute `xml:",any"`
}

func GetCasTokenByPgt

func GetCasTokenByPgt(pgt string) (bool, *CasAuthenticationSuccess, string, string)

GetCasTokenByPgt * @ret1: whether a token is found @ret2: token, nil if not found @ret3: the service URL who requested to issue this token @ret4: userIf of user who requested to issue this token

func GetCasTokenByTicket

func GetCasTokenByTicket(ticket string) (bool, *CasAuthenticationSuccess, string, string)

GetCasTokenByTicket * @ret1: whether a token is found @ret2: token, nil if not found @ret3: the service URL who requested to issue this token @ret4: userIf of user who requested to issue this token

func (*CasAuthenticationSuccess) DeepCopy

type CasAuthenticationSuccessWrapper

type CasAuthenticationSuccessWrapper struct {
	AuthenticationSuccess *CasAuthenticationSuccess // the token we issued
	Service               string                    // to which service this token is issued
	UserId                string
}

type CasNamedAttribute

type CasNamedAttribute struct {
	XMLName xml.Name `xml:"cas:attribute" json:"-"`
	Name    string   `xml:"name,attr,omitempty"`
	Value   string   `xml:",innerxml"`
}

type CasProxies

type CasProxies struct {
	XMLName xml.Name `xml:"cas:proxies" json:"-"`
	Proxies []string `xml:"cas:proxy"`
}

func (*CasProxies) DeepCopy

func (c *CasProxies) DeepCopy() CasProxies

type CasProxyFailure

type CasProxyFailure struct {
	XMLName xml.Name `xml:"cas:proxyFailure" json:"-"`
	Code    string   `xml:"code,attr"`
	Message string   `xml:",innerxml"`
}

type CasProxySuccess

type CasProxySuccess struct {
	XMLName     xml.Name `xml:"cas:proxySuccess" json:"-"`
	ProxyTicket string   `xml:"cas:proxyTicket"`
}

type CasServiceResponse

type CasServiceResponse struct {
	XMLName      xml.Name `xml:"cas:serviceResponse" json:"-"`
	Xmlns        string   `xml:"xmlns:cas,attr"`
	Failure      *CasAuthenticationFailure
	Success      *CasAuthenticationSuccess
	ProxySuccess *CasProxySuccess
	ProxyFailure *CasProxyFailure
}

type CasUserAttributes

type CasUserAttributes struct {
	XMLName       xml.Name             `xml:"cas:userAttributes" json:"-"`
	Attributes    []*CasNamedAttribute `xml:"cas:attribute"`
	AnyAttributes []*CasAnyAttribute   `xml:",any"`
}

func (*CasUserAttributes) DeepCopy

func (c *CasUserAttributes) DeepCopy() CasUserAttributes

type Cert

type Cert struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	DisplayName     string `xorm:"varchar(100)" json:"displayName"`
	Scope           string `xorm:"varchar(100)" json:"scope"`
	Type            string `xorm:"varchar(100)" json:"type"`
	CryptoAlgorithm string `xorm:"varchar(100)" json:"cryptoAlgorithm"`
	BitSize         int    `json:"bitSize"`
	ExpireInYears   int    `json:"expireInYears"`

	ExpireTime       string `xorm:"varchar(100)" json:"expireTime"`
	DomainExpireTime string `xorm:"varchar(100)" json:"domainExpireTime"`
	Provider         string `xorm:"varchar(100)" json:"provider"`
	Account          string `xorm:"varchar(100)" json:"account"`
	AccessKey        string `xorm:"varchar(100)" json:"accessKey"`
	AccessSecret     string `xorm:"varchar(100)" json:"accessSecret"`

	Certificate string `xorm:"mediumtext" json:"certificate"`
	PrivateKey  string `xorm:"mediumtext" json:"privateKey"`
}

func GetCert

func GetCert(id string) (*Cert, error)

func GetCertByDomain

func GetCertByDomain(domain string) (*Cert, error)

func GetCerts

func GetCerts(owner string) ([]*Cert, error)

func GetDefaultCert

func GetDefaultCert() (*Cert, error)

func GetGlobalCerts

func GetGlobalCerts() ([]*Cert, error)

func GetMaskedCert

func GetMaskedCert(cert *Cert) *Cert

func GetMaskedCerts

func GetMaskedCerts(certs []*Cert, err error) ([]*Cert, error)

func GetPaginationCerts

func GetPaginationCerts(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Cert, error)

func GetPaginationGlobalCerts

func GetPaginationGlobalCerts(offset, limit int, field, value, sortField, sortOrder string) ([]*Cert, error)

func (*Cert) GetId

func (p *Cert) GetId() string

type Claims

type Claims struct {
	*User
	TokenType string `json:"tokenType,omitempty"`
	Nonce     string `json:"nonce,omitempty"`
	Tag       string `json:"tag"`
	Scope     string `json:"scope,omitempty"`
	// the `azp` (Authorized Party) claim. Optional. See https://openid.net/specs/openid-connect-core-1_0.html#IDToken
	Azp      string `json:"azp,omitempty"`
	Provider string `json:"provider,omitempty"`
	// Project is the caller's org DEFAULT project (the Project row with
	// IsDefault=true for the user's org). The gateway mints X-Project-Id from it
	// (empty ⟹ default scope ⟹ header omitted). Resolved once at mint time and
	// threaded into every token format alongside `organization`.
	Project string `json:"project,omitempty"`
	// BillingAccount is the signed `billing_account` claim — IAM's authoritative
	// statement of who pays (see billing_account.go). Resolved once at mint time
	// and threaded into every token format, exactly like Project. It is ALSO the
	// parse target: this Claims struct is what ParseJwtToken decodes into, so a
	// downstream reader (ai/object.Payer) reads the claim straight off it.
	BillingAccount string `json:"billing_account,omitempty"`
	// Orgs is the org-membership SET: every org the subject may act in (home +
	// teams), each with a coarse role. The gateway authorizes an org-switch
	// against it (X-Org-Id ∈ orgs). Resolved once at mint, threaded into every
	// format like `project`. Empty ⟹ home-only (the default scope).
	Orgs []OrgRef `json:"orgs,omitempty"`

	SigninMethod string `json:"signinMethod,omitempty"`
	jwt.RegisteredClaims
}

func ParseJwtToken

func ParseJwtToken(token string, cert *Cert) (*Claims, error)

func ParseJwtTokenByApplication

func ParseJwtTokenByApplication(token string, application *Application) (*Claims, error)

func ValidateJwtAssertion

func ValidateJwtAssertion(clientAssertion string, application *Application, host string) (bool, *Claims, error)

type ClaimsShort

type ClaimsShort struct {
	*UserShort
	// Organization mirrors the embedded user's `owner` under the standard OIDC
	// claim name. `owner` is the canonical org claim (gateway → X-Org-Id); this
	// alias lets consumers read either, identically across every token format.
	Organization string `json:"organization,omitempty"`
	// Project is the org's default project; see Claims.Project.
	Project string `json:"project,omitempty"`
	// BillingAccount is the signed `billing_account` claim; see Claims.BillingAccount.
	BillingAccount string `json:"billing_account,omitempty"`
	// Orgs is the org-membership set; see Claims.Orgs.
	Orgs      []OrgRef `json:"orgs,omitempty"`
	TokenType string   `json:"tokenType,omitempty"`
	Nonce     string   `json:"nonce,omitempty"`
	Scope     string   `json:"scope,omitempty"`
	Azp       string   `json:"azp,omitempty"`
	Provider  string   `json:"provider,omitempty"`

	SigninMethod string `json:"signinMethod,omitempty"`
	jwt.RegisteredClaims
}

type ClaimsStandard

type ClaimsStandard struct {
	*UserStandard
	// Organization mirrors the embedded user's `owner` (see ClaimsShort).
	Organization string `json:"organization,omitempty"`
	// Project is the org's default project; see Claims.Project.
	Project string `json:"project,omitempty"`
	// BillingAccount is the signed `billing_account` claim; see Claims.BillingAccount.
	BillingAccount string `json:"billing_account,omitempty"`
	// Orgs is the org-membership set; see Claims.Orgs.
	Orgs                []OrgRef    `json:"orgs,omitempty"`
	EmailVerified       bool        `json:"email_verified,omitempty"`
	PhoneNumber         string      `json:"phone_number,omitempty"`
	PhoneNumberVerified bool        `json:"phone_number_verified,omitempty"`
	Gender              string      `json:"gender,omitempty"`
	TokenType           string      `json:"tokenType,omitempty"`
	Nonce               string      `json:"nonce,omitempty"`
	Scope               string      `json:"scope,omitempty"`
	Address             OIDCAddress `json:"address,omitempty"`
	Azp                 string      `json:"azp,omitempty"`
	Provider            string      `json:"provider,omitempty"`

	jwt.RegisteredClaims
}

func ParseStandardJwtToken

func ParseStandardJwtToken(token string, cert *Cert) (*ClaimsStandard, error)

func ParseStandardJwtTokenByApplication

func ParseStandardJwtTokenByApplication(token string, application *Application) (*ClaimsStandard, error)

type ClaimsWithoutThirdIdp

type ClaimsWithoutThirdIdp struct {
	*UserWithoutThirdIdp
	// Organization mirrors the embedded user's `owner` (see ClaimsShort).
	Organization string `json:"organization,omitempty"`
	// Project is the org's default project; see Claims.Project.
	Project string `json:"project,omitempty"`
	// BillingAccount is the signed `billing_account` claim; see Claims.BillingAccount.
	BillingAccount string `json:"billing_account,omitempty"`
	// Orgs is the org-membership set; see Claims.Orgs.
	Orgs      []OrgRef `json:"orgs,omitempty"`
	TokenType string   `json:"tokenType,omitempty"`
	Nonce     string   `json:"nonce,omitempty"`
	Tag       string   `json:"tag"`
	Scope     string   `json:"scope,omitempty"`
	Azp       string   `json:"azp,omitempty"`
	Provider  string   `json:"provider,omitempty"`

	SigninMethod string `json:"signinMethod,omitempty"`
	jwt.RegisteredClaims
}

type Code

type Code struct {
	Message string `xorm:"varchar(100)" json:"message"`
	Code    string `xorm:"varchar(100)" json:"code"`
}

func GetOAuthCode

func GetOAuthCode(userId string, clientId string, provider string, signinMethod string, responseType string, redirectUri string, scope string, state string, nonce string, challenge string, challengeMethod string, resource string, host string, lang string) (*Code, error)

type ConsentRecord

type ConsentRecord struct {
	// owner/name
	Application   string   `json:"application"`
	GrantedScopes []string `json:"grantedScopes"`
}

ConsentRecord represents the data for OAuth consent API requests/responses

type Credential

type Credential struct {
	Value string `json:"value"`
	Salt  string `json:"salt"`
}

type DashboardDateItem

type DashboardDateItem struct {
	CreatedTime string `json:"createTime"`
}

type DashboardMapItem

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

type DatabaseSyncerProvider

type DatabaseSyncerProvider struct {
	Syncer *Syncer
}

DatabaseSyncerProvider implements SyncerProvider for database-based syncers

func (*DatabaseSyncerProvider) AddUser

func (p *DatabaseSyncerProvider) AddUser(user *OriginalUser) (bool, error)

AddUser adds a new user to the database

func (*DatabaseSyncerProvider) Close

func (p *DatabaseSyncerProvider) Close() error

Close closes the database connection and SSH tunnel

func (*DatabaseSyncerProvider) GetOriginalGroups

func (p *DatabaseSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error)

GetOriginalGroups retrieves all groups from Database (not implemented yet)

func (*DatabaseSyncerProvider) GetOriginalUserGroups

func (p *DatabaseSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error)

GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)

func (*DatabaseSyncerProvider) GetOriginalUsers

func (p *DatabaseSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error)

GetOriginalUsers retrieves all users from the database

func (*DatabaseSyncerProvider) InitAdapter

func (p *DatabaseSyncerProvider) InitAdapter() error

InitAdapter initializes the database adapter

func (*DatabaseSyncerProvider) TestConnection

func (p *DatabaseSyncerProvider) TestConnection() error

TestConnection tests the database connection

func (*DatabaseSyncerProvider) UpdateUser

func (p *DatabaseSyncerProvider) UpdateUser(user *OriginalUser) (bool, error)

UpdateUser updates an existing user in the database

type DcrError

type DcrError struct {
	Error            string `json:"error"`
	ErrorDescription string `json:"error_description,omitempty"`
}

DcrError represents an RFC 7591 error response

type DeviceAuthCache

type DeviceAuthCache struct {
	UserSignIn bool
	UserName   string
	// UserOwner is the approving user's org, captured at approval. The token
	// mint resolves the user in THIS org (not the app's) so a global admin —
	// who lives in conf.AdminOrg, not the app's tenant — resolves to their real
	// godmode identity. Empty on older entries: the mint falls back to the app
	// org, preserving pre-existing single-tenant behavior.
	UserOwner     string
	ApplicationId string
	Scope         string
	RequestAt     time.Time
}

type DeviceAuthResponse

type DeviceAuthResponse struct {
	DeviceCode              string `json:"device_code"`
	UserCode                string `json:"user_code"`
	VerificationUri         string `json:"verification_uri"`
	VerificationUriComplete string `json:"verification_uri_complete"`
	ExpiresIn               int    `json:"expires_in"`
	Interval                int    `json:"interval"`
}

func GetDeviceAuthResponse

func GetDeviceAuthResponse(deviceCode string, userCode string, host string) DeviceAuthResponse

type DingtalkAccessTokenResp

type DingtalkAccessTokenResp struct {
	Errcode     int    `json:"errcode"`
	Errmsg      string `json:"errmsg"`
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}

type DingtalkDepartment

type DingtalkDepartment struct {
	DeptId          int64  `json:"dept_id"`
	Name            string `json:"name"`
	ParentId        int64  `json:"parent_id"`
	CreateDeptGroup bool   `json:"create_dept_group"`
	AutoAddUser     bool   `json:"auto_add_user"`
}

type DingtalkDeptDetailResp

type DingtalkDeptDetailResp struct {
	Errcode   int                 `json:"errcode"`
	Errmsg    string              `json:"errmsg"`
	Result    *DingtalkDepartment `json:"result"`
	RequestId string              `json:"request_id"`
}

type DingtalkDeptListResp

type DingtalkDeptListResp struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
	Result  []struct {
		DeptId int64 `json:"dept_id"`
	} `json:"result"`
	RequestId string `json:"request_id"`
}

type DingtalkResult

type DingtalkResult struct {
	List       []*DingtalkUser `json:"list"`
	HasMore    bool            `json:"has_more"`
	NextCursor int64           `json:"next_cursor"`
}

type DingtalkSyncerProvider

type DingtalkSyncerProvider struct {
	Syncer *Syncer
}

DingtalkSyncerProvider implements SyncerProvider for DingTalk API-based syncers

func (*DingtalkSyncerProvider) AddUser

func (p *DingtalkSyncerProvider) AddUser(user *OriginalUser) (bool, error)

AddUser adds a new user to DingTalk (not supported for read-only API)

func (*DingtalkSyncerProvider) Close

func (p *DingtalkSyncerProvider) Close() error

Close closes any open connections (no-op for DingTalk API-based syncer)

func (*DingtalkSyncerProvider) GetOriginalGroups

func (p *DingtalkSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error)

GetOriginalGroups retrieves all groups (departments) from DingTalk

func (*DingtalkSyncerProvider) GetOriginalUserGroups

func (p *DingtalkSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error)

GetOriginalUserGroups retrieves the group (department) IDs that a user belongs to

func (*DingtalkSyncerProvider) GetOriginalUsers

func (p *DingtalkSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error)

GetOriginalUsers retrieves all users from DingTalk API

func (*DingtalkSyncerProvider) InitAdapter

func (p *DingtalkSyncerProvider) InitAdapter() error

InitAdapter initializes the DingTalk syncer (no database adapter needed)

func (*DingtalkSyncerProvider) TestConnection

func (p *DingtalkSyncerProvider) TestConnection() error

TestConnection tests the DingTalk API connection

func (*DingtalkSyncerProvider) UpdateUser

func (p *DingtalkSyncerProvider) UpdateUser(user *OriginalUser) (bool, error)

UpdateUser updates an existing user in DingTalk (not supported for read-only API)

type DingtalkUser

type DingtalkUser struct {
	UserId     string `json:"userid"`
	UnionId    string `json:"unionid"`
	Name       string `json:"name"`
	Department []int  `json:"dept_id_list"`
	Position   string `json:"title"`
	Mobile     string `json:"mobile"`
	Email      string `json:"email"`
	Avatar     string `json:"avatar"`
	JobNumber  string `json:"job_number"`
	Active     bool   `json:"active"`
}

type DingtalkUserListResp

type DingtalkUserListResp struct {
	Errcode   int             `json:"errcode"`
	Errmsg    string          `json:"errmsg"`
	Result    *DingtalkResult `json:"result"`
	RequestId string          `json:"request_id"`
}

type DomainPromotion added in v1.18.1

type DomainPromotion struct {
	// Org is the user's resulting owner field after promotion.
	Org string
	// SuperAdmin reports whether the rule confers global-admin status
	// (i.e. Org == conf.AdminOrg).
	SuperAdmin bool
}

DomainPromotion describes the effect of an email-domain auto-promotion rule. It carries the target org (where the user is moved) and whether the user should become a global admin (i.e. owner == conf.AdminOrg) on promotion.

In this IAM the global-admin status is computed from user.Owner == conf.AdminOrg. "global admin + home-org membership" is therefore expressed as Owner=AdminOrg for domains that should manage everything (hanzo, lux, zoo) and Owner=<homeOrg> + IsAdmin=true for org-scoped admins (pars).

func LookupDomainPromotion added in v1.18.1

func LookupDomainPromotion(email string) (DomainPromotion, bool)

LookupDomainPromotion returns the promotion outcome for an email's domain (case-insensitive), or (zero, false) if the domain is not configured.

Pure (modulo brand.json read): no DB access. Safe for unit tests.

Rule source: conf.LoadBrand() reads /etc/brand/brand.json (or $IAM_BRAND_FILE). White-label deployments override the rule list there — IAM itself ships no hardcoded brand-specific list.

type DynamicClientRegistrationRequest

type DynamicClientRegistrationRequest struct {
	ClientName              string   `json:"client_name,omitempty"`
	RedirectUris            []string `json:"redirect_uris,omitempty"`
	GrantTypes              []string `json:"grant_types,omitempty"`
	ResponseTypes           []string `json:"response_types,omitempty"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method,omitempty"`
	ApplicationType         string   `json:"application_type,omitempty"`
	Contacts                []string `json:"contacts,omitempty"`
	LogoUri                 string   `json:"logo_uri,omitempty"`
	ClientUri               string   `json:"client_uri,omitempty"`
	PolicyUri               string   `json:"policy_uri,omitempty"`
	TosUri                  string   `json:"tos_uri,omitempty"`
	Scope                   string   `json:"scope,omitempty"`
}

DynamicClientRegistrationRequest represents an RFC 7591 client registration request

type DynamicClientRegistrationResponse

type DynamicClientRegistrationResponse struct {
	ClientId                string   `json:"client_id"`
	ClientSecret            string   `json:"client_secret,omitempty"`
	ClientIdIssuedAt        int64    `json:"client_id_issued_at,omitempty"`
	ClientSecretExpiresAt   int64    `json:"client_secret_expires_at,omitempty"`
	ClientName              string   `json:"client_name,omitempty"`
	RedirectUris            []string `json:"redirect_uris,omitempty"`
	GrantTypes              []string `json:"grant_types,omitempty"`
	ResponseTypes           []string `json:"response_types,omitempty"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method,omitempty"`
	ApplicationType         string   `json:"application_type,omitempty"`
	Contacts                []string `json:"contacts,omitempty"`
	LogoUri                 string   `json:"logo_uri,omitempty"`
	ClientUri               string   `json:"client_uri,omitempty"`
	PolicyUri               string   `json:"policy_uri,omitempty"`
	TosUri                  string   `json:"tos_uri,omitempty"`
	Scope                   string   `json:"scope,omitempty"`
	RegistrationClientUri   string   `json:"registration_client_uri,omitempty"`
	RegistrationAccessToken string   `json:"registration_access_token,omitempty"`
}

DynamicClientRegistrationResponse represents an RFC 7591 client registration response

type Enforcer

type Enforcer struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
	UpdatedTime string `xorm:"varchar(100) updated" json:"updatedTime"`
	DisplayName string `xorm:"varchar(100)" json:"displayName"`
	Description string `xorm:"varchar(100)" json:"description"`

	Model   string `xorm:"varchar(100)" json:"model"`
	Adapter string `xorm:"varchar(100)" json:"adapter"`

	ModelCfg map[string]string `xorm:"-" json:"modelCfg"`
	*authz.Enforcer
}

func GetEnforcer

func GetEnforcer(id string) (*Enforcer, error)

func GetEnforcers

func GetEnforcers(owner string) ([]*Enforcer, error)

func GetInitializedEnforcer

func GetInitializedEnforcer(enforcerId string) (*Enforcer, error)

func GetPaginationEnforcers

func GetPaginationEnforcers(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Enforcer, error)

func (*Enforcer) GetId

func (enforcer *Enforcer) GetId() string

func (*Enforcer) GetModelAndAdapter

func (enforcer *Enforcer) GetModelAndAdapter() string

func (*Enforcer) InitEnforcer

func (enforcer *Enforcer) InitEnforcer() error

func (*Enforcer) LoadModelCfg

func (enforcer *Enforcer) LoadModelCfg() error

type Expression

type Expression struct {
	Name     string `json:"name"`
	Operator string `json:"operator"`
	Value    string `json:"value"`
}

type FaceId

type FaceId struct {
	Name       string    `xorm:"varchar(100) notnull pk" json:"name"`
	FaceIdData []float64 `json:"faceIdData"`
	ImageUrl   string    `json:"ImageUrl"`
}

type Filter

type Filter struct {
	Ptype       string   `json:"ptype,omitempty"`
	FieldIndex  *int     `json:"fieldIndex,omitempty"`
	FieldValues []string `json:"fieldValues"`
}

Filter represents filter criteria with optional policy type

type Form

type Form struct {
	Owner       string      `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string      `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string      `xorm:"varchar(100)" json:"createdTime"`
	DisplayName string      `xorm:"varchar(100)" json:"displayName"`
	Type        string      `xorm:"varchar(100)" json:"type"`
	Tag         string      `xorm:"varchar(100)" json:"tag"`
	FormItems   []*FormItem `xorm:"mediumtext" json:"formItems"`
}

func GetForm

func GetForm(id string) (*Form, error)

func GetForms

func GetForms(owner string) ([]*Form, error)

func GetGlobalForms

func GetGlobalForms() ([]*Form, error)

func GetMaskedForm

func GetMaskedForm(form *Form, isMaskEnabled bool) *Form

func GetMaskedForms

func GetMaskedForms(forms []*Form, isMaskEnabled bool) []*Form

func GetPaginationForms

func GetPaginationForms(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Form, error)

func (*Form) GetId

func (form *Form) GetId() string

type FormItem

type FormItem struct {
	Name    string `json:"name"`
	Label   string `json:"label"`
	Visible bool   `json:"visible"`
	Width   string `json:"width"`
}

type GaugeVecInfo

type GaugeVecInfo struct {
	Method     string  `json:"method"`
	Name       string  `json:"name"`
	Throughput float64 `json:"throughput"`
}

type Group

type Group struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk unique index" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
	UpdatedTime string `xorm:"varchar(100)" json:"updatedTime"`

	DisplayName  string   `xorm:"varchar(100)" json:"displayName"`
	Manager      string   `xorm:"varchar(100)" json:"manager"`
	ContactEmail string   `xorm:"varchar(100)" json:"contactEmail"`
	Type         string   `xorm:"varchar(100)" json:"type"`
	ParentId     string   `xorm:"varchar(100)" json:"parentId"`
	ParentName   string   `xorm:"-" json:"parentName"`
	IsTopGroup   bool     `xorm:"bool" json:"isTopGroup"`
	Users        []string `xorm:"-" json:"users"`

	Title        string   `json:"title,omitempty"`
	Key          string   `json:"key,omitempty"`
	HaveChildren bool     `xorm:"-" json:"haveChildren"`
	Children     []*Group `json:"children,omitempty"`

	IsEnabled bool `json:"isEnabled"`
}

func ConvertToTreeData

func ConvertToTreeData(groups []*Group, parentId string) []*Group

func GetGlobalGroups

func GetGlobalGroups() ([]*Group, error)

func GetGroup

func GetGroup(id string) (*Group, error)

func GetGroups

func GetGroups(owner string) ([]*Group, error)

func GetPaginationGroups

func GetPaginationGroups(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Group, error)

func (*Group) GetId

func (group *Group) GetId() string

type GroupNode

type GroupNode struct{}
type Header struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

type HistogramVecInfo

type HistogramVecInfo struct {
	Method  string `json:"method"`
	Name    string `json:"name"`
	Count   uint64 `json:"count"`
	Latency string `json:"latency"`
}

type HttpProvider

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

func (*HttpProvider) CleanUp

func (p *HttpProvider) CleanUp(domain string, token string, keyAuth string) error

func (*HttpProvider) Present

func (p *HttpProvider) Present(domain string, token string, keyAuth string) error

type IdpEntityDescriptor

type IdpEntityDescriptor struct {
	XMLName  xml.Name `xml:"EntityDescriptor"`
	DS       string   `xml:"xmlns:ds,attr"`
	XMLNS    string   `xml:"xmlns,attr"`
	MD       string   `xml:"xmlns:md,attr"`
	EntityId string   `xml:"entityID,attr"`

	IdpSSODescriptor IdpSSODescriptor `xml:"IDPSSODescriptor"`
}

IdpEntityDescriptor SAML METADATA

func GetSamlMeta

func GetSamlMeta(application *Application, host string, enablePostBinding bool) (*IdpEntityDescriptor, error)

type IdpSSODescriptor

type IdpSSODescriptor struct {
	XMLName                    xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:metadata IDPSSODescriptor"`
	ProtocolSupportEnumeration string   `xml:"protocolSupportEnumeration,attr"`
	SigningKeyDescriptor       KeyDescriptor
	NameIDFormats              []NameIDFormat      `xml:"NameIDFormat"`
	SingleSignOnService        SingleSignOnService `xml:"SingleSignOnService"`
	Attribute                  []Attribute         `xml:"Attribute"`
}

type InitData

type InitData struct {
	Organizations []*Organization `json:"organizations"`
	Applications  []*Application  `json:"applications"`
	Users         []*User         `json:"users"`
	Certs         []*Cert         `json:"certs"`
	Providers     []*Provider     `json:"providers"`
	Ldaps         []*Ldap         `json:"ldaps"`
	Models        []*Model        `json:"models"`
	Permissions   []*Permission   `json:"permissions"`
	Resources     []*Resource     `json:"resources"`
	Roles         []*Role         `json:"roles"`
	Syncers       []*Syncer       `json:"syncers"`
	Tokens        []*Token        `json:"tokens"`
	Webhooks      []*Webhook      `json:"webhooks"`
	Groups        []*Group        `json:"groups"`
	Adapters      []*Adapter      `json:"adapters"`
	Enforcers     []*Enforcer     `json:"enforcers"`
	Invitations   []*Invitation   `json:"invitations"`
	Records       []*Record       `json:"records"`
	Sessions      []*Session      `json:"sessions"`
	Sites         []*Site         `json:"sites"`
	Rules         []*Rule         `json:"rules"`

	EnforcerPolicies map[string][][]string `json:"enforcerPolicies"`
}

type IntrospectionResponse

type IntrospectionResponse struct {
	Active    bool     `json:"active"`
	Scope     string   `json:"scope,omitempty"`
	ClientId  string   `json:"client_id,omitempty"`
	Username  string   `json:"username,omitempty"`
	TokenType string   `json:"token_type,omitempty"`
	Exp       int64    `json:"exp,omitempty"`
	Iat       int64    `json:"iat,omitempty"`
	Nbf       int64    `json:"nbf,omitempty"`
	Sub       string   `json:"sub,omitempty"`
	Aud       []string `json:"aud,omitempty"`
	Iss       string   `json:"iss,omitempty"`
	Jti       string   `json:"jti,omitempty"`
}

type Invitation

type Invitation struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
	UpdatedTime string `xorm:"varchar(100)" json:"updatedTime"`
	DisplayName string `xorm:"varchar(100)" json:"displayName"`

	Code      string `xorm:"varchar(100) index" json:"code"`
	IsRegexp  bool   `json:"isRegexp"`
	Quota     int    `json:"quota"`
	UsedCount int    `json:"usedCount"`

	Application string `xorm:"varchar(100)" json:"application"`
	Username    string `xorm:"varchar(100)" json:"username"`
	Email       string `xorm:"varchar(100)" json:"email"`
	Phone       string `xorm:"varchar(100)" json:"phone"`

	SignupGroup string `xorm:"varchar(100)" json:"signupGroup"`
	DefaultCode string `xorm:"varchar(100)" json:"defaultCode"`

	State string `xorm:"varchar(100)" json:"state"`
}

func CheckInvitationCode

func CheckInvitationCode(application *Application, organization *Organization, authForm *form.AuthForm, lang string) (*Invitation, string)

func GetInvitation

func GetInvitation(id string) (*Invitation, error)

func GetInvitationByCode

func GetInvitationByCode(code string, organizationName string, lang string) (*Invitation, string)

func GetInvitations

func GetInvitations(owner string) ([]*Invitation, error)

func GetMaskedInvitation

func GetMaskedInvitation(invitation *Invitation) *Invitation

func GetPaginationInvitations

func GetPaginationInvitations(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Invitation, error)

func (*Invitation) GetId

func (invitation *Invitation) GetId() string
func (invitation *Invitation) GetInvitationLink(host string, application string) string

func (*Invitation) IsInvitationCodeValid

func (invitation *Invitation) IsInvitationCodeValid(application *Application, invitationCode string, username string, email string, phone string, lang string) (bool, string)

func (*Invitation) SimpleCheckInvitationCode

func (invitation *Invitation) SimpleCheckInvitationCode(invitationCode string, lang string) (bool, string)

type JsonWebKeySet

type JsonWebKeySet struct {
	Keys []interface{} `json:"keys"`
}

JsonWebKeySet is a JWKS container that supports both traditional (RSA/EC) and post-quantum (ML-DSA-65) keys. Traditional keys use go-jose serialization; ML-DSA-65 keys use the IETF draft format (kty=MLDSA, alg=MLDSA65).

func GetJsonWebKeySet

func GetJsonWebKeySet(applicationName string) (JsonWebKeySet, error)

type JwtItem

type JwtItem struct {
	Name     string `json:"name"`
	Category string `json:"category"`
	Value    string `json:"value"`
	Type     string `json:"type"`
}

type Key

type Key struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
	UpdatedTime string `xorm:"varchar(100)" json:"updatedTime"`
	DisplayName string `xorm:"varchar(100)" json:"displayName"`

	// Type indicates the scope this key belongs to: "Organization", "Application", "User", or "General"
	Type         string `xorm:"varchar(100)" json:"type"`
	Organization string `xorm:"varchar(100)" json:"organization"`
	Application  string `xorm:"varchar(100)" json:"application"`
	User         string `xorm:"varchar(100)" json:"user"`

	AccessKey    string `xorm:"varchar(100) index" json:"accessKey"`
	AccessSecret string `xorm:"varchar(100)" json:"accessSecret"`

	ExpireTime string `xorm:"varchar(100)" json:"expireTime"`
	State      string `xorm:"varchar(100)" json:"state"`
}

func GetGlobalKeys

func GetGlobalKeys() ([]*Key, error)

func GetKey

func GetKey(id string) (*Key, error)

func GetKeyByAccessKey

func GetKeyByAccessKey(accessKey string) (*Key, error)

GetKeyByAccessKey resolves a key by its AccessKey (pk-) field. For sk- prefixed tokens, use GetKeyBySecretKey instead.

func GetKeyBySecretKey

func GetKeyBySecretKey(secretKey string) (*Key, error)

GetKeyBySecretKey resolves a key by its AccessSecret (sk-) field. Used when a backend sends a secret key for full API access.

func GetKeys

func GetKeys(owner string) ([]*Key, error)

func GetMaskedKey

func GetMaskedKey(key *Key, isMaskEnabled bool) *Key

func GetMaskedKeys

func GetMaskedKeys(keys []*Key, isMaskEnabled bool, err error) ([]*Key, error)

func GetPaginationGlobalKeys

func GetPaginationGlobalKeys(offset, limit int, field, value, sortField, sortOrder string) ([]*Key, error)

func GetPaginationKeys

func GetPaginationKeys(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Key, error)

func ResolveAnyKey

func ResolveAnyKey(token string) (*Key, bool, error)

ResolveAnyKey resolves a token that could be pk-, sk-, or legacy (hk-/bare UUID). Returns the Key and whether it's a publishable key.

func (*Key) GetId

func (key *Key) GetId() string

type KeyDescriptor

type KeyDescriptor struct {
	XMLName xml.Name `xml:"KeyDescriptor"`
	Use     string   `xml:"use,attr"`
	KeyInfo KeyInfo  `xml:"KeyInfo"`
}

type KeyInfo

type KeyInfo struct {
	XMLName  xml.Name `xml:"http://www.w3.org/2000/09/xmldsig# KeyInfo"`
	X509Data X509Data `xml:",innerxml"`
}

type KeycloakSyncerProvider

type KeycloakSyncerProvider struct {
	DatabaseSyncerProvider
}

KeycloakSyncerProvider implements SyncerProvider for Keycloak database syncers Keycloak syncer extends DatabaseSyncerProvider with special handling for Keycloak schema

func (*KeycloakSyncerProvider) GetOriginalGroups

func (p *KeycloakSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error)

GetOriginalGroups retrieves all groups from Keycloak (not implemented yet)

func (*KeycloakSyncerProvider) GetOriginalUserGroups

func (p *KeycloakSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error)

GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)

func (*KeycloakSyncerProvider) GetOriginalUsers

func (p *KeycloakSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error)

GetOriginalUsers retrieves all users from Keycloak database This method overrides the base implementation to handle Keycloak-specific logic

type LarkAccessTokenResp

type LarkAccessTokenResp struct {
	Code              int    `json:"code"`
	Msg               string `json:"msg"`
	TenantAccessToken string `json:"tenant_access_token"`
	Expire            int    `json:"expire"`
}

type LarkAvatar

type LarkAvatar struct {
	Avatar72     string `json:"avatar_72"`
	Avatar240    string `json:"avatar_240"`
	Avatar640    string `json:"avatar_640"`
	AvatarOrigin string `json:"avatar_origin"`
}

type LarkDeptListResp

type LarkDeptListResp struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		Items []struct {
			DepartmentId string `json:"department_id"`
		} `json:"items"`
		HasMore   bool   `json:"has_more"`
		PageToken string `json:"page_token"`
	} `json:"data"`
}

type LarkStatus

type LarkStatus struct {
	IsFrozen    bool `json:"is_frozen"`
	IsResigned  bool `json:"is_resigned"`
	IsActivated bool `json:"is_activated"`
	IsExited    bool `json:"is_exited"`
}

type LarkSyncerProvider

type LarkSyncerProvider struct {
	Syncer *Syncer
}

LarkSyncerProvider implements SyncerProvider for Lark API-based syncers

func (*LarkSyncerProvider) AddUser

func (p *LarkSyncerProvider) AddUser(user *OriginalUser) (bool, error)

AddUser adds a new user to Lark (not supported for read-only API)

func (*LarkSyncerProvider) Close

func (p *LarkSyncerProvider) Close() error

Close closes any open connections (no-op for Lark API-based syncer)

func (*LarkSyncerProvider) GetOriginalGroups

func (p *LarkSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error)

GetOriginalGroups retrieves all groups from Lark (not implemented yet)

func (*LarkSyncerProvider) GetOriginalUserGroups

func (p *LarkSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error)

GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)

func (*LarkSyncerProvider) GetOriginalUsers

func (p *LarkSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error)

GetOriginalUsers retrieves all users from Lark API

func (*LarkSyncerProvider) InitAdapter

func (p *LarkSyncerProvider) InitAdapter() error

InitAdapter initializes the Lark syncer (no database adapter needed)

func (*LarkSyncerProvider) TestConnection

func (p *LarkSyncerProvider) TestConnection() error

TestConnection tests the Lark API connection

func (*LarkSyncerProvider) UpdateUser

func (p *LarkSyncerProvider) UpdateUser(user *OriginalUser) (bool, error)

UpdateUser updates an existing user in Lark (not supported for read-only API)

type LarkUser

type LarkUser struct {
	UserId        string      `json:"user_id"`
	UnionId       string      `json:"union_id"`
	OpenId        string      `json:"open_id"`
	Name          string      `json:"name"`
	EnName        string      `json:"en_name"`
	Email         string      `json:"email"`
	Mobile        string      `json:"mobile"`
	Gender        int         `json:"gender"`
	Avatar        *LarkAvatar `json:"avatar"`
	Status        *LarkStatus `json:"status"`
	DepartmentIds []string    `json:"department_ids"`
	JobTitle      string      `json:"job_title"`
}

type LarkUserListResp

type LarkUserListResp struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		Items     []*LarkUser `json:"items"`
		HasMore   bool        `json:"has_more"`
		PageToken string      `json:"page_token"`
	} `json:"data"`
}

type Ldap

type Ldap struct {
	Id          string `xorm:"varchar(100) notnull pk" json:"id"`
	Owner       string `xorm:"varchar(100)" json:"owner"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	ServerName          string            `xorm:"varchar(100)" json:"serverName"`
	Host                string            `xorm:"varchar(100)" json:"host"`
	Port                int               `xorm:"int" json:"port"`
	EnableSsl           bool              `xorm:"bool" json:"enableSsl"`
	AllowSelfSignedCert bool              `xorm:"bool" json:"allowSelfSignedCert"`
	Username            string            `xorm:"varchar(100)" json:"username"`
	Password            string            `xorm:"varchar(100)" json:"password"`
	BaseDn              string            `xorm:"varchar(500)" json:"baseDn"`
	Filter              string            `xorm:"varchar(200)" json:"filter"`
	FilterFields        []string          `xorm:"mediumtext" json:"filterFields"`
	DefaultGroup        string            `xorm:"varchar(100)" json:"defaultGroup"`
	PasswordType        string            `xorm:"varchar(100)" json:"passwordType"`
	CustomAttributes    map[string]string `json:"customAttributes"`

	AutoSync     int    `json:"autoSync"`
	LastSync     string `xorm:"varchar(100)" json:"lastSync"`
	EnableGroups bool   `xorm:"bool" json:"enableGroups"`
}

func GetLdap

func GetLdap(id string) (*Ldap, error)

func GetLdaps

func GetLdaps(owner string) ([]*Ldap, error)

func GetMaskedLdap

func GetMaskedLdap(ldap *Ldap, errs ...error) (*Ldap, error)

func GetMaskedLdaps

func GetMaskedLdaps(ldaps []*Ldap, errs ...error) ([]*Ldap, error)

func (*Ldap) GetLdapConn

func (ldap *Ldap) GetLdapConn() (c *LdapConn, err error)

type LdapAutoSynchronizer

type LdapAutoSynchronizer struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func GetLdapAutoSynchronizer

func GetLdapAutoSynchronizer() *LdapAutoSynchronizer

func NewLdapAutoSynchronizer

func NewLdapAutoSynchronizer() *LdapAutoSynchronizer

func (*LdapAutoSynchronizer) LdapAutoSynchronizerStartUpAll

func (l *LdapAutoSynchronizer) LdapAutoSynchronizerStartUpAll() error

LdapAutoSynchronizerStartUpAll start all autosync goroutine for existing ldap servers in each organizations

func (*LdapAutoSynchronizer) StartAutoSync

func (l *LdapAutoSynchronizer) StartAutoSync(ldapId string) error

StartAutoSync start autosync for specified ldap, old existing autosync goroutine will be ceased

func (*LdapAutoSynchronizer) StopAutoSync

func (l *LdapAutoSynchronizer) StopAutoSync(ldapId string)

type LdapConn

type LdapConn struct {
	Conn *goldap.Conn
	IsAD bool
}

func (*LdapConn) Close

func (l *LdapConn) Close()

func (*LdapConn) GetLdapGroups

func (l *LdapConn) GetLdapGroups(ldapServer *Ldap) ([]LdapGroup, error)

GetLdapGroups fetches LDAP groups and organizational units

func (*LdapConn) GetLdapUsers

func (l *LdapConn) GetLdapUsers(ldapServer *Ldap) ([]LdapUser, error)

type LdapGroup

type LdapGroup struct {
	Dn          string   `json:"dn"`
	Cn          string   `json:"cn"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Member      []string `json:"member"`
	ParentDn    string   `json:"parentDn"`
}

type LdapUser

type LdapUser struct {
	UidNumber string `json:"uidNumber"`
	Uid       string `json:"uid"`
	Cn        string `json:"cn"`
	GidNumber string `json:"gidNumber"`
	// Gcn                   string
	Uuid                  string `json:"uuid"`
	UserPrincipalName     string `json:"userPrincipalName"`
	DisplayName           string `json:"displayName"`
	Mail                  string
	Email                 string `json:"email"`
	EmailAddress          string
	TelephoneNumber       string
	Mobile                string `json:"mobile"`
	MobileTelephoneNumber string
	RegisteredAddress     string
	PostalAddress         string
	Country               string `json:"country"`
	CountryName           string `json:"countryName"`

	GroupId    string            `json:"groupId"`
	Address    string            `json:"address"`
	MemberOf   []string          `json:"memberOf"`
	Attributes map[string]string `json:"attributes"`
}

func AutoAdjustLdapUser

func AutoAdjustLdapUser(users []LdapUser) []LdapUser

func (*LdapUser) GetLdapUuid

func (ldapUser *LdapUser) GetLdapUuid() string
type Link struct {
	Rel   string
	Sizes string
	Href  string
}

type MLDSA65WebKey

type MLDSA65WebKey struct {
	Kty string `json:"kty"`
	Alg string `json:"alg"`
	Use string `json:"use"`
	Kid string `json:"kid"`
	X   string `json:"x"` // base64url-encoded raw public key
}

MLDSA65WebKey is the JWK representation of an ML-DSA-65 public key, following the IETF draft convention for post-quantum JWK.

type ManagedAccount

type ManagedAccount struct {
	Application string `xorm:"varchar(100)" json:"application"`
	Username    string `xorm:"varchar(100)" json:"username"`
	Password    string `xorm:"varchar(100)" json:"password"`
	SigninUrl   string `xorm:"varchar(200)" json:"signinUrl"`
}

type Membership added in v1.31.31

type Membership struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(255) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	User string `xorm:"varchar(150) index" json:"user"` // the user id, "<homeOrg>/<username>"
	Org  string `xorm:"varchar(100) index" json:"org"`  // the org slug the user may act in
	Role string `xorm:"varchar(100)" json:"role"`       // coarse org role: owner | admin | member
}

Membership records that a user may ACT IN an org — the (User × Org × Role) relation that lets ONE identity belong to its personal org AND team orgs. It is the tenancy set the JWT emits as the `orgs` claim, against which the edge authorizes an org-switch (X-Org-Id ∈ orgs) with no round-trip.

It is orthogonal to the Role/Permission catalog: Membership answers "which orgs may this identity act in, and with what COARSE role (owner|admin|member)", while Role/Permission answer fine-grained authorization WITHIN an org. A user's HOME org (User.Owner) is always an implicit membership; explicit rows add the TEAM orgs the user has been invited into.

Like every org row it is owned by the platform ("admin"); the natural key (Owner, Name) uses Name = "<userId>|<org>" so a (user, org) pair is unique. The User and Org columns are the hot lookup paths and stay indexed.

func GetMembershipsByOrg added in v1.31.31

func GetMembershipsByOrg(org string) ([]*Membership, error)

GetMembershipsByOrg returns every user who may act in an org — the org's roster.

func GetMembershipsByUser added in v1.31.31

func GetMembershipsByUser(userId string) ([]*Membership, error)

GetMembershipsByUser returns every org a user may act in — the explicit team memberships. The caller unions the user's HOME org (memberOrgRefs) so the token set is complete even before any team is joined.

type MfaAccount

type MfaAccount struct {
	AccountName string `xorm:"varchar(100)" json:"accountName"`
	Issuer      string `xorm:"varchar(100)" json:"issuer"`
	SecretKey   string `xorm:"varchar(100)" json:"secretKey"`
	Origin      string `xorm:"varchar(100)" json:"origin"`
}

type MfaInterface

type MfaInterface interface {
	Initiate(userId string, issuer string) (*MfaProps, error)
	SetupVerify(passcode string) error
	Enable(user *User) error
	Verify(passcode string) error
}

func GetMfaUtil

func GetMfaUtil(mfaType string, config *MfaProps) MfaInterface

type MfaItem

type MfaItem struct {
	Name string `json:"name"`
	Rule string `json:"rule"`
}

type MfaProps

type MfaProps struct {
	Enabled            bool     `json:"enabled"`
	IsPreferred        bool     `json:"isPreferred"`
	MfaType            string   `json:"mfaType" form:"mfaType"`
	Secret             string   `json:"secret,omitempty"`
	CountryCode        string   `json:"countryCode,omitempty"`
	URL                string   `json:"url,omitempty"`
	RecoveryCodes      []string `json:"recoveryCodes,omitempty"`
	MfaRememberInHours int      `json:"mfaRememberInHours"`
}

func GetAllMfaProps

func GetAllMfaProps(user *User, masked bool) []*MfaProps

type MigrationTarget added in v1.20.3

type MigrationTarget struct {
	// Global is the enveloped global iam.db engine ({dataDir}/iam.db, principal
	// "global"). All non-User tables go here.
	Global *xorm.Engine
	// Mgr owns the per-org enveloped user dbs ({dataDir}/orgs/<slug>/iam.db).
	Mgr *OrgDBManager
	// contains filtered or unexported fields
}

MigrationTarget is the destination of a Postgres→SQLite migration: the ENVELOPED on-disk layout the running IAM actually opens. It is built from the SAME primitives the runtime uses (openEncrypted for the global db, OrgDBManager for per-org user dbs), so the migrated files are byte-for-byte the shape the daemon expects — no separate "staging" format that the runtime would then refuse to open.

Routing mirrors the runtime exactly: only the User table is per-org (see orgEngine, called only from user.go); every other table lives on the global engine. So a migrator copies User rows into OrgEngine(owner) and all other tables into Global.

func NewMigrationTarget added in v1.20.3

func NewMigrationTarget(dataDir string) (*MigrationTarget, error)

NewMigrationTarget opens (creating) the enveloped destination layout under dataDir. It REQUIRES IAM_KMS_MASTER_KEY to be set and the build to be able to encrypt (CGO + libsqlcipher); otherwise it fails closed rather than writing a plaintext layout the runtime could never safely consume. The global engine has the full global schema synced; per-org user schemas are synced lazily by the manager on first OrgEngine(owner).

func (*MigrationTarget) Close added in v1.20.3

func (t *MigrationTarget) Close()

Close releases the global engine and all per-org engines.

func (*MigrationTarget) OrgEngine added in v1.20.3

func (t *MigrationTarget) OrgEngine(owner string) (*xorm.Engine, error)

OrgEngine returns the enveloped per-org engine for owner (creating + syncing it on first use), the destination for that org's User rows. Same routing the runtime uses via orgEngine(owner).

type Model

type Model struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
	DisplayName string `xorm:"varchar(100)" json:"displayName"`
	Description string `xorm:"varchar(100)" json:"description"`

	ModelText string `xorm:"mediumtext" json:"modelText"`

	authzmodel.Model `xorm:"-" json:"-"`
}

func GetModel

func GetModel(id string) (*Model, error)

func GetModels

func GetModels(owner string) ([]*Model, error)

func GetPaginationModels

func GetPaginationModels(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Model, error)

func (*Model) GetId

func (m *Model) GetId() string

type NameIDFormat

type NameIDFormat struct {
	// XMLName xml.Name
	Value string `xml:",innerxml"`
}

type NodeItem

type NodeItem struct {
	Name     string `json:"name"`
	Version  string `json:"version"`
	Diff     string `json:"diff"`
	Pid      int    `json:"pid"`
	Status   string `json:"status"`
	Message  string `json:"message"`
	Provider string `json:"provider"`
}

type NotifySendInput added in v1.18.7

type NotifySendInput struct {
	// Channel is "sms" or "email".
	Channel string

	// Recipient is the E.164 phone number (SMS) or the email address (email).
	Recipient string

	// OTP is the code generated by getVerificationCode.
	OTP string

	// AppName is the IAM application name, surfaced in the template as {{.app}}.
	AppName string

	// Tenant is the IAM organization owning this OTP. Informational only under the
	// ZAP path: cloud derives the send's org from the VALIDATED M2M principal, never
	// from a client-supplied value — the cross-tenant isolation boundary.
	Tenant string

	// IdempotencyKey, when set, dedupes notify sends on retry.
	IdempotencyKey string
}

NotifySendInput is the IAM-side shape of one OTP send.

type OIDCAddress

type OIDCAddress struct {
	Formatted     string `json:"formatted"`
	StreetAddress string `json:"street_address"`
	Locality      string `json:"locality"`
	Region        string `json:"region"`
	PostalCode    string `json:"postal_code"`
	Country       string `json:"country"`
}

type OauthProtectedResourceMetadata

type OauthProtectedResourceMetadata struct {
	Resource               string   `json:"resource"`
	AuthorizationServers   []string `json:"authorization_servers"`
	BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
	ScopesSupported        []string `json:"scopes_supported,omitempty"`
	ResourceSigningAlg     []string `json:"resource_signing_alg_values_supported,omitempty"`
	ResourceDocumentation  string   `json:"resource_documentation,omitempty"`
}

OauthProtectedResourceMetadata represents RFC 9728 OAuth 2.0 Protected Resource Metadata

func GetOauthProtectedResourceMetadata

func GetOauthProtectedResourceMetadata(host string) OauthProtectedResourceMetadata

GetOauthProtectedResourceMetadata returns RFC 9728 Protected Resource Metadata for global discovery

func GetOauthProtectedResourceMetadataByApplication

func GetOauthProtectedResourceMetadataByApplication(host string, applicationName string) OauthProtectedResourceMetadata

GetOauthProtectedResourceMetadataByApplication returns RFC 9728 Protected Resource Metadata for application-specific discovery

type OidcDiscovery

type OidcDiscovery struct {
	Issuer                                    string   `json:"issuer"`
	AuthorizationEndpoint                     string   `json:"authorization_endpoint"`
	TokenEndpoint                             string   `json:"token_endpoint"`
	UserinfoEndpoint                          string   `json:"userinfo_endpoint"`
	DeviceAuthorizationEndpoint               string   `json:"device_authorization_endpoint"`
	RegistrationEndpoint                      string   `json:"registration_endpoint,omitempty"`
	JwksUri                                   string   `json:"jwks_uri"`
	IntrospectionEndpoint                     string   `json:"introspection_endpoint"`
	RevocationEndpoint                        string   `json:"revocation_endpoint"`
	ResponseTypesSupported                    []string `json:"response_types_supported"`
	ResponseModesSupported                    []string `json:"response_modes_supported"`
	GrantTypesSupported                       []string `json:"grant_types_supported"`
	SubjectTypesSupported                     []string `json:"subject_types_supported"`
	IdTokenSigningAlgValuesSupported          []string `json:"id_token_signing_alg_values_supported"`
	ScopesSupported                           []string `json:"scopes_supported"`
	TokenEndpointAuthMethodsSupported         []string `json:"token_endpoint_auth_methods_supported"`
	IntrospectionEndpointAuthMethodsSupported []string `json:"introspection_endpoint_auth_methods_supported"`
	RevocationEndpointAuthMethodsSupported    []string `json:"revocation_endpoint_auth_methods_supported"`
	CodeChallengeMethodsSupported             []string `json:"code_challenge_methods_supported"`
	ClaimsSupported                           []string `json:"claims_supported"`
	RequestParameterSupported                 bool     `json:"request_parameter_supported"`
	RequestObjectSigningAlgValuesSupported    []string `json:"request_object_signing_alg_values_supported"`
	EndSessionEndpoint                        string   `json:"end_session_endpoint"`
}

func GetOidcDiscovery

func GetOidcDiscovery(host string, applicationName string) OidcDiscovery

type OktaSyncerProvider

type OktaSyncerProvider struct {
	Syncer *Syncer
}

OktaSyncerProvider implements SyncerProvider for Okta API-based syncers

func (*OktaSyncerProvider) AddUser

func (p *OktaSyncerProvider) AddUser(user *OriginalUser) (bool, error)

AddUser adds a new user to Okta (not supported for read-only API)

func (*OktaSyncerProvider) Close

func (p *OktaSyncerProvider) Close() error

Close closes any open connections (no-op for Okta API-based syncer)

func (*OktaSyncerProvider) GetOriginalGroups

func (p *OktaSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error)

GetOriginalGroups retrieves all groups from Okta (not implemented yet)

func (*OktaSyncerProvider) GetOriginalUserGroups

func (p *OktaSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error)

GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)

func (*OktaSyncerProvider) GetOriginalUsers

func (p *OktaSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error)

GetOriginalUsers retrieves all users from Okta API

func (*OktaSyncerProvider) InitAdapter

func (p *OktaSyncerProvider) InitAdapter() error

InitAdapter initializes the Okta syncer (no database adapter needed)

func (*OktaSyncerProvider) TestConnection

func (p *OktaSyncerProvider) TestConnection() error

TestConnection tests the Okta API connection

func (*OktaSyncerProvider) UpdateUser

func (p *OktaSyncerProvider) UpdateUser(user *OriginalUser) (bool, error)

UpdateUser updates an existing user in Okta (not supported for read-only API)

type OktaUser

type OktaUser struct {
	Id      string `json:"id"`
	Status  string `json:"status"`
	Created string `json:"created"`
	Profile struct {
		Login             string `json:"login"`
		Email             string `json:"email"`
		FirstName         string `json:"firstName"`
		LastName          string `json:"lastName"`
		DisplayName       string `json:"displayName"`
		MobilePhone       string `json:"mobilePhone"`
		PrimaryPhone      string `json:"primaryPhone"`
		StreetAddress     string `json:"streetAddress"`
		City              string `json:"city"`
		State             string `json:"state"`
		ZipCode           string `json:"zipCode"`
		CountryCode       string `json:"countryCode"`
		PostalAddress     string `json:"postalAddress"`
		PreferredLanguage string `json:"preferredLanguage"`
		Locale            string `json:"locale"`
		Timezone          string `json:"timezone"`
		Title             string `json:"title"`
		Department        string `json:"department"`
		Organization      string `json:"organization"`
	} `json:"profile"`
}

OktaUser represents a user from Okta API

type OrgDBManager

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

OrgDBManager manages per-org SQLite databases for IAM.

Directory layout:

{DataDir}/iam.db                     ← Global: certs (JWT signing keys),
                                       providers, admin org/app/user catalog.
{DataDir}/iam.db.dek                 ← Wrapped DEK for the global db.
{DataDir}/orgs/{orgSlug}/iam.db      ← Per-org: users, apps, providers, tokens.
{DataDir}/orgs/{orgSlug}/iam.db.dek  ← Wrapped DEK for that org's db.

When orgIsolation is "none" (default), this manager is nil and all queries go through the global ormer.Engine as before.

ENCRYPTION AT REST (envelope model — rotation-safe):

When a 32-byte master key is configured (IAM_KMS_MASTER_KEY, 64 hex chars), each database has its OWN random DEK (SQLCipher page key), generated once at creation and wrapped (AES-256-GCM) under a KEK = HKDF(masterKey, "org:{slug}"). The wrapped DEK lives in the `<db>.dek` sidecar; the raw DEK is never written. Rotating the master key only rewraps the sidecar (see Rewrap) — the DEK is unchanged, so the encrypted pages are never rewritten and no file is bricked.

Directory isolation separates org data on disk; the per-org DEK ensures one org's file cannot be read with another org's key even if exfiltrated.

func NewOrgDBManager

func NewOrgDBManager(dataDir string) (*OrgDBManager, error)

NewOrgDBManager creates a new per-org database manager.

Encryption posture is decided once, here, from IAM_KMS_MASTER_KEY:

  • unset → unencrypted per-org files (dev / CGO-off CI).
  • set + cgo build → per-org SQLCipher encryption (production).
  • set + !cgo build → hard error (resolveMasterKey). We refuse to run: a master key was supplied but this binary cannot encrypt, and silently writing plaintext org databases would violate the security contract.

Directory permissions are 0700.

func (*OrgDBManager) DeleteOrg

func (m *OrgDBManager) DeleteOrg(owner string) error

DeleteOrg removes an org's engine from the pool and deletes its directory.

func (*OrgDBManager) Encrypted added in v1.20.3

func (m *OrgDBManager) Encrypted() bool

Encrypted reports whether this manager encrypts org databases at rest.

func (*OrgDBManager) GetEngine

func (m *OrgDBManager) GetEngine(owner string) (*xorm.Engine, error)

GetEngine returns the xorm engine for an org, creating it on demand. The caller passes the RAW org owner; canonicalization to a slug happens here, so no caller can route to the wrong file or be rejected for a "weird" name.

func (*OrgDBManager) ListOrgs

func (m *OrgDBManager) ListOrgs() ([]string, error)

ListOrgs returns all provisioned org slugs by scanning the orgs directory.

func (*OrgDBManager) ProvisionOrg

func (m *OrgDBManager) ProvisionOrg(owner string) error

ProvisionOrg creates the org directory, database, and syncs org-scoped tables.

func (*OrgDBManager) ReleasePools

func (m *OrgDBManager) ReleasePools()

ReleasePools closes all org engines. Call on shutdown.

func (*OrgDBManager) Rewrap added in v1.20.3

func (m *OrgDBManager) Rewrap(oldMaster, newMaster []byte) error

Rewrap rotates the master key for every provisioned org database (and is the mechanism that makes KMS master-key rotation non-destructive). For each org sidecar it unwraps the DEK with the OLD master's KEK and rewraps it with the NEW master's KEK, replacing the sidecar atomically. The DEK — and therefore every encrypted page — is never touched, so rotation cannot brick a file.

Call with the CURRENTLY-configured master key as oldMaster and the incoming key as newMaster. On success the manager's in-memory master key is updated; callers should re-open engines (or restart) to pick up the new posture. Any per-file failure aborts BEFORE mutating that file, so a partial rotation never loses data (already-rewrapped files remain readable under newMaster; the rest remain readable under oldMaster — operators re-run with the appropriate pair).

type OrgRef added in v1.31.34

type OrgRef struct {
	Org  string `json:"org"`
	Role string `json:"role,omitempty"`
}

OrgRef is the minimal membership shape carried in an access token: an org the subject may act in, plus the subject's coarse role there. Like roleRef it stays slug-sized so the token stays inside the edge request-header buffer even for a user in many orgs. The gateway authorizes an org-switch against this set (X-Org-Id ∈ orgs) with no round-trip.

func MemberOrgRefs added in v1.31.34

func MemberOrgRefs(user *User) []OrgRef

MemberOrgRefs resolves the org-membership SET a token carries for a user: the user's HOME org (User.Owner) always, plus every org the user has an explicit Membership in. Home is listed first and wins on a duplicate. Resolved once at mint time and threaded into every token format as the `orgs` claim, mirroring how `project` rides alongside `organization`.

type Organization

type Organization struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	// Parent is the tenancy edge: the org that RESELLS/hosts this one. Empty for a
	// top-level tenant. A reseller (white-label partner building on the stack) is the
	// parent of the orgs it onboards, so its admins administer them and its account
	// can roll their usage up. Orgs were flat before this, which made a reseller
	// indistinguishable from an unrelated customer.
	//
	// Every read of this edge MUST go through the ancestry helpers below — they bound
	// the walk and refuse cycles. A cycle in a parent chain that authz trusts is a
	// privilege-escalation primitive (A parent of B, B parent of A ⇒ each administers
	// the other), so the write path rejects cycles and the read path never loops.
	Parent string `xorm:"varchar(100)" json:"parent"`

	// SignupCreatesTenant makes this org a PLATFORM rather than a tenant: a signup
	// against one of its applications lands the user in a NEW child org (Parent =
	// this org) instead of in this org itself.
	//
	// This is what makes billing honest. Commerce namespaces by org, and the balance
	// gate reads the user's org — so while every founder was created inside "hanzo",
	// a brand-new $0 account read HANZO's balance and sailed through the gate. We were
	// enforcing our own wallet. With their own org, the gate reads theirs.
	//
	// Opt-in per org, so a white-label deployment does not silently change shape.
	SignupCreatesTenant bool `xorm:"bool" json:"signupCreatesTenant"`

	DisplayName            string     `xorm:"varchar(100)" json:"displayName"`
	WebsiteUrl             string     `xorm:"varchar(100)" json:"websiteUrl"`
	LogoDark               string     `xorm:"varchar(200)" json:"logoDark"`
	Favicon                string     `xorm:"varchar(200)" json:"favicon"`
	HasPrivilegeConsent    bool       `xorm:"bool" json:"hasPrivilegeConsent"`
	PasswordType           string     `xorm:"varchar(100)" json:"passwordType"`
	PasswordSalt           string     `xorm:"varchar(100)" json:"passwordSalt"`
	PasswordOptions        []string   `xorm:"mediumtext" json:"passwordOptions"`
	PasswordObfuscatorType string     `xorm:"varchar(100)" json:"passwordObfuscatorType"`
	PasswordObfuscatorKey  string     `xorm:"varchar(100)" json:"passwordObfuscatorKey"`
	PasswordExpireDays     int        `json:"passwordExpireDays"`
	CountryCodes           []string   `xorm:"mediumtext"  json:"countryCodes"`
	DefaultAvatar          string     `xorm:"varchar(200)" json:"defaultAvatar"`
	UsePermanentAvatar     bool       `xorm:"bool" json:"usePermanentAvatar"`
	DefaultApplication     string     `xorm:"varchar(100)" json:"defaultApplication"`
	UserTypes              []string   `xorm:"mediumtext" json:"userTypes"`
	Tags                   []string   `xorm:"mediumtext" json:"tags"`
	Languages              []string   `xorm:"mediumtext" json:"languages"`
	ThemeData              *ThemeData `xorm:"json" json:"themeData"`
	MasterPassword         string     `xorm:"varchar(200)" json:"masterPassword"`
	DefaultPassword        string     `xorm:"varchar(200)" json:"defaultPassword"`
	MasterVerificationCode string     `xorm:"varchar(100)" json:"masterVerificationCode"`
	IpWhitelist            string     `xorm:"varchar(200)" json:"ipWhitelist"`
	InitScore              int        `json:"initScore"`
	EnableSoftDeletion     bool       `json:"enableSoftDeletion"`
	IsProfilePublic        bool       `json:"isProfilePublic"`
	UseEmailAsUsername     bool       `json:"useEmailAsUsername"`
	EnableTour             bool       `json:"enableTour"`
	DisableSignin          bool       `json:"disableSignin"`
	IpRestriction          string     `json:"ipRestriction"`
	NavItems               []string   `xorm:"mediumtext" json:"navItems"`
	UserNavItems           []string   `xorm:"mediumtext" json:"userNavItems"`
	WidgetItems            []string   `xorm:"mediumtext" json:"widgetItems"`

	MfaItems           []*MfaItem     `xorm:"mediumtext" json:"mfaItems"`
	MfaRememberInHours int            `json:"mfaRememberInHours"`
	AccountMenu        string         `xorm:"varchar(20)" json:"accountMenu"`
	AccountItems       []*AccountItem `xorm:"mediumtext" json:"accountItems"`

	// Per-org signin rate limiting. Overrides the application-level defaults.
	// 0 = use the application setting (which defaults to 5 attempts / 15 min).
	FailedSigninLimit      int `json:"failedSigninLimit"`
	FailedSigninFrozenTime int `json:"failedSigninFrozenTime"`

	DcrPolicy string `xorm:"varchar(100)" json:"dcrPolicy"`

	LdapAttributes      []string `xorm:"mediumtext" json:"ldapAttributes"`
	KerberosRealm       string   `xorm:"varchar(200)" json:"kerberosRealm"`
	KerberosKdcHost     string   `xorm:"varchar(200)" json:"kerberosKdcHost"`
	KerberosKeytab      string   `xorm:"mediumtext" json:"kerberosKeytab"`
	KerberosServiceName string   `xorm:"varchar(100)" json:"kerberosServiceName"`

	// DEPRECATED: Balance is managed by Commerce (billing.hanzo.ai). Do not write to these fields.
	OrgBalance      float64 `json:"orgBalance"`
	UserBalance     float64 `json:"userBalance"`
	BalanceCredit   float64 `json:"balanceCredit"`
	BalanceCurrency string  `xorm:"varchar(100)" json:"balanceCurrency"`

	IsPersonal bool `xorm:"bool" json:"isPersonal"`
}

func CreatePersonalOrganization

func CreatePersonalOrganization(username, displayName string) (*Organization, error)

CreatePersonalOrganization creates a personal organization and default application for a new user. Uses a database transaction for atomicity — if either insert fails, both are rolled back.

func GetMaskedOrganization

func GetMaskedOrganization(organization *Organization, errs ...error) (*Organization, error)

func GetMaskedOrganizations

func GetMaskedOrganizations(organizations []*Organization, errs ...error) ([]*Organization, error)

func GetOrganization

func GetOrganization(id string) (*Organization, error)

func GetOrganizationByUser

func GetOrganizationByUser(user *User) (*Organization, error)

func GetOrganizations

func GetOrganizations(owner string, name ...string) ([]*Organization, error)

func GetOrganizationsByFields

func GetOrganizationsByFields(owner string, fields ...string) ([]*Organization, error)

func GetPaginationOrganizations

func GetPaginationOrganizations(owner string, name string, offset, limit int, field, value, sortField, sortOrder string) ([]*Organization, error)

func NewAdminOrg added in v1.14.21

func NewAdminOrg() *Organization

NewAdminOrg returns the admin organization placeholder (owner=name=admin).

func NewOrg added in v1.14.21

func NewOrg(name string) *Organization

NewOrg returns an *Organization placeholder owned by the admin org with the given name. Useful for non-admin orgs that the admin user creates.

func (*Organization) GetInitScore

func (org *Organization) GetInitScore() (int, error)

type OriginalGroup

type OriginalGroup struct {
	Id          string
	Name        string
	DisplayName string
	Description string
	Type        string
	Manager     string
	Email       string
}

OriginalGroup represents a group from an external system

type OriginalUser

type OriginalUser = User

type Ormer

type Ormer struct {
	Db           *sql.DB
	Engine       *xorm.Engine
	OrgDBManager *OrgDBManager // nil when orgIsolation != "sqlite"
	// contains filtered or unexported fields
}

Ormer represents the MySQL adapter for policy storage.

func NewAdapter

func NewAdapter(driverName string, dataSourceName string, dbName string) (*Ormer, error)

NewAdapter is the constructor for Ormer.

func NewAdapterFromDb

func NewAdapterFromDb(driverName string, dataSourceName string, dbName string, db *sql.DB) (*Ormer, error)

NewAdapterFromDb is the constructor for Ormer.

func (*Ormer) CreateDatabase

func (a *Ormer) CreateDatabase() error

type PK

type PK = []interface{}

PK is a composite primary key type. Composite primary key type for hanzoai/xorm compatibility.

type Permission

type Permission struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
	DisplayName string `xorm:"varchar(100)" json:"displayName"`
	Description string `xorm:"varchar(100)" json:"description"`

	Users   []string `xorm:"mediumtext" json:"users"`
	Groups  []string `xorm:"mediumtext" json:"groups"`
	Roles   []string `xorm:"mediumtext" json:"roles"`
	Domains []string `xorm:"mediumtext" json:"domains"`

	Model        string   `xorm:"varchar(100)" json:"model"`
	Adapter      string   `xorm:"varchar(100)" json:"adapter"`
	ResourceType string   `xorm:"varchar(100)" json:"resourceType"`
	Resources    []string `xorm:"mediumtext" json:"resources"`
	Actions      []string `xorm:"mediumtext" json:"actions"`
	Effect       string   `xorm:"varchar(100)" json:"effect"`
	IsEnabled    bool     `json:"isEnabled"`

	Submitter   string `xorm:"varchar(100)" json:"submitter"`
	Approver    string `xorm:"varchar(100)" json:"approver"`
	ApproveTime string `xorm:"varchar(100)" json:"approveTime"`
	State       string `xorm:"varchar(100)" json:"state"`
}

func GetMaskedPermissions

func GetMaskedPermissions(permissions []*Permission) []*Permission

func GetPaginationPermissions

func GetPaginationPermissions(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Permission, error)

func GetPermission

func GetPermission(id string) (*Permission, error)

func GetPermissions

func GetPermissions(owner string) ([]*Permission, error)

func GetPermissionsByModel

func GetPermissionsByModel(owner string, model string) ([]*Permission, error)

func GetPermissionsByResource

func GetPermissionsByResource(resourceId string) ([]*Permission, error)

func GetPermissionsByRole

func GetPermissionsByRole(roleId string) ([]*Permission, error)

func GetPermissionsBySubmitter

func GetPermissionsBySubmitter(owner string, submitter string) ([]*Permission, error)

func TeamPermissionFor added in v1.31.26

func TeamPermissionFor(org string, r teamrole.Role) *Permission

TeamPermissionFor builds (does not persist) the Casbin Permission row that binds a catalog role to its resource+actions, so downstream surfaces can call /v1/iam/enforce for app-scope checks. Pure: no DB. Mirrors the proven initAdminPermission shape (Effect Allow, Approved) but is role-bound and org-scoped.

func (*Permission) GetId

func (p *Permission) GetId() string

func (*Permission) GetModelAndAdapter

func (p *Permission) GetModelAndAdapter() string

type ProductInfo

type ProductInfo struct {
	Owner       string  `json:"owner"`
	Name        string  `json:"name"`
	DisplayName string  `json:"displayName"`
	Price       float64 `json:"price"`
	Quantity    int     `json:"quantity,omitempty"`
}

DEPRECATED: ProductInfo is retained for backward compatibility with the Cart column. Billing is now managed by Commerce (billing.hanzo.ai).

type Project

type Project struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	DisplayName  string   `xorm:"varchar(100)" json:"displayName"`
	Description  string   `xorm:"varchar(500)" json:"description"`
	Organization string   `xorm:"varchar(100) index" json:"organization"`
	Tags         []string `xorm:"mediumtext" json:"tags"`
	Metadata     string   `xorm:"mediumtext" json:"metadata"`
	IsDefault    bool     `json:"isDefault"`
}

Project represents a project within an organization. Organizations contain projects, which scope applications and usage tracking.

func GetDefaultProject added in v1.31.22

func GetDefaultProject(organization string) (*Project, error)

GetDefaultProject returns an organization's default project — the row whose Organization matches and IsDefault is true — or nil when the org has none. It is read at token-mint time to stamp the `project` claim, so it queries the indexed Organization column and never falls back to a non-default project.

func GetOrganizationProjects

func GetOrganizationProjects(organization string) ([]*Project, error)

func GetPaginationProjects

func GetPaginationProjects(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Project, error)

func GetProject

func GetProject(id string) (*Project, error)

func GetProjects

func GetProjects(owner string) ([]*Project, error)

func (*Project) GetId

func (project *Project) GetId() string

type PrometheusInfo

type PrometheusInfo struct {
	ApiThroughput   []GaugeVecInfo     `json:"apiThroughput"`
	ApiLatency      []HistogramVecInfo `json:"apiLatency"`
	TotalThroughput float64            `json:"totalThroughput"`
}

func GetPrometheusInfo

func GetPrometheusInfo() (*PrometheusInfo, error)

type Provider

type Provider struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk unique" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	DisplayName       string            `xorm:"varchar(100)" json:"displayName"`
	Category          string            `xorm:"varchar(100)" json:"category"`
	Type              string            `xorm:"varchar(100)" json:"type"`
	SubType           string            `xorm:"varchar(100)" json:"subType"`
	Method            string            `xorm:"varchar(100)" json:"method"`
	ClientId          string            `xorm:"varchar(200)" json:"clientId"`
	ClientSecret      string            `xorm:"varchar(3000)" json:"clientSecret"`
	ClientId2         string            `xorm:"varchar(100)" json:"clientId2"`
	ClientSecret2     string            `xorm:"varchar(500)" json:"clientSecret2"`
	Cert              string            `xorm:"varchar(100)" json:"cert"`
	CustomAuthUrl     string            `xorm:"varchar(200)" json:"customAuthUrl"`
	CustomTokenUrl    string            `xorm:"varchar(200)" json:"customTokenUrl"`
	CustomUserInfoUrl string            `xorm:"varchar(200)" json:"customUserInfoUrl"`
	Scopes            string            `xorm:"varchar(100)" json:"scopes"`
	UserMapping       map[string]string `xorm:"varchar(500)" json:"userMapping"`
	HttpHeaders       map[string]string `xorm:"varchar(500)" json:"httpHeaders"`

	Host       string `xorm:"varchar(100)" json:"host"`
	Port       int    `json:"port"`
	DisableSsl bool   `json:"disableSsl"`                  // Deprecated: Use SslMode instead. If the provider type is WeChat, DisableSsl means EnableQRCode, if type is Google, it means sync phone number
	SslMode    string `xorm:"varchar(100)" json:"sslMode"` // "Auto" (empty means Auto), "Enable", "Disable"
	Title      string `xorm:"varchar(100)" json:"title"`
	Content    string `xorm:"varchar(2000)" json:"content"` // If provider type is WeChat, Content means QRCode string by Base64 encoding
	Receiver   string `xorm:"varchar(100)" json:"receiver"`

	RegionId     string `xorm:"varchar(100)" json:"regionId"`
	SignName     string `xorm:"varchar(100)" json:"signName"`
	TemplateCode string `xorm:"varchar(100)" json:"templateCode"`
	AppId        string `xorm:"varchar(100)" json:"appId"`

	Endpoint         string `xorm:"varchar(1000)" json:"endpoint"`
	IntranetEndpoint string `xorm:"varchar(100)" json:"intranetEndpoint"`
	Domain           string `xorm:"varchar(100)" json:"domain"`
	Bucket           string `xorm:"varchar(100)" json:"bucket"`
	PathPrefix       string `xorm:"varchar(100)" json:"pathPrefix"`

	Metadata               string `xorm:"mediumtext" json:"metadata"`
	IdP                    string `xorm:"mediumtext" json:"idP"`
	IssuerUrl              string `xorm:"varchar(100)" json:"issuerUrl"`
	EnableSignAuthnRequest bool   `json:"enableSignAuthnRequest"`
	EmailRegex             string `xorm:"varchar(200)" json:"emailRegex"`

	ProviderUrl string `xorm:"varchar(200)" json:"providerUrl"`
	EnableProxy bool   `json:"enableProxy"`
	EnablePkce  bool   `json:"enablePkce"`
}

func GetCaptchaProviderByApplication

func GetCaptchaProviderByApplication(applicationId, isCurrentProvider, lang string) (*Provider, error)

func GetCaptchaProviderByOwnerName

func GetCaptchaProviderByOwnerName(applicationId, lang string) (*Provider, error)

func GetFaceIdProviderByApplication

func GetFaceIdProviderByApplication(applicationId, isCurrentProvider, lang string) (*Provider, error)

func GetFaceIdProviderByOwnerName

func GetFaceIdProviderByOwnerName(applicationId, lang string) (*Provider, error)

func GetGlobalProviders

func GetGlobalProviders() ([]*Provider, error)

func GetIdvProviderByApplication

func GetIdvProviderByApplication(applicationId, isCurrentProvider, lang string) (*Provider, error)

func GetIdvProviderByOwnerName

func GetIdvProviderByOwnerName(applicationId, lang string) (*Provider, error)

func GetMaskedProvider

func GetMaskedProvider(provider *Provider, isMaskEnabled bool) *Provider

func GetMaskedProviders

func GetMaskedProviders(providers []*Provider, isMaskEnabled bool) []*Provider

func GetPaginationGlobalProviders

func GetPaginationGlobalProviders(offset, limit int, field, value, sortField, sortOrder string) ([]*Provider, error)

func GetPaginationProviders

func GetPaginationProviders(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Provider, error)

func GetProvider

func GetProvider(id string) (*Provider, error)

func GetProviders

func GetProviders(owner string) ([]*Provider, error)

func GetProvidersByCategory

func GetProvidersByCategory(owner string, category string) ([]*Provider, error)

func GetWechatMiniProgramProvider

func GetWechatMiniProgramProvider(application *Application) *Provider

func (*Provider) GetId

func (p *Provider) GetId() string

type ProviderItem

type ProviderItem struct {
	Owner string `json:"owner"`
	Name  string `json:"name"`

	CanSignUp    bool      `json:"canSignUp"`
	CanSignIn    bool      `json:"canSignIn"`
	CanUnlink    bool      `json:"canUnlink"`
	CountryCodes []string  `json:"countryCodes"`
	Prompted     bool      `json:"prompted"`
	SignupGroup  string    `json:"signupGroup"`
	Rule         string    `json:"rule"`
	Provider     *Provider `json:"provider"`
}

func (*ProviderItem) IsProviderVisible

func (pi *ProviderItem) IsProviderVisible() bool

type PushMfa

type PushMfa struct {
	*MfaProps
	// contains filtered or unexported fields
}

func NewPushMfaUtil

func NewPushMfaUtil(config *MfaProps) *PushMfa

func (*PushMfa) Enable

func (mfa *PushMfa) Enable(user *User) error

func (*PushMfa) Initiate

func (mfa *PushMfa) Initiate(userId string, issuer string) (*MfaProps, error)

func (*PushMfa) SetupVerify

func (mfa *PushMfa) SetupVerify(passCode string) error

func (*PushMfa) Verify

func (mfa *PushMfa) Verify(passCode string) error

type RadiusAccounting

type RadiusAccounting struct {
	Owner       string    `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string    `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime time.Time `json:"createdTime"`

	Username    string `xorm:"index" json:"username"`
	ServiceType int64  `json:"serviceType"` // e.g. LoginUser (1)

	NasId       string `json:"nasId"`       // String identifying the network access server originating the Access-Request.
	NasIpAddr   string `json:"nasIpAddr"`   // e.g. "192.168.0.10"
	NasPortId   string `json:"nasPortId"`   // Contains a text string which identifies the port of the NAS that is authenticating the user. e.g."eth.0"
	NasPortType int64  `json:"nasPortType"` // Indicates the type of physical port the network access server is using to authenticate the user. e.g.Ethernet(15)
	NasPort     int64  `json:"nasPort"`     // Indicates the physical port number of the network access server that is authenticating the user. e.g. 233

	FramedIpAddr    string `json:"framedIpAddr"`    // Indicates the IP address to be configured for the user by sending the IP address of a user to the RADIUS server.
	FramedIpNetmask string `json:"framedIpNetmask"` // Indicates the IP netmask to be configured for the user when the user is using a device on a network.

	AcctSessionId      string    `xorm:"index" json:"acctSessionId"`
	AcctSessionTime    int64     `json:"acctSessionTime"` // Indicates how long (in seconds) the user has received service.
	AcctInputTotal     int64     `json:"acctInputTotal"`
	AcctOutputTotal    int64     `json:"acctOutputTotal"`
	AcctInputPackets   int64     `json:"acctInputPackets"`   // Indicates how many packets have been received from the port over the course of this service being provided to a framed user.
	AcctOutputPackets  int64     `json:"acctOutputPackets"`  // Indicates how many packets have been sent to the port in the course of delivering this service to a framed user.
	AcctTerminateCause int64     `json:"acctTerminateCause"` // e.g. Lost-Carrier (2)
	LastUpdate         time.Time `json:"lastUpdate"`
	AcctStartTime      time.Time `xorm:"index" json:"acctStartTime"`
	AcctStopTime       time.Time `xorm:"index" json:"acctStopTime"`
}

https://www.cisco.com/c/en/us/td/docs/ios-xml/ios/sec_usr_radatt/configuration/xe-16/sec-usr-radatt-xe-16-book/sec-rad-ov-ietf-attr.html

func GetRadiusAccounting

func GetRadiusAccounting(id string) (*RadiusAccounting, error)

func GetRadiusAccountingBySessionId

func GetRadiusAccountingBySessionId(sessionId string) (*RadiusAccounting, error)

func (*RadiusAccounting) GetId

func (ra *RadiusAccounting) GetId() string

type RadiusMfa

type RadiusMfa struct {
	*MfaProps
	// contains filtered or unexported fields
}

func NewRadiusMfaUtil

func NewRadiusMfaUtil(config *MfaProps) *RadiusMfa

func (*RadiusMfa) Enable

func (mfa *RadiusMfa) Enable(user *User) error

func (*RadiusMfa) Initiate

func (mfa *RadiusMfa) Initiate(userId string, issuer string) (*MfaProps, error)

func (*RadiusMfa) SetupVerify

func (mfa *RadiusMfa) SetupVerify(passCode string) error

func (*RadiusMfa) Verify

func (mfa *RadiusMfa) Verify(passCode string) error

type Record

type Record struct {
	Id int `xorm:"int notnull pk autoincr" json:"id"`

	Owner       string `xorm:"varchar(100) index" json:"owner"`
	Name        string `xorm:"varchar(100) index" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	Organization string `xorm:"varchar(100)" json:"organization"`
	ClientIp     string `xorm:"varchar(100)" json:"clientIp"`
	User         string `xorm:"varchar(100)" json:"user"`
	Method       string `xorm:"varchar(100)" json:"method"`
	RequestUri   string `xorm:"varchar(1000)" json:"requestUri"`
	Action       string `xorm:"varchar(1000)" json:"action"`
	Language     string `xorm:"varchar(100)" json:"language"`

	Object     string `xorm:"mediumtext" json:"object"`
	Response   string `xorm:"mediumtext" json:"response"`
	StatusCode int    `json:"statusCode"`

	IsTriggered bool `json:"isTriggered"`
}

func CopyRecord

func CopyRecord(record *Record) *Record

func GetPaginationRecords

func GetPaginationRecords(offset, limit int, field, value, sortField, sortOrder string, filterRecord *Record) ([]*Record, error)

func GetRecords

func GetRecords() ([]*Record, error)

func GetRecordsByField

func GetRecordsByField(record *Record) ([]*Record, error)

func NewRecord

func NewRecord(ctx *context.Context) (*Record, error)

type Resource

type Resource struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(180) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	User        string `xorm:"varchar(100)" json:"user"`
	Provider    string `xorm:"varchar(100)" json:"provider"`
	Application string `xorm:"varchar(100)" json:"application"`
	Tag         string `xorm:"varchar(100)" json:"tag"`
	Parent      string `xorm:"varchar(100)" json:"parent"`
	FileName    string `xorm:"varchar(255)" json:"fileName"`
	FileType    string `xorm:"varchar(100)" json:"fileType"`
	FileFormat  string `xorm:"varchar(100)" json:"fileFormat"`
	FileSize    int    `json:"fileSize"`
	Url         string `xorm:"varchar(500)" json:"url"`
	Description string `xorm:"varchar(255)" json:"description"`
}

func GetDirectResources

func GetDirectResources(owner string, user string, provider *Provider, prefix string, lang string) ([]*Resource, error)

func GetPaginationResources

func GetPaginationResources(owner, user string, offset, limit int, field, value, sortField, sortOrder string) ([]*Resource, error)

func GetResource

func GetResource(id string) (*Resource, error)

func GetResources

func GetResources(owner string, user string) ([]*Resource, error)

func (*Resource) GetId

func (resource *Resource) GetId() string

type Response

type Response struct {
	Status string `json:"status"`
	Msg    string `json:"msg"`

	Data interface{} `json:"data"`
}

type RevokedToken

type RevokedToken struct {
	Id          int64  `xorm:"pk autoincr" json:"id"`
	TokenHash   string `xorm:"varchar(100) notnull unique index" json:"tokenHash"`
	TokenType   string `xorm:"varchar(20)" json:"tokenType"` // "access_token" or "refresh_token"
	RevokedAt   string `xorm:"varchar(100)" json:"revokedAt"`
	RevokedBy   string `xorm:"varchar(100)" json:"revokedBy"` // User who revoked the token
	ClientId    string `xorm:"varchar(100)" json:"clientId"`
	ExpiresAt   string `xorm:"varchar(100)" json:"expiresAt"` // Original token expiration for cleanup
	Owner       string `xorm:"varchar(100)" json:"owner"`
	Application string `xorm:"varchar(100)" json:"application"`
}

RevokedToken represents a revoked OAuth2 token (RFC 7009). Tokens are stored by their hash for security.

func GetRevokedTokens

func GetRevokedTokens(owner string, application string) ([]*RevokedToken, error)

GetRevokedTokens returns all revoked tokens for an application.

type Role

type Role struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
	DisplayName string `xorm:"varchar(100)" json:"displayName"`
	Description string `xorm:"varchar(100)" json:"description"`

	Users     []string `xorm:"mediumtext" json:"users"`
	Groups    []string `xorm:"mediumtext" json:"groups"`
	Roles     []string `xorm:"mediumtext" json:"roles"`
	Domains   []string `xorm:"mediumtext" json:"domains"`
	IsEnabled bool     `json:"isEnabled"`
}

func GetAncestorRoles

func GetAncestorRoles(roleIds ...string) ([]*Role, error)

GetAncestorRoles returns a list of roles that contain the given roleIds

func GetMaskedRoles

func GetMaskedRoles(roles []*Role) []*Role

func GetPaginationRoles

func GetPaginationRoles(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Role, error)

func GetRole

func GetRole(id string) (*Role, error)

func GetRoles

func GetRoles(owner string) ([]*Role, error)

func TeamRoleFor added in v1.31.26

func TeamRoleFor(org string, r teamrole.Role) *Role

TeamRoleFor builds (does not persist) the IAM Role row for a catalog role in an org. Pure: no DB, unit-testable. Role.Name is the exact catalog key so the guard, the client, and storage all speak one identifier.

func (*Role) GetId

func (role *Role) GetId() string

type Rule

type Rule struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100) notnull" json:"createdTime"`
	UpdatedTime string `xorm:"varchar(100) notnull" json:"updatedTime"`

	Type        string        `xorm:"varchar(100) notnull" json:"type"`
	Expressions []*Expression `xorm:"mediumtext" json:"expressions"`
	Action      string        `xorm:"varchar(100) notnull" json:"action"`
	StatusCode  int           `xorm:"int notnull" json:"statusCode"`
	Reason      string        `xorm:"varchar(100) notnull" json:"reason"`
	IsVerbose   bool          `xorm:"bool" json:"isVerbose"`
}

func GetGlobalRules

func GetGlobalRules() ([]*Rule, error)

func GetPaginationRules

func GetPaginationRules(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Rule, error)

func GetRule

func GetRule(id string) (*Rule, error)

func GetRules

func GetRules(owner string) ([]*Rule, error)

func GetRulesByRuleIds

func GetRulesByRuleIds(ids []string) ([]*Rule, error)

func (*Rule) GetId

func (rule *Rule) GetId() string

type SCIMAddress

type SCIMAddress struct {
	StreetAddress string `json:"streetAddress"`
	Locality      string `json:"locality"`
	Region        string `json:"region"`
	PostalCode    string `json:"postalCode"`
	Country       string `json:"country"`
	Formatted     string `json:"formatted"`
	Type          string `json:"type"`
	Primary       bool   `json:"primary"`
}

SCIMAddress represents a SCIM user address structure

type SCIMEmail

type SCIMEmail struct {
	Value   string `json:"value"`
	Type    string `json:"type"`
	Primary bool   `json:"primary"`
}

SCIMEmail represents a SCIM user email structure

type SCIMListResponse

type SCIMListResponse struct {
	TotalResults int         `json:"totalResults"`
	ItemsPerPage int         `json:"itemsPerPage"`
	StartIndex   int         `json:"startIndex"`
	Resources    []*SCIMUser `json:"Resources"`
}

SCIMListResponse represents a SCIM list response

type SCIMName

type SCIMName struct {
	FamilyName string `json:"familyName"`
	GivenName  string `json:"givenName"`
	Formatted  string `json:"formatted"`
}

SCIMName represents a SCIM user name structure

type SCIMPhoneNumber

type SCIMPhoneNumber struct {
	Value   string `json:"value"`
	Type    string `json:"type"`
	Primary bool   `json:"primary"`
}

SCIMPhoneNumber represents a SCIM user phone number structure

type SCIMSyncerProvider

type SCIMSyncerProvider struct {
	Syncer *Syncer
}

SCIMSyncerProvider implements SyncerProvider for SCIM 2.0 API-based syncers

func (*SCIMSyncerProvider) AddUser

func (p *SCIMSyncerProvider) AddUser(user *OriginalUser) (bool, error)

AddUser adds a new user to SCIM (not supported for read-only API)

func (*SCIMSyncerProvider) Close

func (p *SCIMSyncerProvider) Close() error

Close closes any open connections (no-op for SCIM API-based syncer)

func (*SCIMSyncerProvider) GetOriginalGroups

func (p *SCIMSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error)

GetOriginalGroups retrieves all groups from SCIM (not implemented yet)

func (*SCIMSyncerProvider) GetOriginalUserGroups

func (p *SCIMSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error)

GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)

func (*SCIMSyncerProvider) GetOriginalUsers

func (p *SCIMSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error)

GetOriginalUsers retrieves all users from SCIM API

func (*SCIMSyncerProvider) InitAdapter

func (p *SCIMSyncerProvider) InitAdapter() error

InitAdapter initializes the SCIM syncer (no database adapter needed)

func (*SCIMSyncerProvider) TestConnection

func (p *SCIMSyncerProvider) TestConnection() error

TestConnection tests the SCIM API connection

func (*SCIMSyncerProvider) UpdateUser

func (p *SCIMSyncerProvider) UpdateUser(user *OriginalUser) (bool, error)

UpdateUser updates an existing user in SCIM (not supported for read-only API)

type SCIMUser

type SCIMUser struct {
	ID           string            `json:"id"`
	ExternalID   string            `json:"externalId"`
	UserName     string            `json:"userName"`
	Name         SCIMName          `json:"name"`
	DisplayName  string            `json:"displayName"`
	NickName     string            `json:"nickName"`
	ProfileURL   string            `json:"profileUrl"`
	Title        string            `json:"title"`
	UserType     string            `json:"userType"`
	PreferredLan string            `json:"preferredLanguage"`
	Locale       string            `json:"locale"`
	Timezone     string            `json:"timezone"`
	Active       bool              `json:"active"`
	Emails       []SCIMEmail       `json:"emails"`
	PhoneNumbers []SCIMPhoneNumber `json:"phoneNumbers"`
	Addresses    []SCIMAddress     `json:"addresses"`
}

SCIMUser represents a SCIM 2.0 user resource

type SafeAdapter

type SafeAdapter struct {
	*authzstore.Adapter
	// contains filtered or unexported fields
}

SafeAdapter wraps an authzstore.Adapter and overrides RemovePolicy / RemovePolicies with versions that force-include the zero-valued V columns in the WHERE clause via MustCols. The base adapter already does this for single-row deletes; SafeAdapter exists because the authz library's bulk remove path used to call RemovePolicies, which the original xorm-adapter did NOT MustCols, leading to over-broad deletes in production. We keep the override here for parity with historical behavior.

func NewSafeAdapter

func NewSafeAdapter(a *Adapter) *SafeAdapter

func (*SafeAdapter) RemovePolicies

func (a *SafeAdapter) RemovePolicies(sec string, ptype string, rules [][]string) error

func (*SafeAdapter) RemovePolicy

func (a *SafeAdapter) RemovePolicy(sec string, ptype string, rule []string) error

type Saml11AssertionArtifact

type Saml11AssertionArtifact struct {
	XMLName  xml.Name `xml:"AssertionArtifact"`
	InnerXML string   `xml:",innerxml"`
}

type Saml11Request

type Saml11Request struct {
	XMLName           xml.Name `xml:"Request"`
	SAMLP             string   `xml:"samlp,attr"`
	MajorVersion      string   `xml:"MajorVersion,attr"`
	MinorVersion      string   `xml:"MinorVersion,attr"`
	RequestID         string   `xml:"RequestID,attr"`
	IssueInstant      string   `xml:"IssueInstance,attr"`
	AssertionArtifact Saml11AssertionArtifact
}

type SamlItem

type SamlItem struct {
	Name       string `json:"name"`
	NameFormat string `json:"nameFormat"`
	Value      string `json:"value"`
}

type ScopeDescription

type ScopeDescription struct {
	Scope       string `json:"scope"`
	DisplayName string `json:"displayName"`
	Description string `json:"description"`
}

ScopeDescription represents a human-readable description of an OAuth scope

type ScopeItem

type ScopeItem struct {
	Name        string   `json:"name"`
	DisplayName string   `json:"displayName"`
	Description string   `json:"description"`
	Tools       []string `json:"tools"` // MCP tools allowed by this scope
}

type Server

type Server struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
	UpdatedTime string `xorm:"varchar(100)" json:"updatedTime"`
	DisplayName string `xorm:"varchar(100)" json:"displayName"`

	Url         string  `xorm:"varchar(500)" json:"url"`
	Token       string  `xorm:"varchar(500)" json:"-"`
	Application string  `xorm:"varchar(100)" json:"application"`
	Tools       []*Tool `xorm:"mediumtext" json:"tools"`
}

func GetPaginationServers

func GetPaginationServers(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Server, error)

func GetServer

func GetServer(id string) (*Server, error)

func GetServers

func GetServers(owner string) ([]*Server, error)

func (*Server) GetId

func (server *Server) GetId() string

type Session

type Session struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	Application string `xorm:"varchar(100) notnull pk" json:"application"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	SessionId []string `json:"sessionId"`

	ExclusiveSignin bool `xorm:"-"`
}

func GetPaginationSessions

func GetPaginationSessions(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Session, error)

func GetSessions

func GetSessions(owner string) ([]*Session, error)

func GetSingleSession

func GetSingleSession(id string) (*Session, error)

func GetUserAppSessions

func GetUserAppSessions(owner string, name string, application string) ([]*Session, error)

func GetUserSessions

func GetUserSessions(owner string, name string) ([]*Session, error)

func (*Session) GetId

func (session *Session) GetId() string

type SigninItem

type SigninItem struct {
	Name        string `json:"name"`
	Visible     bool   `json:"visible"`
	Label       string `json:"label"`
	CustomCss   string `json:"customCss"`
	Placeholder string `json:"placeholder"`
	Rule        string `json:"rule"`
	IsCustom    bool   `json:"isCustom"`
}

type SigninMethod

type SigninMethod struct {
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	DisplayName string `xorm:"varchar(100)" json:"displayName"`
	Rule        string `json:"rule"`
}

type SignupItem

type SignupItem struct {
	Name        string   `json:"name"`
	Visible     bool     `json:"visible"`
	Required    bool     `json:"required"`
	Prompted    bool     `json:"prompted"`
	Type        string   `json:"type"`
	CustomCss   string   `json:"customCss"`
	Label       string   `json:"label"`
	Placeholder string   `json:"placeholder"`
	Options     []string `json:"options"`
	Regex       string   `json:"regex"`
	Rule        string   `json:"rule"`
}

type SingleSignOnService

type SingleSignOnService struct {
	// XMLName  xml.Name
	Binding  string `xml:"Binding,attr"`
	Location string `xml:"Location,attr"`
}

type Site

type Site struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
	UpdatedTime string `xorm:"varchar(100)" json:"updatedTime"`
	DisplayName string `xorm:"varchar(100)" json:"displayName"`

	Tag            string      `xorm:"varchar(100)" json:"tag"`
	Domain         string      `xorm:"varchar(100)" json:"domain"`
	OtherDomains   []string    `xorm:"varchar(500)" json:"otherDomains"`
	NeedRedirect   bool        `json:"needRedirect"`
	DisableVerbose bool        `json:"disableVerbose"`
	Rules          []string    `xorm:"varchar(500)" json:"rules"`
	EnableAlert    bool        `json:"enableAlert"`
	AlertInterval  int         `json:"alertInterval"`
	AlertTryTimes  int         `json:"alertTryTimes"`
	AlertProviders []string    `xorm:"varchar(500)" json:"alertProviders"`
	Challenges     []string    `xorm:"mediumtext" json:"challenges"`
	Host           string      `xorm:"varchar(100)" json:"host"`
	Port           int         `json:"port"`
	Hosts          []string    `xorm:"varchar(1000)" json:"hosts"`
	SslMode        string      `xorm:"varchar(100)" json:"sslMode"`
	SslCert        string      `xorm:"-" json:"sslCert"`
	PublicIp       string      `xorm:"varchar(100)" json:"publicIp"`
	Node           string      `xorm:"varchar(100)" json:"node"`
	IsSelf         bool        `json:"isSelf"`
	Status         string      `xorm:"varchar(100)" json:"status"`
	Nodes          []*NodeItem `xorm:"mediumtext" json:"nodes"`

	IamApplication string       `xorm:"varchar(100)" json:"iamApplication"`
	ApplicationObj *Application `xorm:"-" json:"applicationObj"`
}

func GetGlobalSites

func GetGlobalSites() ([]*Site, error)

func GetMaskedSite

func GetMaskedSite(site *Site, node string) *Site

func GetMaskedSites

func GetMaskedSites(sites []*Site, node string) []*Site

func GetPaginationSites

func GetPaginationSites(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Site, error)

func GetSite

func GetSite(id string) (*Site, error)

func GetSiteByDomain

func GetSiteByDomain(domain string) *Site

func GetSites

func GetSites(owner string) ([]*Site, error)

func (*Site) GetChallengeMap

func (site *Site) GetChallengeMap() map[string]string

func (*Site) GetHost

func (site *Site) GetHost() string

func (*Site) GetId

func (site *Site) GetId() string

type SmsMfa

type SmsMfa struct {
	*MfaProps
}

func NewEmailMfaUtil

func NewEmailMfaUtil(config *MfaProps) *SmsMfa

func NewSmsMfaUtil

func NewSmsMfaUtil(config *MfaProps) *SmsMfa

func (*SmsMfa) Enable

func (mfa *SmsMfa) Enable(user *User) error

func (*SmsMfa) Initiate

func (mfa *SmsMfa) Initiate(userId string, issuer string) (*MfaProps, error)

func (*SmsMfa) SetupVerify

func (mfa *SmsMfa) SetupVerify(passCode string) error

func (*SmsMfa) Verify

func (mfa *SmsMfa) Verify(passCode string) error

type SsoLogoutNotification

type SsoLogoutNotification struct {
	// User information
	Owner       string `json:"owner"`
	Name        string `json:"name"`
	DisplayName string `json:"displayName"`
	Email       string `json:"email"`
	Phone       string `json:"phone"`
	Id          string `json:"id"`

	// Event type
	Event string `json:"event"`

	// Session-level information for targeted logout
	SessionIds        []string `json:"sessionIds"`        // List of session IDs being logged out
	AccessTokenHashes []string `json:"accessTokenHashes"` // Hashes of access tokens being expired

	// Authentication fields to prevent malicious logout requests
	Nonce     string `json:"nonce"`     // Random nonce for replay protection
	Timestamp int64  `json:"timestamp"` // Unix timestamp of the notification
	Signature string `json:"signature"` // HMAC-SHA256 signature for verification
}

SsoLogoutNotification represents the structure of a session-level SSO logout notification This includes session information and a signature for authentication

type Syncer

type Syncer struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	Organization string `xorm:"varchar(100)" json:"organization"`
	Type         string `xorm:"varchar(100)" json:"type"`
	DatabaseType string `xorm:"varchar(100)" json:"databaseType"`
	SslMode      string `xorm:"varchar(100)" json:"sslMode"`
	SshType      string `xorm:"varchar(100)" json:"sshType"`

	Host             string         `xorm:"varchar(100)" json:"host"`
	Port             int            `json:"port"`
	User             string         `xorm:"varchar(100)" json:"user"`
	Password         string         `xorm:"varchar(150)" json:"password"`
	SshHost          string         `xorm:"varchar(100)" json:"sshHost"`
	SshPort          int            `json:"sshPort"`
	SshUser          string         `xorm:"varchar(100)" json:"sshUser"`
	SshPassword      string         `xorm:"varchar(150)" json:"sshPassword"`
	Cert             string         `xorm:"varchar(100)" json:"cert"`
	Database         string         `xorm:"varchar(100)" json:"database"`
	Table            string         `xorm:"varchar(100)" json:"table"`
	TableColumns     []*TableColumn `xorm:"mediumtext" json:"tableColumns"`
	AffiliationTable string         `xorm:"varchar(100)" json:"affiliationTable"`
	AvatarBaseUrl    string         `xorm:"varchar(100)" json:"avatarBaseUrl"`
	ErrorText        string         `xorm:"mediumtext" json:"errorText"`
	SyncInterval     int            `json:"syncInterval"`
	IsReadOnly       bool           `json:"isReadOnly"`
	IsEnabled        bool           `json:"isEnabled"`

	Ormer     *Ormer      `xorm:"-" json:"-"`
	SshClient *ssh.Client `xorm:"-" json:"-"`
}

func GetMaskedSyncer

func GetMaskedSyncer(syncer *Syncer, errs ...error) (*Syncer, error)

func GetMaskedSyncers

func GetMaskedSyncers(syncers []*Syncer, errs ...error) ([]*Syncer, error)

func GetOrganizationSyncers

func GetOrganizationSyncers(owner, organization string) ([]*Syncer, error)

func GetPaginationSyncers

func GetPaginationSyncers(owner, organization string, offset, limit int, field, value, sortField, sortOrder string) ([]*Syncer, error)

func GetSyncer

func GetSyncer(id string) (*Syncer, error)

func GetSyncers

func GetSyncers(owner string) ([]*Syncer, error)

func (*Syncer) Close

func (syncer *Syncer) Close() error

func (*Syncer) GetId

func (syncer *Syncer) GetId() string

type SyncerProvider

type SyncerProvider interface {
	// InitAdapter initializes the connection to the external system
	InitAdapter() error

	// GetOriginalUsers retrieves all users from the external system
	GetOriginalUsers() ([]*OriginalUser, error)

	// GetOriginalGroups retrieves all groups from the external system
	GetOriginalGroups() ([]*OriginalGroup, error)

	// GetOriginalUserGroups retrieves the group IDs that a user belongs to
	GetOriginalUserGroups(userId string) ([]string, error)

	// AddUser adds a new user to the external system
	AddUser(user *OriginalUser) (bool, error)

	// UpdateUser updates an existing user in the external system
	UpdateUser(user *OriginalUser) (bool, error)

	// TestConnection tests the connection to the external system
	TestConnection() error

	// Close closes any open connections and releases resources
	Close() error
}

SyncerProvider defines the interface that all syncer implementations must satisfy. Different syncer types (Database, Keycloak, WeCom, Azure AD) implement this interface.

func GetSyncerProvider

func GetSyncerProvider(syncer *Syncer) SyncerProvider

GetSyncerProvider returns the appropriate SyncerProvider implementation based on syncer type

type TableColumn

type TableColumn struct {
	Name     string   `json:"name"`
	Type     string   `json:"type"`
	IamName  string   `json:"iamName"`
	IsKey    bool     `json:"isKey"`
	IsHashed bool     `json:"isHashed"`
	Values   []string `json:"values"`
}

type ThemeData

type ThemeData struct {
	ThemeType    string `xorm:"varchar(30)" json:"themeType"`
	ColorPrimary string `xorm:"varchar(10)" json:"colorPrimary"`
	BorderRadius int    `xorm:"int" json:"borderRadius"`
	IsCompact    bool   `xorm:"bool" json:"isCompact"`
	IsEnabled    bool   `xorm:"bool" json:"isEnabled"`
}

type Ticket

type Ticket struct {
	Owner       string           `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string           `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string           `xorm:"varchar(100)" json:"createdTime"`
	UpdatedTime string           `xorm:"varchar(100)" json:"updatedTime"`
	DisplayName string           `xorm:"varchar(100)" json:"displayName"`
	User        string           `xorm:"varchar(100) index" json:"user"`
	Title       string           `xorm:"varchar(200)" json:"title"`
	Content     string           `xorm:"mediumtext" json:"content"`
	State       string           `xorm:"varchar(50)" json:"state"`
	Messages    []*TicketMessage `xorm:"mediumtext json" json:"messages"`
}

func GetPaginationTickets

func GetPaginationTickets(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Ticket, error)

func GetTicket

func GetTicket(id string) (*Ticket, error)

func GetTickets

func GetTickets(owner string) ([]*Ticket, error)

func GetUserTickets

func GetUserTickets(owner, user string) ([]*Ticket, error)

func (*Ticket) GetId

func (ticket *Ticket) GetId() string

type TicketMessage

type TicketMessage struct {
	Author    string `json:"author"`
	Text      string `json:"text"`
	Timestamp string `json:"timestamp"`
	IsAdmin   bool   `json:"isAdmin"`
}

type Token

type Token struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	Application  string `xorm:"varchar(100)" json:"application"`
	Organization string `xorm:"varchar(100)" json:"organization"`
	User         string `xorm:"varchar(100)" json:"user"`

	Code                string `xorm:"varchar(100) index" json:"code"`
	AccessToken         string `xorm:"mediumtext" json:"accessToken"`
	RefreshToken        string `xorm:"mediumtext" json:"refreshToken"`
	AccessTokenHash     string `xorm:"varchar(100) index" json:"accessTokenHash"`
	RefreshTokenHash    string `xorm:"varchar(100) index" json:"refreshTokenHash"`
	ExpiresIn           int    `json:"expiresIn"`
	Scope               string `xorm:"varchar(100)" json:"scope"`
	TokenType           string `xorm:"varchar(100)" json:"tokenType"`
	CodeChallenge       string `xorm:"varchar(100)" json:"codeChallenge"`
	CodeChallengeMethod string `xorm:"varchar(10)" json:"codeChallengeMethod"`
	CodeIsUsed          bool   `json:"codeIsUsed"`
	CodeExpireIn        int64  `json:"codeExpireIn"`
	Resource            string `xorm:"varchar(255)" json:"resource"` // RFC 8707 Resource Indicator
}

func GetPaginationTokens

func GetPaginationTokens(owner, organization string, offset, limit int, field, value, sortField, sortOrder string) ([]*Token, error)

func GetToken

func GetToken(id string) (*Token, error)

func GetTokenByAccessToken

func GetTokenByAccessToken(accessToken string) (*Token, error)

func GetTokenByRefreshToken

func GetTokenByRefreshToken(refreshToken string) (*Token, error)

func GetTokenByTokenValue

func GetTokenByTokenValue(tokenValue, tokenTypeHint string) (*Token, error)

func GetTokenByUser

func GetTokenByUser(application *Application, user *User, scope string, nonce string, host string) (*Token, error)

GetTokenByUser Implicit flow

func GetTokens

func GetTokens(owner string, organization string) ([]*Token, error)

func GetTokensByUser

func GetTokensByUser(owner, username string) ([]*Token, error)

GetTokensByUser retrieves all tokens for a specific user

func GetUserTokenForAudience added in v1.28.2

func GetUserTokenForAudience(application *Application, user *User, audience string, scope string, host string) (*Token, error)

GetUserTokenForAudience mints a short-lived, user-bound JWT for an EXPLICIT audience. It is the server-side primitive a confidential, trusted client (e.g. hanzo-console) uses to obtain a token it forwards to a resource server (e.g. commerce) that derives the user's org from the verified `owner` claim — the SSR analogue of a browser holding its own IAM token.

It is identical to GetTokenByUser except the audience is set explicitly via the RFC 8707 `resource` claim instead of defaulting to the minting application's clientId. This decouples the token's audience from WHICH app minted it, so the resource server's fixed audience allowlist (commerce IAM_ACCEPTED_AUDIENCES) matches deterministically. An empty `audience` falls back to the default (clientId / shared-org) audience, so callers that don't care get GetTokenByUser's behavior.

The token carries the user's real `owner` (org) claim, so the resource server scopes strictly to THAT org — there is no cross-tenant widening here: the audience only names the trusted client, never the billed subject.

func (*Token) GetId

func (token *Token) GetId() string

type TokenError

type TokenError struct {
	Error            string `json:"error"`
	ErrorDescription string `json:"error_description,omitempty"`
}

type TokenWrapper

type TokenWrapper struct {
	AccessToken  string `json:"access_token"`
	IdToken      string `json:"id_token"`
	RefreshToken string `json:"refresh_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	Scope        string `json:"scope"`
}

type Tool

type Tool struct {
	mcpsdk.Tool
	IsAllowed bool `json:"isAllowed"`
}

type TotpMfa

type TotpMfa struct {
	*MfaProps
	// contains filtered or unexported fields
}

func NewTotpMfaUtil

func NewTotpMfaUtil(config *MfaProps) *TotpMfa

func (*TotpMfa) Enable

func (mfa *TotpMfa) Enable(user *User) error

func (*TotpMfa) Initiate

func (mfa *TotpMfa) Initiate(userId string, issuer string) (*MfaProps, error)

func (*TotpMfa) SetupVerify

func (mfa *TotpMfa) SetupVerify(passcode string) error

func (*TotpMfa) Verify

func (mfa *TotpMfa) Verify(passcode string) error

type User

type User struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(255) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100) index" json:"createdTime"`
	UpdatedTime string `xorm:"varchar(100)" json:"updatedTime"`
	DeletedTime string `xorm:"varchar(100)" json:"deletedTime"`

	Id              string     `xorm:"varchar(100) index" json:"id"`
	ExternalId      string     `xorm:"varchar(100) index" json:"externalId"`
	Type            string     `xorm:"varchar(100)" json:"type"`
	Password        string     `xorm:"varchar(150)" json:"password"`
	PasswordSalt    string     `xorm:"varchar(100)" json:"passwordSalt"`
	PasswordType    string     `xorm:"varchar(100)" json:"passwordType"`
	DisplayName     string     `xorm:"varchar(100)" json:"displayName"`
	FirstName       string     `xorm:"varchar(100)" json:"firstName"`
	LastName        string     `xorm:"varchar(100)" json:"lastName"`
	Avatar          string     `xorm:"text" json:"avatar"`
	AvatarType      string     `xorm:"varchar(100)" json:"avatarType"`
	PermanentAvatar string     `xorm:"varchar(500)" json:"permanentAvatar"`
	Email           string     `xorm:"varchar(100) index" json:"email"`
	EmailVerified   bool       `json:"emailVerified"`
	Phone           string     `xorm:"varchar(100) index" json:"phone"`
	CountryCode     string     `xorm:"varchar(6)" json:"countryCode"`
	Region          string     `xorm:"varchar(100)" json:"region"`
	Location        string     `xorm:"varchar(100)" json:"location"`
	Address         []string   `json:"address"`
	Addresses       []*Address `xorm:"addresses blob" json:"addresses"`
	Affiliation     string     `xorm:"varchar(100)" json:"affiliation"`
	Title           string     `xorm:"varchar(100)" json:"title"`
	IdCardType      string     `xorm:"varchar(100)" json:"idCardType"`
	IdCard          string     `xorm:"varchar(100) index" json:"idCard"`
	RealName        string     `xorm:"varchar(100)" json:"realName"`
	IsVerified      bool       `json:"isVerified"`
	Homepage        string     `xorm:"varchar(100)" json:"homepage"`
	Bio             string     `xorm:"varchar(100)" json:"bio"`
	Tag             string     `xorm:"varchar(100)" json:"tag"`
	Language        string     `xorm:"varchar(100)" json:"language"`
	Gender          string     `xorm:"varchar(100)" json:"gender"`
	Birthday        string     `xorm:"varchar(100)" json:"birthday"`
	Education       string     `xorm:"varchar(100)" json:"education"`
	Score           int        `json:"score"`
	Karma           int        `json:"karma"`
	Ranking         int        `json:"ranking"`
	// DEPRECATED: Balance is managed by Commerce (billing.hanzo.ai). Do not write to these fields.
	Balance           float64 `json:"balance"`
	BalanceCredit     float64 `json:"balanceCredit"`
	Currency          string  `xorm:"varchar(100)" json:"currency"`
	BalanceCurrency   string  `xorm:"varchar(100)" json:"balanceCurrency"`
	IsDefaultAvatar   bool    `xorm:"bool default false" json:"isDefaultAvatar"`
	IsOnline          bool    `xorm:"bool default false" json:"isOnline"`
	IsAdmin           bool    `xorm:"bool default false" json:"isAdmin"`
	IsForbidden       bool    `xorm:"bool default false" json:"isForbidden"`
	IsDeleted         bool    `xorm:"bool default false" json:"isDeleted"`
	SignupApplication string  `xorm:"varchar(100)" json:"signupApplication"`
	Hash              string  `xorm:"varchar(100)" json:"hash"`
	PreHash           string  `xorm:"varchar(100)" json:"preHash"`
	RegisterType      string  `xorm:"varchar(100)" json:"registerType"`
	RegisterSource    string  `xorm:"varchar(100)" json:"registerSource"`
	AccessKey         string  `xorm:"varchar(100)" json:"accessKey"`
	AccessSecret      string  `xorm:"varchar(100)" json:"accessSecret"`
	// AccessSecretHash holds the argon2id hash of a service-account's API
	// secret. Service accounts (Type=="service-account") authenticate ONLY by
	// an API key and MUST NOT store the secret in plaintext, so their secret is
	// hashed here and the plaintext AccessSecret column is left empty. json:"-"
	// guarantees the hash never serializes through ANY response path (masked or
	// not) — it is verify-only material. Legacy hk- user keys (which predate
	// this) keep using the plaintext AccessSecret column; see
	// VerifyUserAccessSecret for the single verification choke point.
	AccessSecretHash     string `xorm:"varchar(150)" json:"-"`
	AccessToken          string `xorm:"mediumtext" json:"accessToken"`
	OriginalToken        string `xorm:"mediumtext" json:"originalToken"`
	OriginalRefreshToken string `xorm:"mediumtext" json:"originalRefreshToken"`

	CreatedIp      string `xorm:"varchar(100)" json:"createdIp"`
	LastSigninTime string `xorm:"varchar(100)" json:"lastSigninTime"`
	LastSigninIp   string `xorm:"varchar(100)" json:"lastSigninIp"`

	GitHub          string `xorm:"github varchar(100)" json:"github"`
	Google          string `xorm:"varchar(100)" json:"google"`
	QQ              string `xorm:"qq varchar(100)" json:"qq"`
	WeChat          string `xorm:"wechat varchar(100)" json:"wechat"`
	Facebook        string `xorm:"facebook varchar(100)" json:"facebook"`
	DingTalk        string `xorm:"dingtalk varchar(100)" json:"dingtalk"`
	Weibo           string `xorm:"weibo varchar(100)" json:"weibo"`
	Gitee           string `xorm:"gitee varchar(100)" json:"gitee"`
	LinkedIn        string `xorm:"linkedin varchar(100)" json:"linkedin"`
	Wecom           string `xorm:"wecom varchar(100)" json:"wecom"`
	Lark            string `xorm:"lark varchar(100)" json:"lark"`
	GitLab          string `xorm:"gitlab varchar(100)" json:"gitlab"`
	Adfs            string `xorm:"adfs varchar(100)" json:"adfs"`
	Baidu           string `xorm:"baidu varchar(100)" json:"baidu"`
	Alipay          string `xorm:"alipay varchar(100)" json:"alipay"`
	Iam             string `xorm:"iam varchar(100)" json:"iam"`
	Infoflow        string `xorm:"infoflow varchar(100)" json:"infoflow"`
	Apple           string `xorm:"apple varchar(100)" json:"apple"`
	AzureAD         string `xorm:"azuread varchar(100)" json:"azuread"`
	AzureADB2c      string `xorm:"azureadb2c varchar(100)" json:"azureadb2c"`
	Slack           string `xorm:"slack varchar(100)" json:"slack"`
	Steam           string `xorm:"steam varchar(100)" json:"steam"`
	Bilibili        string `xorm:"bilibili varchar(100)" json:"bilibili"`
	Okta            string `xorm:"okta varchar(100)" json:"okta"`
	Douyin          string `xorm:"douyin varchar(100)" json:"douyin"`
	Kwai            string `xorm:"kwai varchar(100)" json:"kwai"`
	Line            string `xorm:"line varchar(100)" json:"line"`
	Amazon          string `xorm:"amazon varchar(100)" json:"amazon"`
	Auth0           string `xorm:"auth0 varchar(100)" json:"auth0"`
	BattleNet       string `xorm:"battlenet varchar(100)" json:"battlenet"`
	Bitbucket       string `xorm:"bitbucket varchar(100)" json:"bitbucket"`
	Box             string `xorm:"box varchar(100)" json:"box"`
	CloudFoundry    string `xorm:"cloudfoundry varchar(100)" json:"cloudfoundry"`
	Dailymotion     string `xorm:"dailymotion varchar(100)" json:"dailymotion"`
	Deezer          string `xorm:"deezer varchar(100)" json:"deezer"`
	DigitalOcean    string `xorm:"digitalocean varchar(100)" json:"digitalocean"`
	Discord         string `xorm:"discord varchar(100)" json:"discord"`
	Dropbox         string `xorm:"dropbox varchar(100)" json:"dropbox"`
	EveOnline       string `xorm:"eveonline varchar(100)" json:"eveonline"`
	Fitbit          string `xorm:"fitbit varchar(100)" json:"fitbit"`
	Gitea           string `xorm:"gitea varchar(100)" json:"gitea"`
	Heroku          string `xorm:"heroku varchar(100)" json:"heroku"`
	InfluxCloud     string `xorm:"influxcloud varchar(100)" json:"influxcloud"`
	Instagram       string `xorm:"instagram varchar(100)" json:"instagram"`
	Intercom        string `xorm:"intercom varchar(100)" json:"intercom"`
	Kakao           string `xorm:"kakao varchar(100)" json:"kakao"`
	Lastfm          string `xorm:"lastfm varchar(100)" json:"lastfm"`
	Mailru          string `xorm:"mailru varchar(100)" json:"mailru"`
	Meetup          string `xorm:"meetup varchar(100)" json:"meetup"`
	MicrosoftOnline string `xorm:"microsoftonline varchar(100)" json:"microsoftonline"`
	Naver           string `xorm:"naver varchar(100)" json:"naver"`
	Nextcloud       string `xorm:"nextcloud varchar(100)" json:"nextcloud"`
	OneDrive        string `xorm:"onedrive varchar(100)" json:"onedrive"`
	Oura            string `xorm:"oura varchar(100)" json:"oura"`
	Patreon         string `xorm:"patreon varchar(100)" json:"patreon"`
	Paypal          string `xorm:"paypal varchar(100)" json:"paypal"`
	SalesForce      string `xorm:"salesforce varchar(100)" json:"salesforce"`
	Shopify         string `xorm:"shopify varchar(100)" json:"shopify"`
	Soundcloud      string `xorm:"soundcloud varchar(100)" json:"soundcloud"`
	Spotify         string `xorm:"spotify varchar(100)" json:"spotify"`
	Strava          string `xorm:"strava varchar(100)" json:"strava"`
	Stripe          string `xorm:"stripe varchar(100)" json:"stripe"`
	Telegram        string `xorm:"telegram varchar(100)" json:"telegram"`
	TikTok          string `xorm:"tiktok varchar(100)" json:"tiktok"`
	Tumblr          string `xorm:"tumblr varchar(100)" json:"tumblr"`
	Twitch          string `xorm:"twitch varchar(100)" json:"twitch"`
	Twitter         string `xorm:"twitter varchar(100)" json:"twitter"`
	Typetalk        string `xorm:"typetalk varchar(100)" json:"typetalk"`
	Uber            string `xorm:"uber varchar(100)" json:"uber"`
	VK              string `xorm:"vk varchar(100)" json:"vk"`
	Wepay           string `xorm:"wepay varchar(100)" json:"wepay"`
	Xero            string `xorm:"xero varchar(100)" json:"xero"`
	Yahoo           string `xorm:"yahoo varchar(100)" json:"yahoo"`
	Yammer          string `xorm:"yammer varchar(100)" json:"yammer"`
	Yandex          string `xorm:"yandex varchar(100)" json:"yandex"`
	Zoom            string `xorm:"zoom varchar(100)" json:"zoom"`
	Custom          string `xorm:"custom varchar(100)" json:"custom"`
	Custom2         string `xorm:"custom2 text" json:"custom2"`
	Custom3         string `xorm:"custom3 text" json:"custom3"`
	Custom4         string `xorm:"custom4 text" json:"custom4"`
	Custom5         string `xorm:"custom5 text" json:"custom5"`
	Custom6         string `xorm:"custom6 text" json:"custom6"`
	Custom7         string `xorm:"custom7 text" json:"custom7"`
	Custom8         string `xorm:"custom8 text" json:"custom8"`
	Custom9         string `xorm:"custom9 text" json:"custom9"`
	Custom10        string `xorm:"custom10 text" json:"custom10"`

	WebauthnCredentials []webauthn.Credential `xorm:"webauthnCredentials blob" json:"webauthnCredentials"`
	PreferredMfaType    string                `xorm:"varchar(100)" json:"preferredMfaType"`
	RecoveryCodes       []string              `xorm:"mediumtext" json:"recoveryCodes"`
	TotpSecret          string                `xorm:"varchar(100)" json:"totpSecret"`
	VerificationCode    string                `xorm:"varchar(20)" json:"verificationCode"` // Per-user pinned OTP (test/sandbox users)
	MfaPhoneEnabled     bool                  `json:"mfaPhoneEnabled"`
	MfaEmailEnabled     bool                  `json:"mfaEmailEnabled"`
	MfaRadiusEnabled    bool                  `json:"mfaRadiusEnabled"`
	MfaRadiusUsername   string                `xorm:"varchar(100)" json:"mfaRadiusUsername"`
	MfaRadiusProvider   string                `xorm:"varchar(100)" json:"mfaRadiusProvider"`
	MfaPushEnabled      bool                  `json:"mfaPushEnabled"`
	MfaPushReceiver     string                `xorm:"varchar(100)" json:"mfaPushReceiver"`
	MfaPushProvider     string                `xorm:"varchar(100)" json:"mfaPushProvider"`
	MultiFactorAuths    []*MfaProps           `xorm:"-" json:"multiFactorAuths,omitempty"`
	Invitation          string                `xorm:"varchar(100) index" json:"invitation"`
	InvitationCode      string                `xorm:"varchar(100) index" json:"invitationCode"`
	FaceIds             []*FaceId             `json:"faceIds"`
	Cart                []ProductInfo         `xorm:"mediumtext" json:"cart"`

	Ldap       string            `xorm:"ldap varchar(100)" json:"ldap"`
	Properties map[string]string `json:"properties"`

	Roles       []*Role       `json:"roles"`
	Permissions []*Permission `json:"permissions"`
	Groups      []string      `xorm:"mediumtext" json:"groups"`

	LastChangePasswordTime string `xorm:"varchar(100)" json:"lastChangePasswordTime"`
	LastSigninWrongTime    string `xorm:"varchar(100)" json:"lastSigninWrongTime"`
	SigninWrongTimes       int    `json:"signinWrongTimes"`

	ManagedAccounts     []ManagedAccount `xorm:"managedAccounts blob" json:"managedAccounts"`
	MfaAccounts         []MfaAccount     `xorm:"mfaAccounts blob" json:"mfaAccounts"`
	MfaItems            []*MfaItem       `xorm:"mediumtext" json:"mfaItems"`
	MfaRememberDeadline string           `xorm:"varchar(100)" json:"mfaRememberDeadline"`
	NeedUpdatePassword  bool             `json:"needUpdatePassword"`
	IpWhitelist         string           `xorm:"varchar(200)" json:"ipWhitelist"`
	ApplicationScopes   []ConsentRecord  `xorm:"mediumtext" json:"applicationScopes"`
}

func CheckUserPassword

func CheckUserPassword(organization string, username string, password string, lang string, options ...bool) (*User, error)

func CreateServiceAccount added in v1.31.1

func CreateServiceAccount(org, name, agentRef string, isAdmin bool) (*User, string, string, error)

CreateServiceAccount provisions a service account in org and mints its first API key. It returns the created principal and the raw access key + secret, which are shown to the caller EXACTLY ONCE — only the argon2id hash of the secret is persisted.

  • org: the owning organization; the SA is org-scoped, so every token minted from its key carries owner==org and downstream services attribute actions to <org>/<name>.
  • name: the canonical <org>-<agent> handle (validated).
  • agentRef: optional back-reference to the agent record this SA embodies (e.g. an agents.hanzo.ai agent id); stored on the User.Tag for correlation. Empty is fine.

isAdmin controls the privileged-column write path in UpdateUser (the key mint), mirroring AddUserKeys — a non-admin self-mint and an admin/console mint both work.

func ExtendManagedAccountsWithUser

func ExtendManagedAccountsWithUser(user *User) (*User, error)

func GetFilteredUser

func GetFilteredUser(user *User, isAdmin bool, isAdminOrSelf bool, accountItems []*AccountItem) (*User, error)

func GetGlobalUsers

func GetGlobalUsers() ([]*User, error)

func GetGlobalUsersWithFilter

func GetGlobalUsersWithFilter(cond builder.Cond) ([]*User, error)

func GetGroupUsers

func GetGroupUsers(groupId string) ([]*User, error)

func GetGroupUsersWithoutError

func GetGroupUsersWithoutError(groupId string) []*User

func GetMaskedUser

func GetMaskedUser(user *User, isAdminOrSelf bool, errs ...error) (*User, error)

func GetMaskedUsers

func GetMaskedUsers(users []*User, errs ...error) ([]*User, error)

func GetPaginationGlobalUsers

func GetPaginationGlobalUsers(offset, limit int, field, value, sortField, sortOrder string) ([]*User, error)

func GetPaginationGroupUsers

func GetPaginationGroupUsers(groupId string, offset, limit int, field, value, sortField, sortOrder string) ([]*User, error)

func GetPaginationUsers

func GetPaginationUsers(owner string, offset, limit int, field, value, sortField, sortOrder string, groupName string) ([]*User, error)

func GetServiceAccount added in v1.31.1

func GetServiceAccount(org, name string) (*User, error)

GetServiceAccount loads a single service account by <org>/<name>, or (nil,nil) if no such principal exists or the row is not a service account.

func GetSortedUsers

func GetSortedUsers(owner string, sorter string, limit int) ([]*User, error)

func GetUser

func GetUser(id string) (*User, error)

func GetUserByAccessKey

func GetUserByAccessKey(accessKey string) (*User, error)

func GetUserByEmail

func GetUserByEmail(owner string, email string) (*User, error)

func GetUserByEmailOnly

func GetUserByEmailOnly(email string) (*User, error)

func GetUserByField

func GetUserByField(organizationName string, field string, value string) (*User, error)

func GetUserByFields

func GetUserByFields(organization string, field string) (*User, error)

func GetUserByInvitationCode

func GetUserByInvitationCode(owner string, invitationCode string) (*User, error)

func GetUserByKerberosName

func GetUserByKerberosName(organizationName string, kerberosUsername string) (*User, error)

GetUserByKerberosName looks up a user by their Kerberos principal name. It strips the realm part (e.g., "user@REALM.COM" -> "user") and searches by username.

func GetUserByPhone

func GetUserByPhone(owner string, phone string) (*User, error)

GetUserByPhone looks up a user by phone within an organization.

Phone normalization: `phone` is normalized to E.164 before the query. The caller MAY pass either a raw national number plus a separate country code via GetUserByPhoneWithCountry, or a phone string that already carries a '+' prefix. Inputs that cannot be normalized fall back to a verbatim query so legacy callers that already passed E.164 continue to work; the stored row is authoritative E.164 after the one-shot migration in object.MigratePhoneToE164.

func GetUserByPhoneOnly

func GetUserByPhoneOnly(phone string) (*User, error)

GetUserByPhoneOnly is the cross-org variant used by the OTP verification path. Same normalization invariant as GetUserByPhone.

func GetUserByPhoneWithCountry added in v1.18.7

func GetUserByPhoneWithCountry(owner string, phone string, countryCode string) (*User, error)

GetUserByPhoneWithCountry is the canonical phone lookup: normalizes (phone, countryCode) to E.164 and queries `User.Phone` exactly. No fallback to national-number matching — that is the collision path that orphaned orders before this change. If the input cannot be parsed, returns (nil, nil) — a non-normalizable phone never matches a stored E.164 row.

func GetUserByUserId

func GetUserByUserId(owner string, userId string) (*User, error)

func GetUserByUserIdOnly

func GetUserByUserIdOnly(userId string) (*User, error)

func GetUserByWebauthID

func GetUserByWebauthID(webauthId string) (*User, error)

func GetUserForLogin added in v1.31.24

func GetUserForLogin(appOrg string, field string) (*User, error)

GetUserForLogin resolves the login user for an application whose organization is appOrg, allowing the user to live in a DESCENDANT tenant of appOrg.

Signup now puts each founder in their own org (so commerce, which namespaces by org, bills THEM and not the parent), while the client application they authenticate against still belongs to the parent — the platform (or a white-label reseller). Login therefore has to look one way DOWN the tenancy chain:

exact match in appOrg          → the fast path, unchanged behaviour
unique match in a descendant   → the founder in their own tenant
several descendant matches     → refuse (ambiguous identity is never resolved)

It only ever accepts a user the app's org is an ANCESTOR of, so a tenant client can never authenticate a user from an unrelated org (or from its own parent).

func GetUserNoCheck

func GetUserNoCheck(id string) (*User, error)

func GetUsers

func GetUsers(owner string) ([]*User, error)

func GetUsersByFieldCrossOrg added in v1.25.4

func GetUsersByFieldCrossOrg(field string, value string) ([]*User, error)

GetUsersByFieldCrossOrg returns ALL users matching field=value across every organization — the global engine plus each per-org SQLite under orgIsolation=sqlite. The auth layer needs the full colliding set so it can select the row whose password verifies (and so it can skip the global-admin row for tenant logins). Deduplicated by (owner, name).

func GetUsersByTagWithFilter

func GetUsersByTagWithFilter(owner string, tag string, cond builder.Cond) ([]*User, error)

func GetUsersWithFilter

func GetUsersWithFilter(owner string, cond builder.Cond) ([]*User, error)

func ListServiceAccounts added in v1.31.1

func ListServiceAccounts(org string) ([]*User, error)

ListServiceAccounts returns the service accounts in org, with ALL credential material stripped (access key/secret masked; the hash never serializes). It is the read surface — names + metadata only, never secrets.

func NewAdminUser added in v1.14.21

func NewAdminUser() *User

NewAdminUser returns the bootstrap admin user placeholder.

func VerifyWalletLogin added in v1.22.1

func VerifyWalletLogin(in WalletLoginInput) (*User, error)

VerifyWalletLogin is the one server-side entry point for multi-chain wallet login. Fail closed at every step:

  1. Parse the SIGNED CAIP-122 message; read the nonce from it (not the body), so a forged body can't desync nonce from signature.
  2. Atomically BURN the nonce BEFORE crypto -- a captured proof can never be replayed even if verification would otherwise succeed.
  3. walletconnect.VerifyProof: address-binding + domain + nonce + time + the per-chain cryptographic check. Identity = res.Address (canonical), never the client-claimed address.
  4. Resolve (chain,verifiedAddress) -> WalletLink -> user: - existing link -> log that user in - no link + session user -> link the new wallet to the session identity - no link + signup allowed -> provision "<chain>_<address>" user + link - no link + login-only -> error (no account linked to this wallet)

Returns the resolved user; the caller mints the session/JWT via HandleLoggedIn.

func (*User) AddCredentials

func (user *User) AddCredentials(credential webauthn.Credential, isSuperAdmin bool) (bool, error)

func (*User) CheckUserFace

func (user *User) CheckUserFace(faceIdImage []string, provider *Provider) (bool, error)

func (*User) CredentialExcludeList

func (user *User) CredentialExcludeList() []protocol.CredentialDescriptor

CredentialExcludeList returns a CredentialDescriptor array filled with all the user's credentials

func (*User) DeleteCredentials

func (user *User) DeleteCredentials(credentialIdBase64 string) (bool, error)

func (*User) GetCountryCode

func (user *User) GetCountryCode(countryCode string) string

func (*User) GetFriendlyName

func (user *User) GetFriendlyName() string

func (*User) GetId

func (user *User) GetId() string

func (*User) GetMfaProps

func (user *User) GetMfaProps(mfaType string, masked bool) *MfaProps

func (*User) GetPreferredMfaProps

func (user *User) GetPreferredMfaProps(masked bool) *MfaProps

func (*User) GetUserFullGroupPath

func (user *User) GetUserFullGroupPath() ([]string, error)

func (*User) IsAdminUser

func (user *User) IsAdminUser() bool

func (*User) IsApplicationAdmin

func (user *User) IsApplicationAdmin(application *Application) bool

IsApplicationAdmin reports whether the user may administer (and therefore see the unmasked clientSecret/Cert of) the application. This is the sole gate GetMaskedApplication uses to decide secret reveal.

SECURITY (Red H-5): IsShared MUST NOT widen this. A shared application is VISIBLE to other orgs for login, but its credentials belong to the owning org only. Reveal is limited to the owning-org admin and the global admin (conf.AdminOrg). A non-owning org admin reading a shared app gets a MASKED app — the previous `(user.IsAdmin && application.IsShared)` clause leaked every shared app's clientSecret/Cert to any org admin.

func (*User) IsApproved added in v1.31.18

func (user *User) IsApproved() bool

IsApproved reports whether the user may access customer surfaces. Fail-open by default (absent ⇒ approved) so existing users are never locked out; only an explicit "pending" tag (set at waitlist signup) gates access. Global admins are always approved regardless of the property.

func (*User) IsMfaEnabled

func (user *User) IsMfaEnabled() bool

func (*User) IsSuperAdmin added in v1.31.21

func (user *User) IsSuperAdmin() bool

IsSuperAdmin reports whether the user is a Hanzo super admin: a member of the admin organization (owner == conf.AdminOrg, the IAM_ADMIN_ORG). This is the ONE fact behind every "global admin" gate — there is no stored is_super_admin column; the authority is derived from org membership, so it can never drift from the org the user actually belongs to. This is the CANONICAL name.

func (*User) SetApprovalStatus added in v1.31.18

func (user *User) SetApprovalStatus(status string)

SetApprovalStatus sets the approval property, allocating the map if needed.

func (*User) UpdateUserHash

func (user *User) UpdateUserHash() error

func (*User) UpdateUserPassword

func (user *User) UpdateUserPassword(organization *Organization)

func (*User) WebAuthnCredentials

func (user *User) WebAuthnCredentials() []webauthn.Credential

func (*User) WebAuthnDisplayName

func (user *User) WebAuthnDisplayName() string

func (*User) WebAuthnID

func (user *User) WebAuthnID() []byte

WebAuthnID implementation of webauthn.User interface

func (*User) WebAuthnIcon

func (user *User) WebAuthnIcon() string

func (*User) WebAuthnName

func (user *User) WebAuthnName() string

type UserGroupEnforcer

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

func NewUserGroupEnforcer

func NewUserGroupEnforcer(enforcer *authz.Enforcer) *UserGroupEnforcer

func (*UserGroupEnforcer) AddGroupForUser

func (e *UserGroupEnforcer) AddGroupForUser(user string, group string) (bool, error)

func (*UserGroupEnforcer) AddGroupsForUser

func (e *UserGroupEnforcer) AddGroupsForUser(user string, groups []string) (bool, error)

func (*UserGroupEnforcer) DeleteGroupForUser

func (e *UserGroupEnforcer) DeleteGroupForUser(user string, group string) (bool, error)

func (*UserGroupEnforcer) DeleteGroupsForUser

func (e *UserGroupEnforcer) DeleteGroupsForUser(user string) (bool, error)

func (*UserGroupEnforcer) GetAllUsersByGroup

func (e *UserGroupEnforcer) GetAllUsersByGroup(group string) ([]string, error)

func (*UserGroupEnforcer) GetGroupsForUser

func (e *UserGroupEnforcer) GetGroupsForUser(user string) ([]string, error)

func (*UserGroupEnforcer) GetUserNamesByGroupName

func (e *UserGroupEnforcer) GetUserNamesByGroupName(groupName string) ([]string, error)

func (*UserGroupEnforcer) UpdateGroupsForUser

func (e *UserGroupEnforcer) UpdateGroupsForUser(user string, groups []string) (bool, error)

type UserShort

type UserShort struct {
	Owner string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name  string `xorm:"varchar(100) notnull pk" json:"name"`

	Id            string `xorm:"varchar(100) index" json:"id"`
	DisplayName   string `xorm:"varchar(100)" json:"displayName"`
	Avatar        string `xorm:"varchar(500)" json:"avatar"`
	Email         string `xorm:"varchar(100) index" json:"email"`
	EmailVerified bool   `json:"email_verified,omitempty"`
	Phone         string `xorm:"varchar(100) index" json:"phone"`
}

type UserStandard

type UserStandard struct {
	Owner string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name  string `xorm:"varchar(100) notnull pk" json:"preferred_username,omitempty"`

	Id            string `xorm:"varchar(100) index" json:"id"`
	DisplayName   string `xorm:"varchar(100)" json:"name,omitempty"`
	Avatar        string `xorm:"varchar(500)" json:"picture,omitempty"`
	Email         string `xorm:"varchar(100) index" json:"email,omitempty"`
	EmailVerified bool   `json:"email_verified,omitempty"`
	Phone         string `xorm:"varchar(100) index" json:"phone,omitempty"`
}

type UserWithoutThirdIdp

type UserWithoutThirdIdp struct {
	Owner string `json:"owner"`
	Name  string `json:"name"`

	Id            string `json:"id,omitempty"`
	Type          string `json:"type,omitempty"`
	DisplayName   string `json:"displayName,omitempty"`
	Email         string `json:"email,omitempty"`
	EmailVerified bool   `json:"email_verified,omitempty"`
	Phone         string `json:"phone,omitempty"`

	IsAdmin bool `json:"isAdmin,omitempty"`

	Roles       []roleRef         `json:"roles,omitempty"`
	Permissions []roleRef         `json:"permissions,omitempty"`
	Groups      []string          `json:"groups,omitempty"`
	Properties  map[string]string `json:"properties,omitempty"`
}

UserWithoutThirdIdp is the identity + authorization projection embedded in the default "JWT" access token. It carries exactly what a bearer needs: identity (sub/name/owner/email), the org (owner + the wrapper's `organization` claim), the authorization grant (isAdmin + roles/permissions/groups) and the billing tier (Properties, filtered to billingProps). Everything else is dropped: credential material (password/passwordSalt/passwordType/totpSecret/ recoveryCodes/hash), the full profile (avatar/address/education/social-IdP links), audit + gamification fields, managedAccounts and the console UI-preferences blob that otherwise dominated Properties.

Two invariants fall out by construction: (1) the token never leaks credentials, and (2) it stays inside the edge request-header buffer — api.hanzo.ai answers HTTP 431 "Too big request header" on oversized headers, which locked tenants out of /v1/chat/completions, billing CRUD and search.

type Userinfo

type Userinfo struct {
	Sub string `json:"sub"`
	Iss string `json:"iss"`
	Aud string `json:"aud"`
	// Owner is the tenant/org slug (the org the user belongs to). It is the
	// canonical org claim across IAM's OIDC surface and JWTs — the gateway
	// derives X-Org-Id from it (see the 2026-03-27 header convention), and
	// migrated clients read it to scope tenancy. Organization mirrors it under
	// the standard OIDC-friendly name so consumers can read either.
	Owner         string   `json:"owner"`
	Organization  string   `json:"organization,omitempty"`
	Name          string   `json:"preferred_username,omitempty"`
	DisplayName   string   `json:"name,omitempty"`
	Email         string   `json:"email,omitempty"`
	EmailVerified bool     `json:"email_verified,omitempty"`
	Avatar        string   `json:"picture,omitempty"`
	Address       string   `json:"address,omitempty"`
	Phone         string   `json:"phone,omitempty"`
	RealName      string   `json:"real_name,omitempty"`
	IsVerified    bool     `json:"is_verified,omitempty"`
	Groups        []string `json:"groups,omitempty"`
	Roles         []string `json:"roles,omitempty"`
	Permissions   []string `json:"permissions,omitempty"`
}

func GetUserInfo

func GetUserInfo(user *User, scope string, aud string, host string) (*Userinfo, error)

type ValidatorFunc

type ValidatorFunc func(password string, lang string) string

type VerificationRecord

type VerificationRecord struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	RemoteAddr string `xorm:"varchar(100)" json:"remoteAddr"`
	Type       string `xorm:"varchar(10)" json:"type"`
	User       string `xorm:"varchar(100) notnull" json:"user"`
	Provider   string `xorm:"varchar(100) notnull" json:"provider"`
	Receiver   string `xorm:"varchar(100) index notnull" json:"receiver"`
	Code       string `xorm:"varchar(10) notnull" json:"code"`
	Time       int64  `xorm:"notnull" json:"time"`
	IsUsed     bool   `xorm:"notnull" json:"isUsed"`
}

func GetPaginationVerifications

func GetPaginationVerifications(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*VerificationRecord, error)

func GetUserVerifications

func GetUserVerifications(owner, user string) ([]*VerificationRecord, error)

func GetVerification

func GetVerification(id string) (*VerificationRecord, error)

func GetVerifications

func GetVerifications(owner string) ([]*VerificationRecord, error)

type VerifyResult

type VerifyResult struct {
	Code int
	Msg  string
}

func CheckVerificationCode

func CheckVerificationCode(dest string, code string, lang string) (*VerifyResult, error)

type ViaSSHDialer

type ViaSSHDialer struct {
	Client       *ssh.Client
	Context      *context.Context
	DatabaseType string
}

func (*ViaSSHDialer) Dial

func (v *ViaSSHDialer) Dial(network, address string) (net.Conn, error)

func (*ViaSSHDialer) DialContext

func (v *ViaSSHDialer) DialContext(ctx context.Context, network string, addr string) (net.Conn, error)

func (*ViaSSHDialer) DialTimeout

func (v *ViaSSHDialer) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error)

func (*ViaSSHDialer) MysqlDial

func (v *ViaSSHDialer) MysqlDial(ctx context.Context, addr string) (net.Conn, error)

func (*ViaSSHDialer) Open

func (v *ViaSSHDialer) Open(s string) (_ driver.Conn, err error)
type WalletLink struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"` // organization
	User        string `xorm:"varchar(100) notnull pk" json:"user"`  // user.Name
	Chain       string `xorm:"varchar(20) notnull pk unique(chain_addr)" json:"chain"`
	Address     string `xorm:"varchar(128) notnull pk unique(chain_addr)" json:"address"`
	Scheme      string `xorm:"varchar(40)" json:"scheme"`
	PublicKey   string `xorm:"varchar(256)" json:"publicKey"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
}
func GetWalletLink(organization, chain, address string) (*WalletLink, error)

GetWalletLink resolves a verified (chain,address) to its link row, scoped to the application's organization. Returns (nil, nil) when no wallet is on file.

NOTE: address is compared as the verifier canonicalizes it. For EVM the verifier returns a lowercased 0x address, so store + look up the verifier's canonical form to keep EVM case-insensitive.

func GetWalletLinkGlobal added in v1.22.1

func GetWalletLinkGlobal(chain, address string) (*WalletLink, error)

GetWalletLinkGlobal resolves a verified (chain,address) across every organization. The (chain,address) pair is globally unique, so this returns at most one row. Used to enforce "a wallet binds to at most one identity" even across orgs before a new link is created.

func GetWalletLinksByUser added in v1.22.1

func GetWalletLinksByUser(owner, user string) ([]*WalletLink, error)

GetWalletLinksByUser lists every wallet a user has linked (for account UI).

type WalletLoginInput added in v1.22.1

type WalletLoginInput struct {
	Domain    string // host the nonce was minted against (re-checked vs the burned row)
	Chain     wc.Chain
	Scheme    string
	Address   string
	PublicKey string
	Message   string
	Signature string
	Extra     map[string]interface{}

	Method       string // "signup" (default) | "login"
	Application  *Application
	Organization *Organization
	SessionUser  *User // non-nil => an authenticated caller linking a new wallet
}

WalletLoginInput is everything the auth core needs to verify a wallet login and resolve it to a user. It is a walletconnect proof plus the routing context the HTTP shell has already resolved (application/organization) and, for the "link a new wallet to my existing account" flow, the authenticated session user (nil when anonymous).

type Web3Nonce added in v1.22.1

type Web3Nonce struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"` // the nonce string itself
	Chain       string `xorm:"varchar(20)" json:"chain"`
	Address     string `xorm:"varchar(128)" json:"address"`
	Domain      string `xorm:"varchar(128)" json:"domain"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
	ExpireTime  string `xorm:"varchar(100)" json:"expireTime"`
	Used        bool   `xorm:"bool" json:"used"`
}

func BurnWeb3Nonce added in v1.22.1

func BurnWeb3Nonce(nonce string) (*Web3Nonce, error)

BurnWeb3Nonce atomically consumes a nonce. Returns the row iff it existed, was unused, and is unexpired; otherwise (nil, nil). The conditional UPDATE is the replay guard -- never split "read then write".

func MintWeb3Challenge added in v1.22.1

func MintWeb3Challenge(domain string, chain wc.Chain, address string) (*Web3Nonce, *wc.LoginChallenge, error)

MintWeb3Challenge creates a single-use login nonce, persists it, and returns both the stored row and the CAIP-122 LoginChallenge the wallet must sign.

domain MUST be the brand login host derived from the request (hanzo.id / lux.id / ...), never client-supplied -- phishing protection rides on the domain binding. chain/address are advisory (scoping/rate-limit hints); the authoritative binding happens in VerifyWalletLogin against the SIGNED message.

type WebFinger

type WebFinger struct {
	Subject    string             `json:"subject"`
	Links      []WebFingerLink    `json:"links"`
	Aliases    *[]string          `json:"aliases,omitempty"`
	Properties *map[string]string `json:"properties,omitempty"`
}

func GetWebFinger

func GetWebFinger(resource string, rels []string, host string, applicationName string) (WebFinger, error)
type WebFingerLink struct {
	Rel  string `json:"rel"`
	Href string `json:"href"`
}

type Webhook

type Webhook struct {
	Owner       string `xorm:"varchar(100) notnull pk" json:"owner"`
	Name        string `xorm:"varchar(100) notnull pk" json:"name"`
	CreatedTime string `xorm:"varchar(100)" json:"createdTime"`

	Organization string `xorm:"varchar(100) index" json:"organization"`

	Url            string    `xorm:"varchar(200)" json:"url"`
	Method         string    `xorm:"varchar(100)" json:"method"`
	ContentType    string    `xorm:"varchar(100)" json:"contentType"`
	Headers        []*Header `xorm:"mediumtext" json:"headers"`
	Events         []string  `xorm:"mediumtext" json:"events"`
	TokenFields    []string  `xorm:"mediumtext" json:"tokenFields"`
	ObjectFields   []string  `xorm:"mediumtext" json:"objectFields"`
	IsUserExtended bool      `json:"isUserExtended"`
	SingleOrgOnly  bool      `json:"singleOrgOnly"`
	IsEnabled      bool      `json:"isEnabled"`
}

func GetPaginationWebhooks

func GetPaginationWebhooks(owner, organization string, offset, limit int, field, value, sortField, sortOrder string) ([]*Webhook, error)

func GetWebhook

func GetWebhook(id string) (*Webhook, error)

func GetWebhooks

func GetWebhooks(owner string, organization string) ([]*Webhook, error)

func (*Webhook) GetId

func (p *Webhook) GetId() string

type WecomAccessTokenResp

type WecomAccessTokenResp struct {
	Errcode     int    `json:"errcode"`
	Errmsg      string `json:"errmsg"`
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}

type WecomDeptListResp

type WecomDeptListResp struct {
	Errcode    int    `json:"errcode"`
	Errmsg     string `json:"errmsg"`
	Department []struct {
		Id int `json:"id"`
	} `json:"department"`
}

type WecomSyncerProvider

type WecomSyncerProvider struct {
	Syncer *Syncer
}

WecomSyncerProvider implements SyncerProvider for WeCom (WeChat Work) API-based syncers

func (*WecomSyncerProvider) AddUser

func (p *WecomSyncerProvider) AddUser(user *OriginalUser) (bool, error)

AddUser adds a new user to WeCom (not supported for read-only API)

func (*WecomSyncerProvider) Close

func (p *WecomSyncerProvider) Close() error

Close closes any open connections (no-op for WeCom API-based syncer)

func (*WecomSyncerProvider) GetOriginalGroups

func (p *WecomSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error)

GetOriginalGroups retrieves all groups from WeCom (not implemented yet)

func (*WecomSyncerProvider) GetOriginalUserGroups

func (p *WecomSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error)

GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)

func (*WecomSyncerProvider) GetOriginalUsers

func (p *WecomSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error)

GetOriginalUsers retrieves all users from WeCom API

func (*WecomSyncerProvider) InitAdapter

func (p *WecomSyncerProvider) InitAdapter() error

InitAdapter initializes the WeCom syncer (no database adapter needed)

func (*WecomSyncerProvider) TestConnection

func (p *WecomSyncerProvider) TestConnection() error

TestConnection tests the WeCom API connection

func (*WecomSyncerProvider) UpdateUser

func (p *WecomSyncerProvider) UpdateUser(user *OriginalUser) (bool, error)

UpdateUser updates an existing user in WeCom (not supported for read-only API)

type WecomUser

type WecomUser struct {
	UserId     string `json:"userid"`
	Name       string `json:"name"`
	Department []int  `json:"department"`
	Position   string `json:"position"`
	Mobile     string `json:"mobile"`
	Gender     string `json:"gender"`
	Email      string `json:"email"`
	Avatar     string `json:"avatar"`
	Status     int    `json:"status"`
	Enable     int    `json:"enable"`
}

type WecomUserListResp

type WecomUserListResp struct {
	Errcode  int          `json:"errcode"`
	Errmsg   string       `json:"errmsg"`
	Userlist []*WecomUser `json:"userlist"`
}

type X509Certificate

type X509Certificate struct {
	XMLName xml.Name `xml:"http://www.w3.org/2000/09/xmldsig# X509Certificate"`
	Cert    string   `xml:",innerxml"`
}

type X509Data

type X509Data struct {
	XMLName         xml.Name        `xml:"http://www.w3.org/2000/09/xmldsig# X509Data"`
	X509Certificate X509Certificate `xml:",innerxml"`
}

type X509Key

type X509Key struct {
	X509Certificate string
	PrivateKey      string
}

func (X509Key) GetKeyPair

func (x X509Key) GetKeyPair() (privateKey *rsa.PrivateKey, cert []byte, err error)

Source Files

Jump to

Keyboard shortcuts

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