model

package
v2.8.2 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2023 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TFAStatusMandatory = "mandatory" // TFAStatusMandatory for mandatory TFA for all users.
	TFAStatusOptional  = "optional"  // TFAStatusOptional for TFA that can be enabled/disabled for particular user.
	TFAStatusDisabled  = "disabled"  // TFAStatusDisabled is when the app does not support TFA.
)
View Source
const (
	TokenPayloadServiceNone   = "none"   // TokenPayloadServiceNone no service is used
	TokenPayloadServicePlugin = "plugin" // TokenPayloadServicePlugin user local identifo plugin with specific name to retreive token payload
	TokenPayloadServiceHttp   = "http"   // TokenPayloadServiceHttp use external service to get token paylad
)
View Source
const (
	// ErrorInternal represents internal server error, used to mask real internal problem.
	ErrorInternal = Error("internal error")
	// ErrorNotFound is a general not found error.
	ErrorNotFound = Error("not found")
	// ErrorWrongDataFormat is for corrupted request data.
	ErrorWrongDataFormat = Error("wrong data format")
	// ErrorUserExists is for unwanted user entry presense.
	ErrorUserExists = Error("User already exists")
	// ErrorNotImplemented is for features that are not implemented yet.
	ErrorNotImplemented = Error("Not implemented")

	// ErrorPasswordShouldHave6Letters is for failed password strength check.
	ErrorPasswordShouldHave6Letters = Error("Password should have at least six letters")
	// ErrorPasswordNoUppercase is for failed password strength check.
	ErrorPasswordNoUppercase = Error("Password should have at least one uppercase symbol")
	// ErrorPasswordWrongSymbols is for failed password strength check.
	ErrorPasswordWrongSymbols = Error("Password contains wrong symbols")
)
View Source
const (
	// SessionStorageMem means to store sessions in memory.
	SessionStorageMem = "memory"
	// SessionStorageRedis means to store sessions in Redis.
	SessionStorageRedis = "redis"
	// SessionStorageDynamoDB means to store sessions in DynamoDB.
	SessionStorageDynamoDB = "dynamo"
)
View Source
const (
	// EmailServiceMailgun is a Mailgun service.
	EmailServiceMailgun = "mailgun"
	// EmailServiceAWS is an AWS SES service.
	EmailServiceAWS = "ses"
	// EmailServiceMock is an email service mock.
	EmailServiceMock = "mock"
)
View Source
const (
	TokenTypeInvite     = "invite"      // TokenTypeInvite is an invite token type value.
	TokenTypeReset      = "reset"       // TokenTypeReset is an reset token type value.
	TokenTypeWebCookie  = "web-cookie"  // TokenTypeWebCookie is a web-cookie token type value.
	TokenTypeAccess     = "access"      // TokenTypeAccess is an access token type.
	TokenTypeRefresh    = "refresh"     // TokenTypeRefresh is a refresh token type.
	TokenTypeTFAPreauth = "2fa-preauth" // TokenTypeTFAPreauth is an 2fa preauth token type.
)
View Source
const AppleFilesDefaultPath string = "./apple"
View Source
const (
	IdentifoConfigPathEnvName = "IDENTIFO_CONFIG"
)
View Source
const (
	// OfflineScope is a scope value to request refresh token.
	OfflineScope = "offline"
)
View Source
const PrivateKeyName = "private.pem"

Key names.

View Source
const (

	// RouteMobileRegionUAE is a regional UAE RouteMobileR platform.
	RouteMobileRegionUAE = "uae"
)

Variables

View Source
var (
	// ErrWrongSignatureAlgorithm is for unsupported signature algorithm.
	ErrWrongSignatureAlgorithm = errors.New("Unsupported signature algorithm")
	// ErrEmptyToken is when token is empty.
	ErrEmptyToken = errors.New("Token is empty")
	// ErrTokenInvalid is when token is invalid.
	ErrTokenInvalid = errors.New("Token is invalid")
)
View Source
var (
	// EmailRegexp is a regexp which all valid emails must match.
	EmailRegexp = regexp.MustCompile(`^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$`)
	// PhoneRegexp is a regexp which all valid phone numbers must match.
	PhoneRegexp = regexp.MustCompile(`^[\+][0-9]{9,15}$`)
)
View Source
var AppleFilenames = AppleFiles{
	DeveloperDomainAssociation: "apple-developer-domain-association.txt",
	AppSiteAssociation:         "apple-app-site-association",
}

AppleFilenames are names of the files related to Apple services.

View Source
var DefaultCors = cors.Options{AllowedHeaders: []string{"*", "x-identifo-clientid"}, AllowedMethods: []string{"HEAD", "GET", "POST", "PUT", "PATCH", "DELETE"}, AllowCredentials: true}
View Source
var DefaultLoginWebAppSettings = LoginWebAppSettings{
	LoginURL:         "/web",
	RegisterURL:      "/web/register",
	ResetPasswordURL: "/web/password/reset",
	ConfirmEmailURL:  "/web/email_confirm",
	ErrorURL:         "/web/misconfiguration",
	TFADisableURL:    "/web/tfa/disable",
	TFAResetURL:      "/web/tfa/reset",
	WelcomePageURL:   "/web/welcome",
}

DefaultLoginWebAppSettings default settings for self-hosted SPA login app by Identifo.

View Source
var DefaultServerSettings = ServerSettings{
	General: GeneralServerSettings{
		Host:   "http://localhost:8081",
		Port:   "8081",
		Issuer: "Identifo",
	},
	Storage: StorageSettings{
		DefaultStorage:          DatabaseSettings{Type: DBTypeMem},
		AppStorage:              DatabaseSettings{Type: DBTypeDefault},
		UserStorage:             DatabaseSettings{Type: DBTypeDefault},
		TokenStorage:            DatabaseSettings{Type: DBTypeDefault},
		TokenBlacklist:          DatabaseSettings{Type: DBTypeDefault},
		VerificationCodeStorage: DatabaseSettings{Type: DBTypeDefault},
		InviteStorage:           DatabaseSettings{Type: DBTypeDefault},
		ManagementKeysStorage:   DatabaseSettings{Type: DBTypeDefault},
	},
	SessionStorage: SessionStorageSettings{
		Type:            SessionStorageMem,
		SessionDuration: SessionDuration{Duration: time.Second * 300},
	},
	KeyStorage: FileStorageSettings{
		Type: FileStorageTypeLocal,
		Local: FileStorageLocal{
			Path: "./jwt/test_artifacts/private.pem",
		},
	},
	Login: LoginSettings{
		LoginWith: LoginWith{
			Phone:         true,
			Username:      true,
			Federated:     false,
			FederatedOIDC: false,
		},
		TFAType:          TFATypeApp,
		TFAResendTimeout: 30,
	},
	Services: ServicesSettings{
		Email: EmailServiceSettings{
			Type: EmailServiceMock,
		},
		SMS: SMSServiceSettings{
			Type: SMSServiceMock,
		},
	},
	AdminPanel:     AdminPanelSettings{Enabled: true},
	LoginWebApp:    FileStorageSettings{Type: FileStorageTypeNone},
	EmailTemplates: FileStorageSettings{Type: FileStorageTypeNone},
	AdminAccount: AdminAccountSettings{
		LoginEnvName:    "IDENTIFO_ADMIN_LOGIN",
		PasswordEnvName: "IDENTIFO_ADMIN_PASSWORD",
	},
}

