identity

package
v14.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// AttrAccessSelf is a profile field a client with users:update may change.
	AttrAccessSelf = "self"
	// AttrAccessPrivileged is written by an admin client, or by a server client
	// whose scopes include users:attr:<name>.
	AttrAccessPrivileged = "privileged"
)
View Source
const (
	// RecoveryCodesLength is the array length of the recovery codes.
	RecoveryCodesLength = 4
	// RecoveryCodeLength is the character length of each recovery code.
	RecoveryCodeLength = 12
)
View Source
const Header = "X-Token"

Header is the header key used to send the server application client's token.

Variables

View Source
var (
	// ReadUserPolicy is the policy that allows reading the self-user data.
	ReadUserPolicy = oauth2.ResourcePolicy{Resource: "user", Action: "read"}

	// UserAppPolicies are the policies that the app user client can use.
	// Now includes OIDC standard scopes
	UserAppPolicies = []oauth2.Policy{
		ReadUserPolicy,
	}

	// UserAppScopes are the scopes that the app user client can use.
	UserAppScopes = oauth2.PolicyScopes(UserAppPolicies...)
)
View Source
var (
	// CreateUsersPolicy is the policy that allows creating new users.
	CreateUsersPolicy = oauth2.ResourcePolicy{Resource: "users", Action: "create"}
	// ReadUsersPolicy is the policy that allows reading one or more users.
	ReadUsersPolicy = oauth2.ResourcePolicy{Resource: "users", Action: "read"}
	// UpdateUsersPolicy is the policy that allows updating one or more user data.
	UpdateUsersPolicy = oauth2.ResourcePolicy{Resource: "users", Action: "update"}
	// DeleteUsersPolicy is the policy that allows deleting one or more users.
	DeleteUsersPolicy = oauth2.ResourcePolicy{Resource: "users", Action: "delete"}
	// BillingPolicy is the policy that allows reading the billing data.
	BillingPolicy = oauth2.ResourcePolicy{Resource: "billing", Action: "read"}

	// ServerOnlyPolicies gate /u, /u/groups, /cors, /billing and /cache.
	// AllowPolicies matches any one of them. A user client holds user:read, which is not here.
	ServerOnlyPolicies = []oauth2.Policy{
		CreateUsersPolicy,
		ReadUsersPolicy,
		UpdateUsersPolicy,
		DeleteUsersPolicy,
		BillingPolicy,
	}

	// CreateClientsPolicy is the policy that allows creating new clients.
	CreateClientsPolicy = oauth2.ResourcePolicy{Resource: "clients", Action: "create"}
	// ReadClientsPolicy is the policy that allows reading one or more clients.
	ReadClientsPolicy = oauth2.ResourcePolicy{Resource: "clients", Action: "read"}
	// UpdateClientsPolicy is the policy that allows updating one or more clients.
	UpdateClientsPolicy = oauth2.ResourcePolicy{Resource: "clients", Action: "update"}
	// DeleteClientsPolicy is the policy that allows deleting one or more clients.
	DeleteClientsPolicy = oauth2.ResourcePolicy{Resource: "clients", Action: "delete"}

	// ServerAppPolicies are the policies that the app server client can use, including the user client app's ones.
	ServerAppPolicies = slices.Concat(ServerOnlyPolicies, UserAppPolicies)
)
View Source
var (
	// ManageClientsPolicies are the policies that allow managing the client applications.
	ManageClientsPolicies = []oauth2.Policy{
		CreateClientsPolicy,
		ReadClientsPolicy,
		UpdateClientsPolicy,
		DeleteClientsPolicy,
	}

	// ManageClientsScopes are the scopes of the ManageClientsPolicies.
	ManageClientsScopes = oauth2.PolicyScopes(ManageClientsPolicies...)

	// AdminAppPolicies are the policies that the admin app client can use:
	// the server ones plus the client management ones.
	// slices.Concat allocates a new slice, so it never aliases the backing array of ServerAppPolicies.
	AdminAppPolicies = slices.Concat(ServerAppPolicies, ManageClientsPolicies)
)

AllPolicies contains all policies. Note: to invalidate all previous client tokens, just change its client secret value on database and on the client-side.

View Source
var ErrInvalidUserCredentials = errors.New("invalid user credentials")
View Source
var ErrSignToken = errors.New("failed to sign token")

ErrSignToken is returned when the server fails to sign a token.

View Source
var ProtectedFields = map[string]bool{
	"id":         true,
	"created_at": true,
	"updated_at": true,
}

ProtectedFields are system-managed fields that cannot be updated by users

View Source
var ReservedUserFields = []string{
	"id", "username", "password", "created_at", "updated_at", "password", "otp", "otp_recovery_codes",
}

ReservedUserFields contains field names that cannot be set in custom attributes because they are already part of the User entity structure.

View Source
var RestrictedUserUpdateColumns = []string{
	"id", "created_at", "updated_at", "password", "otp", "otp_recovery_codes",
}

RestrictedUserUpdateColumns are the columns that are not allowed to be updated by the UpdateUsers method.

