Documentation ¶
Index ¶
- Constants
- Variables
- func AllEmailTemplatesFileNames() []string
- func MergeScopes(allowed, def, requested []string) []string
- func NewTokenWithClaims(method jwt.SigningMethod, kid string, claims jwt.Claims) *jwt.Token
- func PasswordHash(pwd string) string
- func RandomPassword(length int) string
- func ReqestedScopesApply(user, requested []string) []string
- func SliceContains(s []string, e string) bool
- func SliceExcluding(a []string, exclude string) []string
- func SliceIntersect(a, b []string) []string
- func StrongPswd(pswd string) error
- type AdminAccountSettings
- type AdminPanelSettings
- type AppData
- type AppStorage
- type AppType
- type AppleFiles
- type AuthorizationWay
- type BoltDBDatabaseSettings
- type Claims
- type ConfigurationStorage
- type ConfigurationWatcher
- type ConnectionTester
- type ContextKey
- type DatabaseSettings
- type DatabaseType
- type DynamoDBSessionStorageSettings
- type DynamoDatabaseSettings
- type EmailData
- type EmailService
- type EmailServiceSettings
- type EmailServiceType
- type EmailTemplateType
- type EmailTransport
- type Error
- type FederatedProvider
- type FederatedProviderSettings
- type FederatedSession
- type FileStorageLocal
- type FileStorageS3
- type FileStorageSettings
- type FileStorageType
- type GRPCSettings
- type GeneralServerSettings
- type Invite
- type InviteStorage
- type JWTKeys
- type JWToken
- func (t *JWToken) Audience() string
- func (t *JWToken) Claims() *Claims
- func (t *JWToken) ExpiresAt() time.Time
- func (t *JWToken) ID() string
- func (t *JWToken) IssuedAt() time.Time
- func (t *JWToken) Issuer() string
- func (t *JWToken) NotBefore() time.Time
- func (t *JWToken) Payload() map[string]interface{}
- func (t *JWToken) Scopes() string
- func (t *JWToken) Subject() string
- func (t *JWToken) Type() string
- func (t *JWToken) UserID() string
- func (t *JWToken) Validate() error
- type KeyStorage
- type LoggerSettings
- type LoginSettings
- type LoginWith
- type MailgunEmailServiceSettings
- type MongoDatabaseSettings
- type NexmoServiceSettings
- type OriginCheckFunc
- type OriginChecker
- type PluginSettings
- type RedisDatabaseSettings
- type RouteMobileServiceSettings
- type Router
- type SESEmailServiceSettings
- type SMSService
- type SMSServiceSettings
- type SMSServiceType
- type Server
- type ServerServices
- type ServerSettings
- type ServerStorageCollection
- type ServicesSettings
- type Session
- type SessionDuration
- type SessionManager
- type SessionService
- type SessionStorage
- type SessionStorageSettings
- type SessionStorageType
- type StandardTokenClaims
- type StorageSettings
- type TFAInfo
- type TFAStatus
- type TFAType
- type TemplateStorage
- type TestConnection
- type TestType
- type Token
- type TokenBlacklist
- type TokenPayloadProvider
- type TokenPayloadServiceHttpSettings
- type TokenPayloadServicePluginSettings
- type TokenPayloadServiceType
- type TokenService
- type TokenSignatureAlgorithm
- func (alg TokenSignatureAlgorithm) MarshalJSON() ([]byte, error)
- func (alg TokenSignatureAlgorithm) MarshalYAML() (interface{}, error)
- func (alg TokenSignatureAlgorithm) String() string
- func (alg *TokenSignatureAlgorithm) UnmarshalJSON(data []byte) error
- func (alg *TokenSignatureAlgorithm) UnmarshalYAML(unmarshal func(interface{}) error) error
- type TokenStorage
- type TwilioServiceSettings
- type User
- type UserStorage
- type VerificationCodeStorage
Constants ¶
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. )
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 )
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") )
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" )
const ( // EmailServiceMailgun is a Mailgun service. EmailServiceMailgun = "mailgun" // EmailServiceAWS is an AWS SES service. EmailServiceAWS = "ses" // EmailServiceMock is an email service mock. EmailServiceMock = "mock" )
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. )
const AppleFilesDefaultPath string = "./apple"
const (
IdentifoConfigPathEnvName = "IDENTIFO_CONFIG"
)
const (
// OfflineScope is a scope value to request refresh token.
OfflineScope = "offline"
)
const PrivateKeyName = "private.pem"
Key names.
const (
// RouteMobileRegionUAE is a regional UAE RouteMobileR platform.
RouteMobileRegionUAE = "uae"
)
Variables ¶
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") )
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}$`) )
var AppleFilenames = AppleFiles{
DeveloperDomainAssociation: "apple-developer-domain-association.txt",
AppSiteAssociation: "apple-app-site-association",
}
AppleFilenames are names of the files related to Apple services.
var DefaultCors = cors.Options{AllowedHeaders: []string{"*", "x-identifo-clientid"}, AllowedMethods: []string{"HEAD", "GET", "POST", "PUT", "PATCH", "DELETE"}, AllowCredentials: true}
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}, }, 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, }, 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
var ErrSessionNotFound = errors.New("Session not found. ")
ErrSessionNotFound is when session not found.
var ErrUserNotFound = errors.New("User not found. ")
ErrUserNotFound is when user not found.
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"}}, }
var StrToTokenSignAlg = map[string]TokenSignatureAlgorithm{ "es256": TokenSignatureAlgorithmES256, "rs256": TokenSignatureAlgorithmRS256, "invalid": TokenSignatureAlgorithmInvalid, }
StrToTokenSignAlg maps string token service algorithm names to values.
Functions ¶
func AllEmailTemplatesFileNames ¶
func AllEmailTemplatesFileNames() []string
func MergeScopes ¶
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 ¶
NewTokenWithClaims generates new JWT token with claims and keyID.
func PasswordHash ¶
PasswordHash creates hash with salt for password.
func ReqestedScopesApply ¶
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 SliceExcluding ¶ added in v2.3.2
func SliceIntersect ¶
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
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 successfull login. Useful not only for web apps, mobile and desktop apps could use custom scheme for that. 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"` // 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 ¶
AppDataFromJSON unmarshal AppData from JSON string
func (AppData) GetCustomEmailTemplatePath ¶ added in v2.2.24
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 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 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 FederatedProvider ¶
type FederatedSession ¶
type FederatedSession struct { ProviderSession 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 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 { 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.
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 ¶
JWToken represents JWT token.
type KeyStorage ¶
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 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"` }
LoginWith is a type for configuring supported login ways.
type MongoDatabaseSettings ¶ added in v2.3.3
type NexmoServiceSettings ¶
type OriginChecker ¶
type PluginSettings ¶ added in v2.2.14
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 Router ¶
type Router interface {
ServeHTTP(http.ResponseWriter, *http.Request)
}
Router handles all incoming http requests.
type SESEmailServiceSettings ¶
type SMSService ¶
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 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 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 SessionDuration ¶
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"` }
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 TFAType ¶
type TFAType string
TFAType is a type of two-factor authentication for apps that support it.
type TemplateStorage ¶
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 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 ¶
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,omitempty" bson:"name,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) (Token, error) NewInviteToken(email, role 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 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 ¶
UserFromJSON deserialize user data from JSON.
func (User) Deanonimized ¶
Deanonimized returns model with all fields set for deanonimized user
func (User) SanitizedTFA ¶
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.
Source Files ¶
- app_storage.go
- apple.go
- configuration_storage.go
- configuration_watcher.go
- connection_tester.go
- cors_options.go
- email_service.go
- email_templates.go
- errors.go
- federated_identity_provider.go
- http_context.go
- invite.go
- invite_storage.go
- key_storage.go
- origin_checker.go
- password.go
- server.go
- server_settings.go
- server_settings_defaults.go
- server_settings_validation.go
- session.go
- session_service.go
- session_storage.go
- slice.go
- sms_service.go
- template_storage.go
- token.go
- token_algorithm.go
- token_service.go
- token_storage.go
- user_data_provider.go
- user_storage.go
- verification_code_storage.go