Default Server Settings settings

View Source
var ErrSessionNotFound = errors.New("Session not found. ")

ErrSessionNotFound is when session not found.

View Source
var ErrUserNotFound = errors.New("User not found. ")

ErrUserNotFound is when user not found.

View Source
var FederatedProviders = map[string]FederatedProvider{
	"facebook": {Name: "Facebook", New: func(params map[string]string, redirectURL string, scopes ...string) (*facebook.Provider, error) {
		return facebook.New(params["ClientId"], params["Secret"], redirectURL, scopes...), nil
	}, Params: []string{"ClientId", "Secret"}},
	"google": {Name: "Google", New: func(params map[string]string, redirectURL string, scopes ...string) (*google.Provider, error) {
		return google.New(params["ClientId"], params["Secret"], redirectURL, scopes...), nil
	}, Params: []string{"ClientId", "Secret"}},
	"apple": {Name: "Apple", New: func(params map[string]string, redirectURL string, scopes ...string) (*apple.Provider, error) {
		jwt.TimeFunc = func() time.Time {
			return time.Now().Add(time.Second * 10)
		}

		secret, err := apple.MakeSecret(apple.SecretParams{
			PKCS8PrivateKey: params["PKCS8PrivateKey"],
			TeamId:          params["TeamId"],
			KeyId:           params["KeyId"],
			ClientId:        params["ClientId"],
			Iat:             int(time.Now().Unix()),

			Exp: int(time.Now().Unix()) + 10*60,
		})
		if err != nil {
			return nil, err
		}
		return apple.New(params["ClientId"], *secret, redirectURL, nil, scopes...), nil
	}, Params: []string{"ClientId", "PKCS8PrivateKey,textarea", "TeamId", "KeyId"}},
}

StrToTokenSignAlg maps string token service algorithm names to values.

Functions

func AllEmailTemplatesFileNames

func AllEmailTemplatesFileNames() []string

func MergeScopes

func MergeScopes(allowed, def, requested []string) []string

we have three sets of scopes allowed - the list of scopes allowed for app def - default list of scopes for the new user requested - requested list of scopes for new user

func NewTokenWithClaims

func NewTokenWithClaims(method jwt.SigningMethod, kid string, claims jwt.Claims) *jwt.Token

NewTokenWithClaims generates new JWT token with claims and keyID.

func PasswordHash

func PasswordHash(pwd string) string

PasswordHash creates hash with salt for password.

func RandomPassword

func RandomPassword(length int) string

RandomPassword creates random password

func ReqestedScopesApply

func ReqestedScopesApply(user, requested []string) []string

merge two sets of scopes for requested scope we have three sets of scopes user - the list of scopes user has requested - requested list of scopes for key

func SliceContains

func SliceContains(s []string, e string) bool

func SliceExcluding added in v2.3.2

func SliceExcluding(a []string, exclude string) []string

func SliceIntersect

func SliceIntersect(a, b []string) []string

simple intersection of two slices, with complexity: O(n^2) there is better algorithms around, this one is simple and scopes are usually 1-3 items in it

func StrongPswd

func StrongPswd(pswd string) error

StrongPswd validates password

Types

type AdminAccountSettings

type AdminAccountSettings struct {
	LoginEnvName    string `yaml:"loginEnvName" json:"login_env_name"`
	PasswordEnvName string `yaml:"passwordEnvName" json:"password_env_name"`
}

AdminAccountSettings are names of environment variables that store admin credentials.

type AdminPanelSettings

type AdminPanelSettings struct {
	Enabled bool `json:"enabled" yaml:"enabled"`
}

func (*AdminPanelSettings) Validate

func (kss *AdminPanelSettings) Validate() error

type AppData

type AppData struct {
	ID                   string               `bson:"_id" json:"id"` // TODO: use string?
	Secret               string               `bson:"secret" json:"secret"`
	Active               bool                 `bson:"active" json:"active"`
	Name                 string               `bson:"name" json:"name"`
	Description          string               `bson:"description" json:"description"`
	Scopes               []string             `bson:"scopes" json:"scopes"`   // Scopes is the list of all allowed scopes. If it's empty, no limitations (opaque scope).
	Offline              bool                 `bson:"offline" json:"offline"` // Offline is a boolean value that indicates whether on not the app supports refresh tokens. Do not use refresh tokens with apps that does not have secure storage.
	Type                 AppType              `bson:"type" json:"type"`
	RedirectURLs         []string             `bson:"redirect_urls" json:"redirect_urls"`           // RedirectURLs is the list of allowed urls where user will be redirected after successful login. Useful not only for web apps, mobile and desktop apps could use custom scheme for that.
	LoginAppSettings     *LoginWebAppSettings `bson:"login_app_settings" json:"login_app_settings"` // Rewrite login app settings for custom login, reset password and other settings
	TFAStatus            TFAStatus            `bson:"tfa_status" json:"tfa_status"`
	DebugTFACode         string               `bson:"debug_tfa_code" json:"debug_tfa_code"`
	CustomEmailTemplates bool                 `bson:"customEmailTemplates" json:"customEmailTemplates"`

	// Authorization
	AuthzWay       AuthorizationWay `bson:"authorization_way" json:"authorization_way"`
	AuthzModel     string           `bson:"authorization_model" json:"authorization_model"`
	AuthzPolicy    string           `bson:"authorization_policy" json:"authorization_policy"`
	RolesWhitelist []string         `bson:"roles_whitelist" json:"roles_whitelist"`
	RolesBlacklist []string         `bson:"roles_blacklist" json:"roles_blacklist"`

	// Token settings
	TokenLifespan                     int64                                `bson:"token_lifespan" json:"token_lifespan"`                 // TokenLifespan is a token lifespan in seconds, if 0 - default one is used.
	InviteTokenLifespan               int64                                `bson:"invite_token_lifespan" json:"invite_token_lifespan"`   // InviteTokenLifespan a inviteToken lifespan in seconds, if 0 - default one is used.
	RefreshTokenLifespan              int64                                `bson:"refresh_token_lifespan" json:"refresh_token_lifespan"` // RefreshTokenLifespan is a refreshToken lifespan in seconds, if 0 - default one is used.
	TokenPayload                      []string                             `bson:"token_payload" json:"token_payload"`                   // Payload is a list of fields that are included in token. If it's empty, there are no fields in payload.
	TokenPayloadService               TokenPayloadServiceType              `json:"token_payload_service" bson:"token_payload_service"`
	TokenPayloadServicePluginSettings TokenPayloadServicePluginSettings    `json:"token_payload_service_plugin_settings" bson:"token_payload_service_plugin_settings"`
	TokenPayloadServiceHttpSettings   TokenPayloadServiceHttpSettings      `json:"token_payload_service_http_settings" bson:"token_payload_service_http_settings"`
	FederatedProviders                map[string]FederatedProviderSettings `json:"federated_login_settings" bson:"federated_login_settings"`
	OIDCSettings                      OIDCSettings                         `json:"oidc_settings" bson:"oidc_settings"`

	// registration settings
	RegistrationForbidden        bool     `bson:"registration_forbidden" json:"registration_forbidden"`
	AnonymousRegistrationAllowed bool     `bson:"anonymous_registration_allowed" json:"anonymous_registration_allowed"`
	NewUserDefaultRole           string   `bson:"new_user_default_role" json:"new_user_default_role"`
	NewUserDefaultScopes         []string `bson:"new_user_default_scopes" json:"new_user_default_scopes"`
}