View Source
var UpdatableCoreFields = map[string]bool{
	"username": true,
	"password": true,
}

UpdatableCoreFields are core table fields that can be updated through the set_paths API

Functions

func AttrScope

func AttrScope(name string) string

AttrScope is the scope a server client needs to write a privileged attribute.

func FetchUser

func FetchUser[T any](ctx context.Context, opts entity.FetchOptions, identifier string, usernameIsEmail bool, job fetchJob[T]) (T, error)

FetchUser fetches a user based on the identifier.

func GenerateOTP

func GenerateOTP(issuer, userID, username string) (key *otp.Key, img []byte, err error)

GenerateOTP generates a new TOTP key and returns the QR code image and the key.

func GenerateOTPCode

func GenerateOTPCode(otpURL string) (string, error)

GenerateOTPCode generates a new OTP code based on the given OTP AUTH URL.

func GenerateRecoveryCodes

func GenerateRecoveryCodes() []string

GenerateRecoveryCodes generates 4 recovery codes of 12 chars length that can be used only once.

func NewCostHandler

func NewCostHandler(opts httpcost.Options, db *pg.DB) context.Handler

NewCostHandler returns a new cost handler that calculates the cost of a request and stores it in the provided MetricStore.

func ProcessUser

func ProcessUser[T any](ctx context.Context, identifier string, usernameIsEmail bool, jobWithID, jobWithUsername processJob[T]) (T, error)

ProcessUser processes the user identifier based on its type (UUID or username).

func RegisterCodeErrors

func RegisterCodeErrors() *errors.Options

RegisterCodeErrors registers the error codes used by the identity server. It returns a new errors.Options instance with the error codes mapped to their corresponding HTTP status codes.

func ValidateOTP

func ValidateOTP(passcode, otpURL string) (bool, error)

ValidateOTP validates the given passcode against the given OTP AUTH URL.

Types

type BillingController

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

func NewBillingController

func NewBillingController(r *entity.Registry, cache *httpcache.Cache) *BillingController

func (*BillingController) Routing

func (c *BillingController) Routing(r router.Router)

type BulkIdentifierRequest

type BulkIdentifierRequest struct {
	IDs []string `json:"ids"` // IDs of the users.
}

func (*BulkIdentifierRequest) GetIdentifiers

func (req *BulkIdentifierRequest) GetIdentifiers() []string

type BulkInsertUsersResponse

type BulkInsertUsersResponse struct {
	TotalProvided int64  `json:"total_provided"`
	TotalInserted int64  `json:"total_inserted"`
	Message       string `json:"message"`
}

BulkInsertUsersResponse represents the response for bulk user insertion

type BulkUserDeleteRequest

type BulkUserDeleteRequest struct {
	BulkIdentifierRequest
	Soft bool `json:"soft,omitzero"` // when true the users are not actually deleted, they are still there but marked as deleted and cannot be signed-in.
}

type CORSController

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

func NewCORSController

func NewCORSController(cors *CORSService, cache *httpcache.Cache) *CORSController

func (*CORSController) Routing

func (c *CORSController) Routing(r router.Router)

type CORSService

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

func NewCORSService

func NewCORSService(r *entity.Registry, allowLocal bool) *CORSService

func (*CORSService) AllowOrigin

func (s *CORSService) AllowOrigin(ctx *context.Context, origin string) bool

AllowOrigin completes the cors.AllowOriginFunc signature.

func (*CORSService) DeleteOriginPatterns

func (s *CORSService) DeleteOriginPatterns(ctx stdContext.Context, patterns ...string) (bool, error)

func (*CORSService) Handler

func (s *CORSService) Handler() context.Handler

func (*CORSService) ListOriginPatterns

func (s *CORSService) ListOriginPatterns(ctx stdContext.Context) ([]string, error)

func (*CORSService) Patterns

func (s *CORSService) Patterns() []string

Patterns returns the currently stored CORS patterns.

func (*CORSService) UpsertOriginPatterns

func (s *CORSService) UpsertOriginPatterns(ctx stdContext.Context, patterns ...string) (bool, error)

type CacheController

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

func NewCacheController

func NewCacheController(cache *httpcache.Cache) *CacheController

NewCacheController creates a new CacheController with the given HTTP cache.

func (*CacheController) Routing

func (c *CacheController) Routing(r router.Router)

type CacheInformationResponse

type CacheInformationResponse struct {
	TotalCount        int64             `json:"total_count"`
	PasswordProtected bool              `json:"password_protected"`
	Options           httpcache.Options `json:"options"`
}

type ClientController

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

ClientController serves the client application routes under /clients: the self routes of the calling client and the client management ones.

func NewClientController

func NewClientController(r *entity.Registry, oauth2Server *oauth2.Server[entity.FlatUser], signer *ClientTokenSigner) *ClientController

NewClientController returns a client controller. The oauth2 server and the signer serve the client management routes.

func (*ClientController) Routing

func (c *ClientController) Routing(r router.Router)

type ClientCredentials