AppData represents Application data information.

func AppDataFromJSON

func AppDataFromJSON(d []byte) (AppData, error)

AppDataFromJSON unmarshal AppData from JSON string

func (AppData) GetCustomEmailTemplatePath added in v2.2.24

func (a AppData) GetCustomEmailTemplatePath() string

func (AppData) Sanitized

func (a AppData) Sanitized() AppData

type AppStorage

type AppStorage interface {
	AppByID(id string) (AppData, error)
	ActiveAppByID(appID string) (AppData, error)
	CreateApp(app AppData) (AppData, error)
	DisableApp(app AppData) error
	UpdateApp(appID string, newApp AppData) (AppData, error)
	FetchApps(filter string) ([]AppData, error)
	DeleteApp(id string) error
	ImportJSON(data []byte, cleanOldData bool) error
	TestDatabaseConnection() error
	Close()
}

AppStorage is an abstract representation of applications data storage.

type AppType

type AppType string

AppType is a type of application.

const (
	Web     AppType = "web"     // Web is a web app.
	Android AppType = "android" // Android is an Android app.
	IOS     AppType = "ios"     // IOS is an iOS app.
	Desktop AppType = "desktop" // Desktop is a desktop app.
)

type AppleFiles

type AppleFiles struct {
	DeveloperDomainAssociation string `yaml:"developerDomainAssociation" json:"developer_domain_association"`
	AppSiteAssociation         string `yaml:"appSiteAssociation" json:"app_site_association"`
}

AppleFiles holds together static files needed for supporting Apple services.

type AuthorizationWay

type AuthorizationWay string

AuthorizationWay is a way of authorization supported by the application.

const (
	NoAuthz        AuthorizationWay = "no authorization" // NoAuthz is when the app does not require any authorization.
	Internal       AuthorizationWay = "internal"         // Internal is for embedded authorization rules.
	RolesWhitelist AuthorizationWay = "whitelist"        // RolesWhitelist is the list of roles allowed to register and login into the application.
	RolesBlacklist AuthorizationWay = "blacklist"        // RolesBlacklist is the list of roles forbidden to register and login into the application.
	External       AuthorizationWay = "external"         // External is for external authorization service.
)

type BoltDBDatabaseSettings

type BoltDBDatabaseSettings struct {
	Path string `yaml:"path" json:"path"`
}

type Claims

type Claims struct {
	Payload map[string]interface{} `json:"payload,omitempty"`
	Scopes  string                 `json:"scopes,omitempty"`
	Type    string                 `json:"type,omitempty"`
	KeyID   string                 `json:"kid,omitempty"` // optional keyID
	jwt.StandardClaims
}

Claims is an extended claims structure.

type ConfigurationStorage

type ConfigurationStorage interface {
	WriteConfig(ServerSettings) error
	LoadServerSettings(validate bool) (ServerSettings, []error)
	LoadedSettings() *ServerSettings
	Errors() []error
	GetUpdateChan() chan interface{}
	CloseUpdateChan()

	// ForceReloadOnWriteConfig function returns the bool
	// if true - after WriteConfig we need to force reload server to apply the changes
	// if false - we don't need force reload server, because the watcher will reload the server instantly
	// for example S3 storage uses 1  mins polling, and to apply  new changes instantly we need to force restart the server
	// for file storage we don't need to force reload it. The file watcher will notify about file change instantly
	ForceReloadOnWriteConfig() bool
}

ConfigurationStorage stores server configuration.

type ConfigurationWatcher

type ConfigurationWatcher interface {
	Watch()
	IsWatching() bool
	WatchChan() <-chan []string
	ErrorChan() <-chan error
	Stop()
}

ConfigurationWatcher is a server configuration watcher.

type ConnectionTester

type ConnectionTester interface {
	Connect() error
}

type ContextKey

type ContextKey int

ContextKey enumerates all context keys

const (
	//AppDataContextKey context key to keep requested app data
	AppDataContextKey ContextKey = iota + 1
	//TokenContextKey bearer token context key
	TokenContextKey
	//TokenRawContextKey bearer token context key in raw format
	TokenRawContextKey
)

type DatabaseSettings

type DatabaseSettings struct {
	Type   DatabaseType           `yaml:"type" json:"type"`
	BoltDB BoltDBDatabaseSettings `yaml:"boltdb" json:"boltdb"`
	Mongo  MongoDatabaseSettings  `yaml:"mongo" json:"mongo"`
	Dynamo DynamoDatabaseSettings `yaml:"dynamo" json:"dynamo"`
	Plugin PluginSettings         `yaml:"plugin" json:"plugin"`
	GRPC   GRPCSettings           `yaml:"grpc" json:"grpc"`
}

DatabaseSettings holds together all settings applicable to a particular database.

func (*DatabaseSettings) UnmarshalJSON added in v2.3.3

func (ds *DatabaseSettings) UnmarshalJSON(b []byte) error

func (*DatabaseSettings) Validate

func (dbs *DatabaseSettings) Validate() error

Validate validates database settings.

type DatabaseType

type DatabaseType string

DatabaseType is a type of database.

const (
	DBTypeDefault  DatabaseType = "default" // DBTypeDefault it means the settings should be referenced from default database settings.
	DBTypeBoltDB   DatabaseType = "boltdb"  // DBTypeBoltDB is for BoltDB.
	DBTypeMongoDB  DatabaseType = "mongo"   // DBTypeMongoDB is for MongoDB.
	DBTypeDynamoDB DatabaseType = "dynamo"  // DBTypeDynamoDB is for DynamoDB.
	DBTypeFake     DatabaseType = "fake"    // DBTypeFake is return some predefined const data.
	DBTypeMem      DatabaseType = "mem"     // DBTypeMem is for in-memory storage.
	DBTypePlugin   DatabaseType = "plugin"  // DBTypePlugin is used for hashicorp/go-plugin.
	DBTypeGRPC     DatabaseType = "grpc"    // DBTypeGRPC is used for pure grpc.
)

type DynamoDBSessionStorageSettings

type DynamoDBSessionStorageSettings struct{}

type DynamoDatabaseSettings

type DynamoDatabaseSettings struct {
	Region   string `yaml:"region" json:"region"`
	Endpoint string `yaml:"endpoint" json:"endpoint"`
}

type EmailData

type EmailData struct {
	User User
	Data interface{}
}

type EmailService

type EmailService interface {
	SendTemplateEmail(emailType EmailTemplateType, subfolder, subject, recipient string, data EmailData) error
	Transport() EmailTransport
	Start()
	Stop()
}

EmailService manages sending emails.

type EmailServiceSettings

type EmailServiceSettings struct {
	Type    EmailServiceType            `yaml:"type" json:"type"`
	Mailgun MailgunEmailServiceSettings `yaml:"mailgun" json:"mailgun"`
	SES     SESEmailServiceSettings     `yaml:"ses" json:"ses"`
}

EmailServiceSettings holds together settings for the email service.

func (*EmailServiceSettings) Validate

func (ess *EmailServiceSettings) Validate() []error

Validate validates email service settings.

type EmailServiceType

type EmailServiceType string

EmailServiceType - how to send email to clients.

type EmailTemplateType

type EmailTemplateType string
const (
	EmailTemplateTypeInvite        EmailTemplateType = "invite-email"
	EmailTemplateTypeResetPassword EmailTemplateType = "reset-password-email"
	EmailTemplateTypeTFAWithCode   EmailTemplateType = "tfa-code-email"
	EmailTemplateTypeVerifyEmail   EmailTemplateType = "verify-email"

	DefaultTemplateExtension = "html"
)

func (EmailTemplateType) FileName

func (t EmailTemplateType) FileName() string

func (EmailTemplateType) String

func (t EmailTemplateType) String() string

type EmailTransport

type EmailTransport interface {
	SendMessage(subject, body, recipient string) error
	SendHTML(subject, html, recipient string) error
}

type Error

type Error string

Error - domain level error type

func (Error) Error

func (e Error) Error() string

Error - implementation of std.Error protocol

type FederatedProvider

type FederatedProvider struct {
	New           interface{} `bson:"-" json:"-"`
	Name          string      `bson:"string,omitempty" json:"string,omitempty"`
	DefaultScopes []string    `bson:"default_scopes,omitempty" json:"default_scopes,omitempty"`
	Params        []string    `bson:"params,omitempty" json:"params,omitempty"`
}

type FederatedProviderSettings

type FederatedProviderSettings struct {
	Params map[string]string `bson:"params,omitempty" json:"params,omitempty"`
	Scopes []string          `bson:"scopes,omitempty" json:"scopes,omitempty"`
}

type FederatedSession

type FederatedSession struct {
	ProviderSession string
	AuthUrl         string
	CallbackUrl     string
	RedirectUrl     string
	AppId           string
	ProviderName    string
	Scopes          []string
}

Session stores data during the auth process with Google.

func UnmarshalFederatedSession

func UnmarshalFederatedSession(data string) (*FederatedSession, error)

UnmarshalSession will unmarshal a JSON string into a session.

func (FederatedSession) Marshal

func (s FederatedSession) Marshal() string

Marshal the session into a string

func (FederatedSession) String

func (s FederatedSession) String() string

type FileStorageLocal

type FileStorageLocal struct {
	Path string `yaml:"path" json:"path"`
}

type FileStorageS3

type FileStorageS3 struct {
	Region   string `yaml:"region" json:"region"`
	Bucket   string `yaml:"bucket" json:"bucket"`
	Key      string `yaml:"key" json:"key"`
	Endpoint string `yaml:"endpoint" json:"endpoint"`
}

type FileStorageSettings

type FileStorageSettings struct {
	Type  FileStorageType  `yaml:"type" json:"type"`
	Local FileStorageLocal `yaml:"local,omitempty" json:"local,omitempty"`
	S3    FileStorageS3    `yaml:"s3,omitempty" json:"s3,omitempty"`
}

func ConfigStorageSettingsFromString

func ConfigStorageSettingsFromString(config string) (FileStorageSettings, error)

func ConfigStorageSettingsFromStringFile

func ConfigStorageSettingsFromStringFile(config string) (FileStorageSettings, error)

func ConfigStorageSettingsFromStringS3

func ConfigStorageSettingsFromStringS3(config string) (FileStorageSettings, error)

func (FileStorageSettings) Dir added in v2.3.0

func (fs FileStorageSettings) Dir() string

if key or path has folder and filename joined, this function returns path part only

func (FileStorageSettings) FileName added in v2.3.0

func (fs FileStorageSettings) FileName() string

if key or path has folder and filename joined, this function returns filename part only

func (*FileStorageSettings) Validate

func (sfs *FileStorageSettings) Validate() []error

Validate validates login web app settings

type FileStorageType

type FileStorageType string
const (
	FileStorageTypeNone    FileStorageType = "none"
	FileStorageTypeDefault FileStorageType = "default"
	FileStorageTypeLocal   FileStorageType = "local"
	FileStorageTypeS3      FileStorageType = "s3"
)

type GRPCSettings added in v2.2.14

type GRPCSettings struct {
	Address string `yaml:"address" json:"address"`
}

type GeneralServerSettings

type GeneralServerSettings struct {
	Locale          string   `yaml:"locale" json:"locale"`
	Host            string   `yaml:"host" json:"host"`
	Port            string   `yaml:"port" json:"port"`
	Issuer          string   `yaml:"issuer" json:"issuer"`
	SupportedScopes []string `yaml:"supported_scopes" json:"supported_scopes"`
}

GeneralServerSettings are general server settings.

func (*GeneralServerSettings) Validate

func (gss *GeneralServerSettings) Validate() []error

Validate validates general services settings.

type Invite

type Invite struct {
	ID        string    `json:"id" bson:"_id"`
	AppID     string    `json:"appId" bson:"appId"`
	Token     string    `json:"token" bson:"token"`
	Archived  bool      `json:"archived" bson:"archived"`
	Email     string    `json:"email" bson:"email"`
	Role      string    `json:"role" bson:"role"`
	CreatedBy string    `json:"createdBy" bson:"createdBy"`
	CreatedAt time.Time `json:"createdAt" bson:"createdAt"`
	ExpiresAt time.Time `json:"expiresAt" bson:"expiresAt"`
}