type ClientCredentials struct {
	Audience      string     `json:"audience"` // The client ID, consumers set Audiences: [audience].
	Kind          ClientKind `json:"kind"`
	Token         string     `json:"token"`
	EncryptionKey string     `json:"encryption_key,omitempty"` // Server and admin clients only.
}

ClientCredentials is what a client application needs to talk to the identity server.

type ClientKind

type ClientKind string

ClientKind is the kind of an OAuth2 client application managed by the identity server.

const (
	// ClientKindServer is a server application: password and refresh token grants,
	// the user management scopes and an encrypted, non-expiring token.
	ClientKindServer ClientKind = "server"
	// ClientKindUser is a user application: authorization code flow (and device code
	// when it has a verification URI) with a plain, non-expiring token.
	ClientKindUser ClientKind = "user"
	// ClientKindAdmin is a server application that may also manage clients.
	ClientKindAdmin ClientKind = "admin"
)

func KindOfClient

func KindOfClient(c *oauth2.Client) ClientKind

KindOfClient infers the kind of a stored client. A client without the password grant is a user client, a client with any "clients:" scope is an admin client and everything else is a server client.

type ClientTokenSigner

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

ClientTokenSigner signs the tokens of the client applications.

func NewClientTokenSigner

func NewClientTokenSigner(clientAuth *auth.Auth[oauth2.ClientTokenClaims], encryptionKey string) *ClientTokenSigner

NewClientTokenSigner returns a signer that uses the given client authenticator and hands out the given encryption key to server and admin clients.

func (*ClientTokenSigner) Credentials

func (s *ClientTokenSigner) Credentials(client *oauth2.Client) (*ClientCredentials, error)

Credentials signs the client's token and returns it with the other values the client needs. Server and admin clients get the encrypted refresh token and the encryption key, user clients get the plain access token.

func (*ClientTokenSigner) Sign

func (s *ClientTokenSigner) Sign(client *oauth2.Client) (*oauth2.Token, error)

Sign signs the token pair of the given client.

type CountClientsResponse

type CountClientsResponse struct {
	TotalCount int64 `json:"total_count"`
}

CountClientsResponse is the response body of GET /clients/count.

type CountResponse

type CountResponse struct {
	ActiveCount   int64 `json:"active_count"`
	InactiveCount int64 `json:"inactive_count"`
	TotalCount    int64 `json:"total_count"`
}

type CountUserGroupsResponse

type CountUserGroupsResponse struct {
	TotalCount int64 `json:"total_count"`
}

type CreateClientRequest

type CreateClientRequest struct {
	Name    string     `json:"name"`
	Website string     `json:"website"`
	LogoURL string     `json:"logo_url"`
	Kind    ClientKind `json:"kind"`
	// RedirectURI is required for the user kind.
	RedirectURI string `json:"redirect_uri,omitempty"`
	// VerificationURI adds the device code grant to a user client.
	VerificationURI string `json:"verification_uri,omitempty"`
	// The max ages are in seconds. Zero means the default of the kind.
	CodeMaxAge    int `json:"code_max_age,omitempty"`
	AccessMaxAge  int `json:"access_max_age,omitempty"`
	RefreshMaxAge int `json:"refresh_max_age,omitempty"`
}

CreateClientRequest is the request body of POST /clients.

func (*CreateClientRequest) Validate

func (r *CreateClientRequest) Validate() error

Validate reports the missing required fields. BindJSON calls it and answers 400 on error.

type CreateClientResponse

type CreateClientResponse struct {
	ClientCredentials
	Client *oauth2.Client `json:"client"`
}

CreateClientResponse is the response body of POST /clients: the credentials of the new client and the client itself, secret included.

type IdentifierRequest

type IdentifierRequest struct {
	Identifier string `json:"identifier"` // id or username (email).

	// Compatibility with ID & Username.
	// If one is set it is used as identifier if that is missing.
	ID       string `json:"id,omitempty"`       // ID of the user.
	Username string `json:"username,omitempty"` // Username of the user, used only if ID is not set.
}

IdentifierRequest is a request body that contains an identifier for user operations.

func (*IdentifierRequest) GetIdentifier

func (req *IdentifierRequest) GetIdentifier() string

GetIdentifier returns the identifier to be used for signing in.

type Options