Invite is a representation of the invite model. Token field is required for proper working.

func (Invite) Validate

func (i Invite) Validate() error

Validate validates the Invite model.

type InviteStorage

type InviteStorage interface {
	Save(email, inviteToken, role, appID, createdBy string, expiresAt time.Time) error
	GetByEmail(email string) (Invite, error)
	GetByID(id string) (Invite, error)
	GetAll(withArchived bool, skip, limit int) ([]Invite, int, error)
	ArchiveAllByEmail(email string) error
	ArchiveByID(id string) error
	Close()
}

InviteStorage is a storage for invites.

type JWTKeys

type JWTKeys struct {
	Public  interface{}
	Private interface{}
}

JWTKeys are keys used for signing and verifying JSON web tokens.

type JWToken

type JWToken struct {
	JWT *jwt.Token
	New bool
}

JWToken represents JWT token.

func (*JWToken) Audience

func (t *JWToken) Audience() string

Audience standard token claim

func (*JWToken) Claims added in v2.3.3

func (t *JWToken) Claims() *Claims

func (*JWToken) ExpiresAt

func (t *JWToken) ExpiresAt() time.Time

ExpiresAt standard token claim

func (*JWToken) ID

func (t *JWToken) ID() string

ID standard token claim

func (*JWToken) IssuedAt

func (t *JWToken) IssuedAt() time.Time

IssuedAt standard token claim

func (*JWToken) Issuer

func (t *JWToken) Issuer() string

Issuer standard token claim

func (*JWToken) NotBefore

func (t *JWToken) NotBefore() time.Time

NotBefore standard token claim

func (*JWToken) Payload

func (t *JWToken) Payload() map[string]interface{}

Payload returns token payload.

func (*JWToken) Scopes

func (t *JWToken) Scopes() string

Scopes standard token claim

func (*JWToken) Subject

func (t *JWToken) Subject() string

Subject standard token claim

func (*JWToken) Type

func (t *JWToken) Type() string

Type returns token type.

func (*JWToken) UserID

func (t *JWToken) UserID() string

UserID returns user ID.

func (*JWToken) Validate

func (t *JWToken) Validate() error

Validate validates token data. Returns nil if all data is valid.

type KeyStorage

type KeyStorage interface {
	ReplaceKey(keyPEM []byte) error
	LoadPrivateKey() (interface{}, error)
}

KeyStorage stores keys used for signing and verifying JWT tokens.

type LoggerSettings

type LoggerSettings struct {
	DumpRequest bool `yaml:"dumpRequest" json:"dumpRequest"`
}

type LoginSettings

type LoginSettings struct {
	LoginWith            LoginWith `yaml:"loginWith" json:"login_with"`
	TFAType              TFAType   `yaml:"tfaType" json:"tfa_type"`
	TFAResendTimeout     int       `yaml:"tfaResendTimeout" json:"tfa_resend_timeout"`
	AllowRegisterMissing bool      `yaml:"allowRegisterMissing" json:"allow_register_missing"`
}

LoginSettings are settings of login.

type LoginWebAppSettings added in v2.3.11

type LoginWebAppSettings struct {
	LoginURL         string `json:"login_url,omitempty" bson:"login_url,omitempty"`
	RegisterURL      string `json:"register_url,omitempty" bson:"register_url,omitempty"`
	ResetPasswordURL string `json:"reset_password_url,omitempty" bson:"reset_password_url,omitempty"`
	ConfirmEmailURL  string `json:"confirm_email_url,omitempty" bson:"confirm_email_url,omitempty"`
	ErrorURL         string `json:"error_url,omitempty" bson:"error_url,omitempty"`
	TFADisableURL    string `json:"tfa_disable_url,omitempty" bson:"tfa_disable_url,omitempty"`
	TFAResetURL      string `json:"tfa_reset_url,omitempty" bson:"tfa_reset_url,omitempty"`
	WelcomePageURL   string `json:"welcome_page_url,omitempty" bson:"welcome_page_url,omitempty"`
}

LoginWebAppSettings settings for login web app: usually it is a SPA app which handles login, register, reset password, etc.

type LoginWith

type LoginWith struct {
	Username      bool `yaml:"username" json:"username"`
	Phone         bool `yaml:"phone" json:"phone"`
	Email         bool `yaml:"email" json:"email"`
	Federated     bool `yaml:"federated" json:"federated"`
	FederatedOIDC bool `yaml:"federatedOIDC" json:"federated_oidc"`
}

LoginWith is a type for configuring supported login ways.

type MailgunEmailServiceSettings

type MailgunEmailServiceSettings struct {
	Domain     string `yaml:"domain" json:"domain"`
	PrivateKey string `yaml:"privateKey" json:"private_key"`
	Sender     string `yaml:"sender" json:"sender"`
}

type ManagementKey added in v2.4.4

type ManagementKey struct {
	ID        string     `json:"id" bson:"_id"`
	Secret    string     `json:"secret" bson:"secret"`
	Name      string     `json:"name" bson:"name"`
	Active    bool       `json:"active" bson:"active"`
	Scopes    []string   `json:"scopes" bson:"scopes"`
	CreatedAt time.Time  `json:"created_at" bson:"createdAt"`
	LastUsed  time.Time  `json:"last_used" bson:"lastUsed"`
	ValidTill *time.Time `json:"valid_till" bson:"validTill"`
}

ManagementKey secret management key to communicate with management api

type ManagementKeysStorage added in v2.4.4

type ManagementKeysStorage interface {
	GetKey(ctx context.Context, id string) (ManagementKey, error)
	CreateKey(ctx context.Context, name string, scopes []string) (ManagementKey, error)
	DisableKey(ctx context.Context, id string) (ManagementKey, error)
	RenameKey(ctx context.Context, id, name string) (ManagementKey, error)
	ChangeScopesForKey(ctx context.Context, id string, scopes []string) (ManagementKey, error)
	UseKey(ctx context.Context, id string) (ManagementKey, error)
	ImportJSON(data []byte, clearOldData bool) error

	GeyAllKeys(ctx context.Context) ([]ManagementKey, error)
}

ManagementKeysStorage storage to persist management keys

type MongoDatabaseSettings added in v2.3.3

type MongoDatabaseSettings struct {
	ConnectionString string `yaml:"connection" json:"connection"`
	DatabaseName     string `yaml:"database" json:"database"`
}

type NexmoServiceSettings

type NexmoServiceSettings struct {
	// Nexmo related config.
	APIKey    string `yaml:"apiKey" json:"api_key"`
	APISecret string `yaml:"apiSecret" json:"api_secret"`
}

type OIDCSettings added in v2.4.0

type OIDCSettings struct {
	ProviderName     string   `bson:"provider_name,omitempty" json:"provider_name,omitempty"`
	ProviderURL      string   `bson:"provider_url,omitempty" json:"provider_url,omitempty"`
	Issuer           string   `bson:"issuer,omitempty" json:"issuer,omitempty"`
	ClientID         string   `bson:"client_id,omitempty" json:"client_id,omitempty"`
	ClientSecret     string   `bson:"client_secret,omitempty" json:"client_secret,omitempty"`
	EmailClaimField  string   `bson:"email_claim_field,omitempty" json:"email_claim_field,omitempty"`
	UserIDClaimField string   `bson:"user_id_claim_field,omitempty" json:"user_id_claim_field,omitempty"`
	Scopes           []string `bson:"scopes,omitempty" json:"scopes,omitempty"`
	InitURL          string   `bson:"init_url,omitempty" json:"init_url,omitempty"`
	// ScopeMapping maps OIDC scopes to Identifo scopes.
	ScopeMapping map[string]string `bson:"scope_mapping,omitempty" json:"scope_mapping,omitempty"`
}

func (OIDCSettings) IsValid added in v2.4.0

func (s OIDCSettings) IsValid() error

type OriginCheckFunc

type OriginCheckFunc func(r *http.Request, origin string) bool

type OriginChecker

type OriginChecker interface {
	AddCheck(f OriginCheckFunc)
	CheckOrigin(r *http.Request, origin string) bool
	Update() error
}

type PluginSettings added in v2.2.14

type PluginSettings struct {
	Cmd    string            `yaml:"cmd" json:"cmd"`
	Params map[string]string `yaml:"params" json:"params"`
}

type RedisDatabaseSettings

type RedisDatabaseSettings struct {
	// host:port address.
	Address string `yaml:"address" json:"address"`
	// Optional password. Must match the password specified in the
	// requirepass server configuration option.
	Password string `yaml:"password" json:"password"`
	// Database to be selected after connecting to the server.
	DB int `yaml:"db" json:"db"`
	// Cluster - if true will connect to redis cluster, address can be comma separated list of addresses.
	Cluster bool `yaml:"cluster" json:"cluster"`
	// Prefix for redis keys
	Prefix string `yaml:"prefix" json:"prefix"`
}

RedisDatabaseSettings redis storage settings

type RouteMobileServiceSettings

type RouteMobileServiceSettings struct {
	// RouteMobile related config.
	Username string `yaml:"username" json:"username"`
	Password string `yaml:"password" json:"password"`
	Source   string `yaml:"source" json:"source"`
	Region   string `yaml:"region" json:"region"`
}

type Router

type Router interface {
	ServeHTTP(http.ResponseWriter, *http.Request)
}

Router handles all incoming http requests.

type SESEmailServiceSettings

type SESEmailServiceSettings struct {
	Region string `yaml:"region" json:"region"`
	Sender string `yaml:"sender" json:"sender"`
}

type SMSService

type SMSService interface {
	SendSMS(recipient, message string) error
}

SMSService is an SMS sending service.

type SMSServiceSettings

type SMSServiceSettings struct {
	Type        SMSServiceType             `yaml:"type" json:"type"`
	Twilio      TwilioServiceSettings      `yaml:"twilio" json:"twilio"`
	Nexmo       NexmoServiceSettings       `yaml:"nexmo" json:"nexmo"`
	Routemobile RouteMobileServiceSettings `yaml:"routemobile" json:"routemobile"`
}

SMSServiceSettings holds together settings for SMS service.

func (*SMSServiceSettings) Validate

func (sss *SMSServiceSettings) Validate() []error

Validate validates SMS service settings.

type SMSServiceType

type SMSServiceType string

SMSServiceType - service for sending sms messages.

const (
	SMSServiceTwilio      SMSServiceType = "twilio"      // SMSServiceTwilio is a Twilio SMS service.
	SMSServiceNexmo       SMSServiceType = "nexmo"       // SMSServiceNexmo is a Nexmo SMS service.
	SMSServiceRouteMobile SMSServiceType = "routemobile" // SMSServiceRouteMobile is a RouteMobile SMS service.
	SMSServiceMock        SMSServiceType = "mock"        // SMSServiceMock is an SMS service mock.
)

type Server

type Server interface {
	Router() Router
	UpdateCORS()
	Storages() ServerStorageCollection
	Services() ServerServices
	Settings() ServerSettings
	Errors() []error
	Close()
}

Server holds together all dependencies.

type ServerServices

type ServerServices struct {
	SMS     SMSService
	Email   EmailService
	Token   TokenService
	Session SessionService
}

type ServerSettings

type ServerSettings struct {
	General        GeneralServerSettings  `yaml:"general" json:"general"`
	AdminAccount   AdminAccountSettings   `yaml:"adminAccount" json:"admin_account"`
	Storage        StorageSettings        `yaml:"storage" json:"storage"`
	SessionStorage SessionStorageSettings `yaml:"sessionStorage" json:"session_storage"`
	Services       ServicesSettings       `yaml:"services" json:"external_services"`
	Login          LoginSettings          `yaml:"login" json:"login"`
	KeyStorage     FileStorageSettings    `yaml:"keyStorage" json:"key_storage"`
	Config         FileStorageSettings    `yaml:"-" json:"config"`
	Logger         LoggerSettings         `yaml:"logger" json:"logger"`
	AdminPanel     AdminPanelSettings     `yaml:"adminPanel" json:"admin_panel"`
	LoginWebApp    FileStorageSettings    `yaml:"loginWebApp" json:"login_web_app"`
	EmailTemplates FileStorageSettings    `yaml:"emailTemplates" json:"email_templates"`
}

ServerSettings are server settings.

func (ServerSettings) GetPort

func (ss ServerSettings) GetPort() string

GetPort returns port on which host listens to incoming connections.

func (*ServerSettings) RewriteDefaults

func (ss *ServerSettings) RewriteDefaults()

Check server settings and apply changes if needed

func (*ServerSettings) Validate

func (ss *ServerSettings) Validate(rewriteDefaults bool) []error

Validate makes sure that all crucial fields are set.

type ServerStorageCollection

type ServerStorageCollection struct {
	App           AppStorage
	User          UserStorage
	Token         TokenStorage
	Blocklist     TokenBlacklist
	Invite        InviteStorage
	Verification  VerificationCodeStorage
	Config        ConfigurationStorage
	Session       SessionStorage
	Key           KeyStorage
	ManagementKey ManagementKeysStorage
	LoginAppFS    fs.FS
	AdminPanelFS  fs.FS
}