type Options struct {
	// The postgres database connection string.
	// Example connection string:
	// host=localhost port=5432 user=makis password=_Pass_ search_path=public dbname=_MyDB_ sslmode=require pool_max_conns=12 pool_min_conns=1 pool_max_conn_lifetime=1h pool_max_conn_idle_time=45m pool_health_check_period=15m
	ConnectionString string             `yaml:"ConnectionString"`
	Auth             auth.Configuration `yaml:"Auth"`
	// EncryptionKey is the required key used to encrypt (AES-GCM) any sensitive data
	// sent to the server by its clients.
	// It's sent to the client once and it should be kept secret on both sides,
	// it's not communicated back to the server.
	// The EncryptionKey is used to encrypt & decrypt the client's secret and the user's password.
	// If it's empty, it's resolved automatically from the Auth's access token key's configured
	// encryption key or, if that one is empty too, from the refresh token key's one.
	// `New` panics if neither of them is configured.
	EncryptionKey string `yaml:"EncryptionKey"`
	// For authorization & device code flows.
	LoginPageURL   string `yaml:"LoginPageURL"`
	ConsentPageURL string `yaml:"ConsentPageURL"`
	// AllowLocalCORS allows loopback origins. Leave it false in production.
	AllowLocalCORS bool `yaml:"AllowLocalCORS"`
	// When true, the username field is treated as an email address
	// and used for password reset and other email-based features.
	UsernameIsEmail bool `yaml:"UsernameIsEmail"`
	// When true, the user can sign up with the same password as the one used to restore the account.
	RestoreOnSamePasswordSignup bool `yaml:"RestoreOnSamePasswordSignup"`

	// Schema is a list of user attributes that are allowed to be set by the user.
	// It is used to validate the user attributes based on the provided JSON schema.
	//
	// Supported field types:
	//   - "text": String field with optional min/max length validation
	//   - "number": Numeric field with optional min/max value validation
	//   - "email": Email field with built-in email format validation
	//   - "date": Date field with optional min/max year validation (YYYY-MM-DD format)
	//   - "phone": Phone number field with optional format validation
	//   - "bool": Boolean field accepting true/false values or string representations
	//   - "slice": Slice field accepting a list of values with optional type and length validation
	//   - "map": Map field accepting map[string]any with optional required key validation
	//   - "uuid": UUID field with optional database indexing
	// See `parseUserSchema` for more information.
	//
	// Examples:
	//   - Name: "firstname"
	//     Type: "text"
	//     Params: ["3", "15"]         # Text field with min 3, max 15 characters
	//   - Name: "lastname"
	//     Type: "text"
	//     Params: ["3", "15"]         # Text field with min 3, max 15 characters
	//   - Name: "age"
	//     Type: "number"
	//     Params: ["18", "105"]       # Numeric field with min 18, max 105
	//   - Name: "email"
	//     Type: "email"
	//     Indexed: true               # Email field with database index
	//     Required: true              # Required field, must be provided
	//   - Name: "company_id"
	//     Type: "uuid"
	//     Indexed: true               # UUID field with database index
	//   - Name: "birthdate"
	//     Type: "date"
	//     Params: ["1900", "now"]     # Date field with min year 1900, max current year
	//   - Name: "phone"
	//     Type: "phone"
	//     Params: ["international"]   # Phone field with international format
	//   - Name: "is_active"
	//     Type: "bool"                # Boolean field accepting true/false or "true"/"false"
	//   - Name: "tags"
	//     Type: "slice"
	//     Params: ["text", "1", "10"]  # Slice of text values between 1 and 10 items
	//   - Name: "tags"
	//     Type: "slice"
	//     Params: ["text"]             # Slice of text values without restrictions
	//   - Name: "tags"
	//     Type: "slice"
	//     Params: ["text", "1"]        # Slice of text values with minimum 1 item
	//   - Name: "preferences"
	//     Type: "map"
	//     Params: ["theme", "lang"]   # Map field requiring "theme" and "lang" keys
	//   - Name: "metadata"
	//     Type: "map"                 # Map field with no required keys
	Schema []*UserAttribute `yaml:"Schema"`
	// Cache options, optional.
	// Example:
	// 	Cache:
	//   Disable: false
	//   Addr:     "127.0.0.1:6379"
	//   Password: "admin!123"
	//   TTL: 10m
	//   CommandTimeout: 15s
	Cache httpcache.Options `yaml:"Cache"`
	// Cache is the user cache options.
	// It is used to cache user data and paginated user lists.
	// If empty, the cache is disabled and all operations are no-op.
	// Cache UserCacheOptions `yaml:"Cache"`
	// Billing & costing options, optional.
	Cost httpcost.Options `yaml:"Cost"`
}

Options is the configuration for the identity server. It's used to create a new identity server. The Options can loaded from a YAML file.

type Server

type Server struct {
	EncryptionKey string
	Provider      *UserProvider
	// contains filtered or unexported fields
}

Server is the identity server. The server is responsible to manage the user-side and server-side client OAuth2 applications.

func Load

func Load(optionsFilename string) *Server

Load loads the identity server from a YAML configuration file. It panics on failure.

func New

func New(opts Options) *Server

New creates and returns a new identity server. It panics on failure.

func (*Server) AddAdminApplication

func (s *Server) AddAdminApplication(ctx stdContext.Context, name, website, logo string) (*ServerApp, error)

AddAdminApplication registers (or upgrades) a server application that may also manage clients. An existing application keeps its secret and version, it only gains the missing "clients:" scopes. It returns an error if the existing application is a user application, which has no password grant.

func (*Server) AddServerApplication

func (s *Server) AddServerApplication(ctx stdContext.Context, name, website, logo string) (*ServerApp, error)

AddServerApplication registers a new server application. It returns the server application structure which contains the token and the shared encryption key. If the application already exists, it generates a token based on the existing one. Usage:

serverApp, err := identityServer.AddServerApplication(
    context.Background(),
    "Example-Server-Name",
    "https://www.iris-go.com",
    "https://www.iris-go.com/images/logo.png",
)

func (*Server) AddUserApplication

func (s *Server) AddUserApplication(ctx stdContext.Context, reg UserApplicationRegistration) (*UserApp, error)

AddUserApplication registers a new user application. If the application already exists, it generates a token based on the existing one. It returns the user application structure which contains the token.

A user application always gets the oauth2.GrantTypeAuthorizationCode, oauth2.GrantTypeDeviceCode and oauth2.GrantTypeRefreshToken grant types and the scopes of UserAppPolicies.

func (*Server) Close

func (s *Server) Close()

Close closes the database and cache connections.

func (*Server) Routing

func (s *Server) Routing(r router.Router)

Routing registers the identity server's handlers to the provided router. It implements the router.Controller/Routing interface.

Usage:

app.Router("/auth", identityServer)

type ServerApp

type ServerApp struct {
	Token         string `yaml:"Token"`
	EncryptionKey string `yaml:"EncryptionKey"`

	Client *oauth2.Client `yaml:"-"`
}

ServerApp is the client application that is used by the server. It has access to all the APIs, including the OAuth2 password grant flow. It's used to create, read, update and delete users.

type TokenEnrichmentResponse

type TokenEnrichmentResponse struct {
	AccessToken string `json:"access_token"`
}

type UpdateClientTokenMaxAgeRequest

type UpdateClientTokenMaxAgeRequest struct {
	AccessMaxAge  int `json:"access_max_age"`
	RefreshMaxAge int `json:"refresh_max_age"`
}

type UserApp

type UserApp struct {
	Token string `yaml:"Token"`

	Client *oauth2.Client `yaml:"-"` // The client application used by the user.
}

UserApp is the client application that is used by the user. It has no access for the OAuth2 password grant flow neither any of the APIs available outside of the /oauth2 ones.

type UserApplicationRegistration

type UserApplicationRegistration struct {
	// Name is the unique name of the application. Required.
	Name string
	// Website is the website URL of the application. Required.
	Website string
	// LogoURL is the URL of the application's logo. Required.
	LogoURL string
	// RedirectURI is the callback URL of the authorization code flow.
	// Required, because a user application always has the authorization code grant type.
	RedirectURI string
	// VerificationURI is the URL where the user enters the device code.
	// Required, because a user application always has the device code grant type.
	VerificationURI string
	// CodeMaxAge is the max age of the authorization and device codes, in seconds.
	// Zero or negative means 3600 (one hour).
	CodeMaxAge int
	// AccessMaxAge is the max age of the access tokens, in seconds.
	// Zero or negative means the token does not expire.
	AccessMaxAge int
	// RefreshMaxAge is the max age of the refresh tokens, in seconds.
	// Zero or negative means the token does not expire. When both max ages are above zero,
	// RefreshMaxAge must be at least AccessMaxAge plus 60.
	RefreshMaxAge int
}

UserApplicationRegistration holds the values AddUserApplication registers a user application with. It has no grant types or scopes: a user application always gets the authorization_code, device code and refresh_token grant types, and the scopes of UserAppPolicies.

Name, Website and LogoURL are required, the same way as in oauth2.ClientRegistration.

type UserAttribute

type UserAttribute struct {
	// Name of the attribute (e.g., firstname, lastname, email)
	Name string `json:"name" yaml:"Name"`
	// Type of the attribute (e.g., text, number, email, date, phone)
	Type string `json:"type" yaml:"Type"`
	// Additional parameters for the attribute type, if any.
	Params []string `json:"params,omitempty" yaml:"Params"`
	// Indexed indicates whether the attribute should be indexed in the database.
	Indexed bool `json:"indexed,omitzero" yaml:"Indexed"`
	// Required indicates whether the attribute is required.
	Required bool `json:"required,omitzero" yaml:"Required"`
	// Access is who may write the attribute.
	// "self" (the default) is a profile field a client with users:update may change.
	// "privileged" is written by an admin client, or by a server client whose scopes
	// include users:attr:<name>. The account holder does not write it.
	Access string `json:"access,omitempty" yaml:"Access"`
}

UserAttribute represents a user attribute in the user schema.

type UserConfirmPasswordResetRequest

type UserConfirmPasswordResetRequest struct {
	Token       string `json:"token"`
	NewPassword string `json:"new_password"` // client-encrypted password.
}

UserConfirmPasswordResetRequest is the request body for the password reset confirmation endpoint.

type UserController

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

UserController is the API controller for the User entity.

func NewUserController

func NewUserController(auth *auth.Auth[entity.FlatUser], userProvider *UserProvider, userSchema *UserSchema, cache *httpcache.Cache) *UserController

NewUserController creates and returns a new UserController API.

func (*UserController) Routing

func (c *UserController) Routing(r router.Router)

Routing registers the API routes. It implements the router.Controller interface.

type UserDeleteRequest

type UserDeleteRequest struct {
	IdentifierRequest

	// When true the user is not actually deleted, is still there but marked as deleted and cannot be signed-in.
	Soft bool `json:"soft,omitzero"`
}