ServerStorageCollection holds the full collections of server storage components

type ServicesSettings

type ServicesSettings struct {
	Email EmailServiceSettings `yaml:"email" json:"email_service"`
	SMS   SMSServiceSettings   `yaml:"sms" json:"sms_service"`
}

ServicesSettings are settings for external services.

func (*ServicesSettings) Validate

func (ess *ServicesSettings) Validate() []error

Validate validates external services settings.

type Session

type Session struct {
	ID             string `json:"id"`
	ExpirationTime int64  `json:"expiration_time"`
}

Session is a session.

type SessionDuration

type SessionDuration struct {
	time.Duration
}

SessionDuration wraps time.Duration to implement custom yaml and json encoding and decoding.

func (SessionDuration) MarshalJSON

func (sd SessionDuration) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller.

func (SessionDuration) MarshalYAML

func (sd SessionDuration) MarshalYAML() (interface{}, error)

MarshalYAML implements yaml.Marshaller.

func (*SessionDuration) UnmarshalJSON

func (sd *SessionDuration) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaller.

func (*SessionDuration) UnmarshalYAML

func (sd *SessionDuration) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements yaml Unmarshaller.

type SessionManager

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

SessionManager is a default session service.

func (*SessionManager) NewSession

func (sm *SessionManager) NewSession() (Session, error)

NewSession creates new session and returns it.

func (*SessionManager) ProlongSession

func (sm *SessionManager) ProlongSession(sessionID string) error

ProlongSession prolongs session duration.

func (*SessionManager) SessionDurationSeconds

func (sm *SessionManager) SessionDurationSeconds() int

SessionDurationSeconds returns session duration in seconds.

type SessionService

type SessionService interface {
	NewSession() (Session, error)
	SessionDurationSeconds() int
	ProlongSession(sessionID string) error
}

SessionService manages sessions.

func NewSessionManager

func NewSessionManager(sessionDuration SessionDuration, sessionStorage SessionStorage) SessionService

NewSessionManager creates new session manager and returns it.

type SessionStorage

type SessionStorage interface {
	GetSession(id string) (Session, error)
	InsertSession(session Session) error
	DeleteSession(id string) error
	ProlongSession(id string, newDuration SessionDuration) error
	Close()
}

SessionStorage is an interface for session storage.

type SessionStorageSettings

type SessionStorageSettings struct {
	Type            SessionStorageType     `yaml:"type" json:"type"`
	SessionDuration SessionDuration        `yaml:"sessionDuration" json:"session_duration"`
	Redis           RedisDatabaseSettings  `yaml:"redis" json:"redis"`
	Dynamo          DynamoDatabaseSettings `yaml:"dynamo" json:"dynamo"`
}

SessionStorageSettings holds together session storage settings.

func (*SessionStorageSettings) Validate

func (sss *SessionStorageSettings) Validate() []error

Validate validates admin session storage settings.

type SessionStorageType

type SessionStorageType string

SessionStorageType - where to store admin sessions.

type StandardTokenClaims

type StandardTokenClaims interface {
	Audience() string
	ExpiresAt() time.Time
	ID() string
	IssuedAt() time.Time
	Issuer() string
	NotBefore() time.Time
	Subject() string
}

StandardTokenClaims structured version of Claims Section, as referenced at https://tools.ietf.org/html/rfc7519#section-4.1

type StorageSettings

type StorageSettings struct {
	DefaultStorage          DatabaseSettings `yaml:"default" json:"default"`
	AppStorage              DatabaseSettings `yaml:"appStorage" json:"app_storage"`
	UserStorage             DatabaseSettings `yaml:"userStorage" json:"user_storage"`
	TokenStorage            DatabaseSettings `yaml:"tokenStorage" json:"token_storage"`
	TokenBlacklist          DatabaseSettings `yaml:"tokenBlacklist" json:"token_blacklist"`
	VerificationCodeStorage DatabaseSettings `yaml:"verificationCodeStorage" json:"verification_code_storage"`
	InviteStorage           DatabaseSettings `yaml:"inviteStorage" json:"invite_storage"`
	ManagementKeysStorage   DatabaseSettings `yaml:"managementKeysStorage" json:"management_keys_storage"`
}

StorageSettings holds together storage settings for different services.

func (*StorageSettings) Validate

func (ss *StorageSettings) Validate() []error

Validate validates storage settings.

type TFAInfo

type TFAInfo struct {
	IsEnabled     bool      `json:"is_enabled" bson:"is_enabled"`
	HOTPCounter   int       `json:"hotp_counter" bson:"hotp_counter"`
	HOTPExpiredAt time.Time `json:"hotp_expired_at" bson:"hotp_expired_at"`
	Email         string    `json:"email" bson:"email"`
	Phone         string    `json:"phone" bson:"phone"`
	Secret        string    `json:"secret" bson:"secret"`
}

TFAInfo encapsulates two-factor authentication user info.

type TFAStatus

type TFAStatus string

TFAStatus is how the app supports two-factor authentication.

type TFAType

type TFAType string

TFAType is a type of two-factor authentication for apps that support it.

const (
	TFATypeApp   TFAType = "app"   // TFATypeApp is an app (like Google Authenticator).
	TFATypeSMS   TFAType = "sms"   // TFATypeSMS is an SMS.
	TFATypeEmail TFAType = "email" // TFATypeEmail is an email.
)

type TemplateStorage

type TemplateStorage interface {
	Template(name string) (*template.Template, error)
}

type TestConnection

type TestConnection struct {
	Type        TestType             `json:"type"`
	Database    *DatabaseSettings    `json:"database,omitempty"`
	KeyStorage  *FileStorageSettings `json:"key_storage,omitempty"`
	FileStorage *FileStorageSettings `json:"file_storage,omitempty"`
}

type TestType

type TestType string

TestType is a test type

const (
	TTDatabase             TestType = "database"
	TTKeyStorage           TestType = "key_storage"
	TTSPAFileStorage       TestType = "spa_file_storage"
	TTEmailTemplateStorage TestType = "email_template_file_storage"
)

type Token

type Token interface {
	StandardTokenClaims
	Validate() error
	UserID() string
	Type() string
	Scopes() string
	Payload() map[string]interface{}
}

Token is an abstract application token.

type TokenBlacklist

type TokenBlacklist interface {
	IsBlacklisted(token string) bool
	Add(token string) error
	Close()
}

TokenBlacklist is a storage for blacklisted tokens.

type TokenPayloadProvider

type TokenPayloadProvider interface {
	TokenPayloadForApp(appId, appName, userId string) (map[string]interface{}, error)
}

TokenPayloadProvider provides additional user payload to include to the token

type TokenPayloadServiceHttpSettings

type TokenPayloadServiceHttpSettings struct {
	URL    string `json:"url,omitempty" bson:"url,omitempty"`
	Secret string `json:"secret,omitempty" bson:"secret,omitempty"`
}

TokenPayloadServiceHttpSettings settings for token payload service

type TokenPayloadServicePluginSettings

type TokenPayloadServicePluginSettings struct {
	Name          string            `json:"name" bson:"name,omitempty"`
	Cmd           string            `json:"cmd" bson:"cmd,omitempty"`
	Params        map[string]string `json:"params" bson:"params,omitempty"`
	ClientTimeout time.Duration     `json:"client_timeout" bson:"client_timeout,omitempty"`
}

TokenPayloadServicePluginSettings settings for token payload service

type TokenPayloadServiceType

type TokenPayloadServiceType string

TokenPayloadServiceType service to allow fetch additional data to include to access token

type TokenService

type TokenService interface {
	NewAccessToken(u User, scopes []string, app AppData, requireTFA bool, tokenPayload map[string]interface{}) (Token, error)
	NewRefreshToken(u User, scopes []string, app AppData) (Token, error)
	RefreshAccessToken(token Token, tokenPayload map[string]interface{}) (Token, error)
	NewInviteToken(email, role, audience string, data map[string]interface{}) (Token, error)
	NewResetToken(userID string) (Token, error)
	NewWebCookieToken(u User) (Token, error)
	Parse(string) (Token, error)
	String(Token) (string, error)
	Issuer() string
	Algorithm() string
	WebCookieTokenLifespan() int64

	// keys management
	// replace the old private key with a new one
	SetPrivateKey(key interface{})
	PrivateKey() interface{}
	// not using crypto.PublicKey here to avoid dependencies
	PublicKey() interface{}
	KeyID() string
}

TokenService is an abstract token manager.

type TokenSignatureAlgorithm

type TokenSignatureAlgorithm int

TokenSignatureAlgorithm is a signing algorithm used by the token service. For now, we only support ES256 and RS256.

const (
	// TokenSignatureAlgorithmES256 is a ES256 signature.
	TokenSignatureAlgorithmES256 TokenSignatureAlgorithm = iota + 1
	// TokenSignatureAlgorithmRS256 is a RS256 signature.
	TokenSignatureAlgorithmRS256
	// TokenSignatureAlgorithmError indicates invalid or unsupported algorithm
	TokenSignatureAlgorithmInvalid
)

func (TokenSignatureAlgorithm) MarshalJSON

func (alg TokenSignatureAlgorithm) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller.

func (TokenSignatureAlgorithm) MarshalYAML

func (alg TokenSignatureAlgorithm) MarshalYAML() (interface{}, error)

MarshalYAML implements yaml.Marshaller.

func (TokenSignatureAlgorithm) String

func (alg TokenSignatureAlgorithm) String() string

String implements Stringer.

func (*TokenSignatureAlgorithm) UnmarshalJSON

func (alg *TokenSignatureAlgorithm) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaller.

func (*TokenSignatureAlgorithm) UnmarshalYAML

func (alg *TokenSignatureAlgorithm) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements yaml.Unmarshaller.

type TokenStorage

type TokenStorage interface {
	SaveToken(token string) error
	HasToken(token string) bool
	DeleteToken(token string) error
	Close()
}

TokenStorage is a storage for issued refresh tokens.

type TwilioServiceSettings

type TwilioServiceSettings struct {
	// Twilio related config.
	AccountSid string `yaml:"accountSid" json:"account_sid"`
	AuthToken  string `yaml:"authToken" json:"auth_token"`
	ServiceSid string `yaml:"serviceSid" json:"service_sid"`
	SendFrom   string `yaml:"sendFrom" json:"send_from"`
	Region     string `yaml:"region" json:"region"`
	Edge       string `yaml:"edge" json:"edge"`
}

type User

type User struct {
	ID              string   `json:"id" bson:"_id"`
	Username        string   `json:"username" bson:"username"`
	Email           string   `json:"email" bson:"email"`
	FullName        string   `json:"full_name" bson:"full_name"`
	Phone           string   `json:"phone" bson:"phone"`
	Pswd            string   `json:"pswd" bson:"pswd"`
	Active          bool     `json:"active" bson:"active"`
	TFAInfo         TFAInfo  `json:"tfa_info" bson:"tfa_info"`
	NumOfLogins     int      `json:"num_of_logins" bson:"num_of_logins"`
	LatestLoginTime int64    `json:"latest_login_time" bson:"latest_login_time"`
	AccessRole      string   `json:"access_role" bson:"access_role"`
	Anonymous       bool     `json:"anonymous" bson:"anonymous"`
	FederatedIDs    []string `json:"federated_ids" bson:"federated_i_ds"`
	Scopes          []string `json:"scopes" bson:"scopes"`
}

User is an abstract representation of the user in auth layer. Everything can be User, we do not depend on any particular implementation.

func UserFromJSON

func UserFromJSON(d []byte) (User, error)

UserFromJSON deserialize user data from JSON.

func (*User) AddFederatedId

func (u *User) AddFederatedId(provider string, id string) string

func (User) Deanonimized

func (u User) Deanonimized() User

Deanonimized returns model with all fields set for deanonimized user

func (User) Sanitized

func (u User) Sanitized() User

Sanitized returns data structure without sensitive information

func (User) SanitizedTFA

func (u User) SanitizedTFA() User

SanitizedTFA returns data structure with masked sensitive data

type UserStorage

type UserStorage interface {
	UserByPhone(phone string) (User, error)
	AddUserWithPassword(user User, password, role string, isAnonymous bool) (User, error)
	UserByID(id string) (User, error)
	UserByEmail(email string) (User, error)
	UserByUsername(username string) (User, error)
	UserByFederatedID(provider string, id string) (User, error)
	AddUserWithFederatedID(user User, provider string, id, role string) (User, error)
	UpdateUser(userID string, newUser User) (User, error)
	ResetPassword(id, password string) error
	CheckPassword(id, password string) error
	DeleteUser(id string) error
	FetchUsers(search string, skip, limit int) ([]User, int, error)
	UpdateLoginMetadata(userID string)

	// push device tokens
	AttachDeviceToken(userID, token string) error
	DetachDeviceToken(token string) error
	AllDeviceTokens(userID string) ([]string, error)

	// import data
	ImportJSON(data []byte, clearOldData bool) error

	Close()
}

UserStorage is an abstract user storage.

type VerificationCodeStorage

type VerificationCodeStorage interface {
	IsVerificationCodeFound(phone, code string) (bool, error)
	CreateVerificationCode(phone, code string) error
	Close()
}

VerificationCodeStorage stores verification codes linked to the phone number.

Jump to

Keyboard shortcuts

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