UserDeleteRequest is the request body for the delete endpoint.

type UserGroupController

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

UserGroupController is the API controller for the UserGroup entity.

func NewUserGroupController

func NewUserGroupController(cache *httpcache.Cache, groups *UserGroupService) *UserGroupController

NewUserGroupController creates and returns a new UserGroupController API.

func (*UserGroupController) Routing

func (c *UserGroupController) Routing(r router.Router)

Routing registers the API routes. It implements the router.Controller interface.

type UserGroupService

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

func NewUserGroupService

func NewUserGroupService(r *entity.Registry) *UserGroupService

func (*UserGroupService) CountUserGroups

func (s *UserGroupService) CountUserGroups(ctx context.Context) (int64, error)

func (*UserGroupService) DeleteUserGroup

func (s *UserGroupService) DeleteUserGroup(ctx context.Context, groupID string) (bool, error)

func (*UserGroupService) GetUserGroup

func (s *UserGroupService) GetUserGroup(ctx context.Context, groupID string) (entity.UserGroup, error)

func (*UserGroupService) InTransaction

func (s *UserGroupService) InTransaction(ctx context.Context, fn func(*UserGroupService) error) error

func (*UserGroupService) ListUserGroupsPaginated

func (*UserGroupService) UpsertUserGroup

func (s *UserGroupService) UpsertUserGroup(ctx context.Context, group entity.UserGroup) (string, bool, error)

type UserIdentifier

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

UserIdentifier represents a user identifier which can be either a UUID or a username/email.

func ParseUserIdentifier

func ParseUserIdentifier(text string, usernameIsEmail bool) (UserIdentifier, error)

ParseUserIdentifier parses the given text as an identifier. It checks if the text is a valid UUID or a username/email based on the usernameIsEmail flag.

func (UserIdentifier) IsEmail

func (id UserIdentifier) IsEmail() bool

IsEmail reports whether the identifier is a valid email address.

func (UserIdentifier) IsUUID

func (id UserIdentifier) IsUUID() bool

IsUUID reports whether the identifier is a UUID.

func (UserIdentifier) IsUsername

func (id UserIdentifier) IsUsername() bool

IsUsername reports whether the identifier is a username or email (not a UUID).

func (UserIdentifier) String

func (id UserIdentifier) String() string

String returns the string representation of the identifier.

type UserPasswordResetRequest

type UserPasswordResetRequest struct {
	IdentifierRequest
	NewPassword string `json:"new_password"` // client-encrypted password.
}

type UserProvider

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

UserProvider is the user authentication and service provider.

func NewUserProvider

func NewUserProvider(r *entity.Registry, authServer *auth.Auth[entity.FlatUser], encryptionKey string, usernameIsEmail, restoreOnSamePasswordSignup bool) *UserProvider

NewUserProvider returns a new UserProvider.

func (*UserProvider) BulkDeleteUsers

func (s *UserProvider) BulkDeleteUsers(ctx stdContext.Context, ids []string, soft bool) (int64, error)

func (*UserProvider) BulkInsertUsers

func (s *UserProvider) BulkInsertUsers(ctx stdContext.Context, users []entity.User) (int64, error)

BulkInsertUsers inserts multiple users in batches with automatic password generation and AES decryption support. If a user's password is empty, generates a strong random password and hashes it. If a user's password is AES-encrypted (hex format), attempts to decrypt it using the provider's shared key. Users are inserted in batches of 500 within separate transactions for optimal performance. Returns the total number of users successfully inserted and any error encountered.

func (*UserProvider) CountTotalUsers

func (s *UserProvider) CountTotalUsers(ctx stdContext.Context) (int64, int64, error)

CountTotalUsers returns the total numbers of enabled and disabled users.

func (*UserProvider) DeleteUser

func (s *UserProvider) DeleteUser(ctx stdContext.Context, identifier string, soft bool) (bool, error)

DeleteUser deletes a user by identifier (ID or username).

func (*UserProvider) GeneratePasswordResetToken

func (s *UserProvider) GeneratePasswordResetToken(ctx stdContext.Context, appClient *oauth2.Client, identifier string, maxAgeSeconds int64) (string, error)

GeneratePasswordResetToken generates a password reset token for the given id or email (username).

func (*UserProvider) GetUser

func (s *UserProvider) GetUser(ctx stdContext.Context, identifier string, includePassword, includeDeleted bool) (entity.User, error)

GetUser retrieves a user by ID or username/email.

func (*UserProvider) GetUserFlattened

func (s *UserProvider) GetUserFlattened(ctx stdContext.Context, identifier string, includePassword, includeDeleted bool) (entity.FlatUser, error)

GetUserFlattened retrieves a user by ID or username/email in a flattened JSON format.

func (*UserProvider) InTransaction

func (s *UserProvider) InTransaction(ctx stdContext.Context, fn func(*UserProvider) error) error

func (*UserProvider) InvalidateToken

func (p *UserProvider) InvalidateToken(ctx stdContext.Context, standardClaims auth.StandardClaims, t entity.FlatUser) error

InvalidateToken is optional and can be used to allow tokens to be invalidated from server-side. Commonly, implement when a token and user pair is saved on a persistence storage and server can decide which token is valid or invalid. It can be an empty method too which returns a nil error.

The first input argument standard context can be casted to iris.Context if executed through Auth.SignoutHandler.

It's called on Auth.SignoutHandler.

func (*UserProvider) InvalidateTokens

func (p *UserProvider) InvalidateTokens(ctx stdContext.Context, t entity.FlatUser) error

InvalidateTokens is like InvalidateToken but it should invalidate all tokens generated for a specific T value. It can be an empty method too which returns a nil error.

The first input argument standard context can be casted to iris.Context if executed through Auth.SignoutAllHandler.

It's called on Auth.SignoutAllHandler.

func (*UserProvider) ListUsersPaginated

ListUsersPaginated returns a list of users based on the given page options and filter options.

func (*UserProvider) ListUsersPaginatedFlattened

func (s *UserProvider) ListUsersPaginatedFlattened(ctx stdContext.Context, l entity.PageOptions, f *entity.UserFilterOptions) ([]entity.FlatUser, int64, error)

ListUsersPaginatedFlattened returns users as a slice of json.RawMessage.

func (*UserProvider) Refresh

Refresh is mostly used to refresh the user information from a persistence storage. For example, if the user has changed their email or other attributes like roles.

func (*UserProvider) ResetPassword

func (s *UserProvider) ResetPassword(ctx stdContext.Context, identifier, encryptedNewPassword string) (bool, error)

ResetPassword resets the password for the given user.

func (*UserProvider) RestoreUser

func (s *UserProvider) RestoreUser(ctx stdContext.Context, identifier string) (bool, error)

RestoreUser restores a user by identifier (ID or username).

func (*UserProvider) RestoreUsers

func (s *UserProvider) RestoreUsers(ctx stdContext.Context, identifiers []string) (bool, error)

func (*UserProvider) Signin

func (p *UserProvider) Signin(ctx stdContext.Context, username, encryptedPassword string) (entity.FlatUser, error)

Signin accepts a username (or email) and a password and should return a valid T value or an error describing the user authentication or verification reason of failure.

The first input argument standard context can be casted to iris.Context if executed through Auth.SigninHandler.

It's called on Auth.SigninHandler.

func (*UserProvider) SigninByIdentifier

func (s *UserProvider) SigninByIdentifier(ctx stdContext.Context, appClient *oauth2.Client, identifier string) (*oauth2.Token, error)

SigninByIdentifier accepts a username or ID and should return a valid oauth2 Token which holds the T value or an error describing the user authentication or verification reason of failure.

func (*UserProvider) Signup

func (s *UserProvider) Signup(ctx stdContext.Context, appClient *oauth2.Client, newUser entity.User) (*oauth2.Token, string, error)

Signup accepts a username, an encrypted password and optional attributes and should return a valid OAuth2 Token which holds the User value or an error describing

func (*UserProvider) UpdateUsers

func (s *UserProvider) UpdateUsers(ctx stdContext.Context, updateableUsers []entity.UpdateableUser, columns ...string) (int64, error)

func (*UserProvider) UpdateUsersPartial

func (s *UserProvider) UpdateUsersPartial(ctx stdContext.Context, updates []entity.PartialUpdateSpec) (int64, error)

UpdateUsersPartial performs partial updates on the core feilds and 'attrs' JSONB column for multiple users. It supports merging new attributes, setting specific paths, and removing paths.

func (*UserProvider) ValidateToken

func (p *UserProvider) ValidateToken(ctx stdContext.Context, standardClaims auth.StandardClaims, t entity.FlatUser) error

ValidateToken accepts the standard JWT claims and the T value obtained by the Signin method and should return a nil error on validation success or a non-nil error for validation failure. It is mostly used to perform checks of the T value's struct fields or the standard claim's (e.g. origin jwt token id). It can be an empty method too which returns a nil error.

The first input argument standard context can be casted to iris.Context if executed through Auth.VerifyHandler.

It's caleld on Auth.VerifyHandler.

func (*UserProvider) VerifyPasswordResetToken

func (s *UserProvider) VerifyPasswordResetToken(ctx stdContext.Context, token string) (entity.FlatUser, error)

VerifyPasswordResetToken verifies the password reset token and returns the associated user.

type UserRequestPasswordResetRequest

type UserRequestPasswordResetRequest struct {
	IdentifierRequest
	MaxAgeSeconds int64 `json:"max_age_seconds,omitzero"` // optional, max age of the token in seconds, defaults to 1 hour (3600).
}

UserRequestPasswordResetRequest is the request body for the password reset request endpoint.

type UserRestoreRequest

type UserRestoreRequest = IdentifierRequest

UserRestoreRequest is the request body for the restore endpoint.

type UserSchema

type UserSchema struct {
	Attrs []*UserAttribute `json:"attrs,omitempty"` // List of user attributes with their types and validation rules.
	// contains filtered or unexported fields
}

UserSchema describes the schema for user attributes, including validation rules and database indexes.

func NewUserSchema

func NewUserSchema() *UserSchema

NewUserSchema creates a new UserSchema instance. It initializes the fieldValidators map to store custom field validators. This validator is used to validate user attributes based on the provided JSON schema. Note that if a user validator exists for an attribute but it's missing, it's considered a required one.

func (*UserSchema) GetDatabaseIndexes

func (s *UserSchema) GetDatabaseIndexes() []string

GetDatabaseIndexes returns the list of database indexes for the user attributes.

func (*UserSchema) HasRules

func (s *UserSchema) HasRules() bool

HasRules checks if the UserSchema has any validation rules defined.

func (*UserSchema) IsPrivileged

func (s *UserSchema) IsPrivileged(name string) bool

IsPrivileged reports whether name is a privileged attribute.

func (*UserSchema) Set

func (s *UserSchema) Set(field string, validator ValueValidatorFunc) *UserSchema

Set adds a custom validator for a specific field. The field is the key in the JSON schema, and the validator is a function that takes a value and returns an error if the value is invalid.

func (*UserSchema) SetBool

func (s *UserSchema) SetBool(field string) *UserSchema

SetBool adds a validator for a boolean field. It accepts a boolean value or a string representation of a boolean ("true" or "false"). If the value is nil it is considered valid, unless the field was marked as required through SetRequired, in which case a "missing required field" error is returned.

func (*UserSchema) SetDate

func (s *UserSchema) SetDate(field string, minYear, maxYear int) *UserSchema

SetDate adds a validator for a date field with specified minimum and maximum years. The date should be in the format YYYY-MM-DD.

func (*UserSchema) SetEmail

func (s *UserSchema) SetEmail(field string) *UserSchema

SetEmail adds a validator for an email field.

func (*UserSchema) SetIndex

func (s *UserSchema) SetIndex(field string) *UserSchema

SetIndex adds a field to the list of database indexes. It is a no-op if no validator has been registered for that field yet, so call Set/SetText/SetEmail (and so on) for the field first.

func (*UserSchema) SetMap

func (s *UserSchema) SetMap(field string, requiredKeys []string) *UserSchema

SetMap adds a validator for a map field. The field should be a map[string]any and the requiredKeys, if any, are the keys the map is checked to contain. If requiredKeys is empty then nothing is validated at all, not even the map type, and any value is accepted. Otherwise, if the value is a byte slice or json.RawMessage, it will be unmarshaled into a map, and if the value is not a map, cannot be unmarshaled into a map or misses one of the requiredKeys, an error is returned.

func (*UserSchema) SetNumber

func (s *UserSchema) SetNumber(field string, min, max float64) *UserSchema

SetNumber adds a validator for a numeric field with specified minimum and maximum values.

func (*UserSchema) SetPhone

func (s *UserSchema) SetPhone(field string, format string) *UserSchema

SetPhone adds a validator for a phone field with optional phone format type.

func (*UserSchema) SetRequired

func (s *UserSchema) SetRequired(field string) *UserSchema

SetRequired adds a field to the list of required fields. It is a no-op if no validator has been registered for that field yet, so call Set/SetText/SetEmail (and so on) for the field first.

func (*UserSchema) SetSlice

func (s *UserSchema) SetSlice(field string, sliceType string, minLength, maxLength int) *UserSchema

SetSlice adds a validator for a slice field. The field should be a slice of a specific type (e.g., []string, []int, etc.). The sliceType parameter specifies the expected type of the slice elements. If sliceType is empty, it defaults to "any", meaning the slice can contain any type of elements.

Available slice types: - text: a slice of strings - number: a slice of floats or integers. - bool: a slice of booleans - any: a slice of any type (any) If sliceType is empty, it defaults to "any".

func (*UserSchema) SetText

func (s *UserSchema) SetText(field string, minLength, maxLength int) *UserSchema

SetText adds a validator for a string field with specified minimum and maximum length.

func (*UserSchema) SetUUID

func (s *UserSchema) SetUUID(field string) *UserSchema

SetUUID adds a validator for a UUIDv4 field.

func (*UserSchema) Validate

func (s *UserSchema) Validate(attrs json.RawMessage) error

Validate validates the user attributes against the defined schema. It checks for the presence of required fields, validates their types, and applies custom validators. Only registered fields and the system's ReservedUserFields are accepted; any other unregistered field will cause validation to fail. If the schema has no rules at all then Validate returns nil without any check.

type UserSigninRequest

type UserSigninRequest = IdentifierRequest

UserSigninRequest is the request body for the signin endpoint.

type UserTokenEnrichmentRequest

type UserTokenEnrichmentRequest struct {
	AccessToken string         `json:"access_token"`
	ExtraClaims map[string]any `json:"extra_claims"` // additional claims to be added to the token.

}

type ValueValidatorFunc

type ValueValidatorFunc = func(value any) error

ValueValidatorFunc is a function type that validates a value against a specific condition. It returns an error if the value is invalid, or nil if it is valid.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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