model

package
v1.2.9 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2021 License: MIT Imports: 20 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 (
	PublicKeyName  = "public.pem"
	PrivateKeyName = "private.pem"
)

Key names.

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 (
	// StaticFilesStorageTypeLocal is for storing static files locally.
	StaticFilesStorageTypeLocal = "local"
	// StaticFilesStorageTypeS3 is for storing static files in S3 bucket.
	StaticFilesStorageTypeS3 = "s3"
	// StaticFilesStorageTypeDynamoDB is for storing static files in DynamoDB table.
	StaticFilesStorageTypeDynamoDB = "dynamodb"
)
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 = "dynamodb"
)
View Source
const (
	// KeyStorageTypeLocal is for storing keys locally.
	KeyStorageTypeLocal = "local"
	// KeyStorageTypeS3 is for storing keys in the S3 bucket.
	KeyStorageTypeS3 = "s3"
)
View Source
const (
	// EmailServiceMailgun is a Mailgun service.
	EmailServiceMailgun = "mailgun"
	// EmailServiceAWS is an AWS SES service.
	EmailServiceAWS = "aws ses"
	// EmailServiceMock is an email service mock.
	EmailServiceMock = "mock"
)
View Source
const (
	AdminPanelBuildPath = "./admin_panel/build"
	WebBuildPath        = "./web/build"
	PagesPath           = "./html"
	EmailTemplatesPath  = "./email_templates"
	AppleFilesPath      = "./apple"
)

These paths describe directories with static files. They are relative to the folder specified in the configuration file.

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.
	TokenTFAPreauthScope = "2fa"         // TokenTFAPreauthScope preauth token scope for first step of TFA
)
View Source
const RouteMobileRegionUAE = "uae"

RouteMobileRegionUAE is a regional UAE RouteMobileR platform.

Variables

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 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 StaticPagesNames = StaticPages{
	DisableTFA:            "disable-tfa.html",
	DisableTFASuccess:     "disable-tfa-success.html",
	ForgotPassword:        "forgot-password.html",
	ForgotPasswordSuccess: "forgot-password-success.html",
	InviteEmail:           "invite-email.html",
	Login:                 "login.html",
	Misconfiguration:      "misconfiguration.html",
	Registration:          "registration.html",
	ResetPassword:         "reset-password.html",
	ResetPasswordEmail:    "reset-password-email.html",
	ResetPasswordSuccess:  "reset-password-success.html",
	ResetTFA:              "reset-tfa.html",
	ResetTFASuccess:       "reset-tfa-success.html",
	TFAEmail:              "tfa-email.html",
	TokenError:            "token-error.html",
	VerifyEmail:           "verify-email.html",
	WebMessage:            "web-message.html",
	WelcomeEmail:          "welcome-email.html",
}

StaticPagesNames are the names of html pages.

Functions

func GetStaticFilePathByFilename

func GetStaticFilePathByFilename(filename, staticFolder string) (filepath string, err error)

GetStaticFilePathByFilename returns filepath for given static file name.

func PasswordHash added in v1.2.4

func PasswordHash(pwd string) string

PasswordHash creates hash with salt for password.

func StrongPswd

func StrongPswd(pswd string) error

StrongPswd validates password

Types

type AdminAccountSettings

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

AdminAccountSettings are names of environment variables that store admin credentials.

type AdminPanelHandlers

type AdminPanelHandlers struct {
	SrcHandler        http.Handler
	ManagementHandler http.Handler
	BuildHandler      http.Handler
}

AdminPanelHandlers holds together admin panel handlers.

type AppData

type AppData struct {
	ID                                string                            `bson:"_id,omitempty" json:"id,omitempty"` // TODO: use string?
	Secret                            string                            `bson:"secret,omitempty" json:"secret,omitempty"`
	Active                            bool                              `bson:"active,omitempty" json:"active,omitempty"`
	Name                              string                            `bson:"name,omitempty" json:"name,omitempty"`
	Description                       string                            `bson:"description,omitempty" json:"description,omitempty"`
	Scopes                            []string                          `bson:"scopes,omitempty" json:"scopes,omitempty"`   // Scopes is the list of all allowed scopes. If it's empty, no limitations (opaque scope).
	Offline                           bool                              `bson:"offline,omitempty" json:"offline,omitempty"` // 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,omitempty" json:"type,omitempty"`
	RedirectURLs                      []string                          `bson:"redirect_urls,omitempty" json:"redirect_urls,omitempty"`                   // 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.
	TokenLifespan                     int64                             `bson:"refresh_token_lifespan,omitempty" json:"refresh_token_lifespan,omitempty"` // TokenLifespan is a token lifespan in seconds, if 0 - default one is used.
	InviteTokenLifespan               int64                             `bson:"invite_token_lifespan,omitempty" json:"invite_token_lifespan,omitempty"`   // InviteTokenLifespan a inviteToken lifespan in seconds, if 0 - default one is used.
	RefreshTokenLifespan              int64                             `bson:"token_lifespan,omitempty" json:"token_lifespan,omitempty"`                 // RefreshTokenLifespan is a refreshToken lifespan in seconds, if 0 - default one is used.
	TokenPayload                      []string                          `bson:"token_payload,omitempty" json:"token_payload,omitempty"`                   // Payload is a list of fields that are included in token. If it's empty, there are no fields in payload.
	TFAStatus                         TFAStatus                         `bson:"tfa_status,omitempty" json:"tfa_status,omitempty"`
	DebugTFACode                      string                            `bson:"debug_tfa_code,omitempty" json:"debug_tfa_code,omitempty"`
	RegistrationForbidden             bool                              `bson:"registration_forbidden,omitempty" json:"registration_forbidden,omitempty"`
	AnonymousRegistrationAllowed      bool                              `bson:"anonymous_registration_allowed,omitempty" json:"anonymous_registration_allowed,omitempty"`
	AuthzWay                          AuthorizationWay                  `bson:"authorization_way,omitempty" json:"authorization_way,omitempty"`
	AuthzModel                        string                            `bson:"authorization_model,omitempty" json:"authorization_model,omitempty"`
	AuthzPolicy                       string                            `bson:"authorization_policy,omitempty" json:"authorization_policy,omitempty"`
	RolesWhitelist                    []string                          `bson:"roles_whitelist,omitempty" json:"roles_whitelist,omitempty"`
	RolesBlacklist                    []string                          `bson:"roles_blacklist,omitempty" json:"roles_blacklist,omitempty"`
	NewUserDefaultRole                string                            `bson:"new_user_default_role,omitempty" json:"new_user_default_role,omitempty"`
	AppleInfo                         *AppleInfo                        `bson:"apple_info,omitempty" json:"apple_info,omitempty"`
	TokenPayloadService               TokenPayloadServiceType           `json:"token_payload_service,omitempty" bson:"token_payload_service,omitempty"`
	TokenPayloadServicePluginSettings TokenPayloadServicePluginSettings `json:"token_payload_service_plugin_settings,omitempty" bson:"token_payload_service_plugin_settings,omitempty"`
	TokenPayloadServiceHttpSettings   TokenPayloadServiceHttpSettings   `json:"token_payload_service_http_settings,omitempty" bson:"token_payload_service_http_settings,omitempty"`
}

AppData represents Application data information.

func AppDataFromJSON added in v1.2.4

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

AppDataFromJSON unmarshal AppData from JSON string

func (AppData) Sanitized added in v1.2.4

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(filterString string, skip, limit int) ([]AppData, int, error)
	DeleteApp(id string) error
	ImportJSON(data []byte) 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,omitempty" json:"developer_domain_association,omitempty"`
	AppSiteAssociation         string `yaml:"appSiteAssociation,omitempty" json:"app_site_association,omitempty"`
}

AppleFiles holds together static files needed for supporting Apple services.

type AppleInfo

type AppleInfo struct {
	ClientID     string `json:"client_id,omitempty" bson:"client_id,omitempty"`
	ClientSecret string `json:"client_secret,omitempty" bson:"client_secret,omitempty"`
}

AppleInfo represents the information needed for Sign In with Apple.

type AssetHandlers

type AssetHandlers struct {
	StylesHandler  http.Handler
	ScriptsHandler http.Handler
	ImagesHandler  http.Handler
	FontsHandler   http.Handler
}

AssetHandlers holds together asset handlers.

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 ConfigStorageSettings added in v1.2.9

type ConfigStorageSettings struct {
	Type      ConfigStorageType    `json:"type,omitempty" yaml:"type,omitempty"`
	RawString string               `json:"raw_string,omitempty" yaml:"raw_string,omitempty"`
	S3        *S3StorageSettings   `json:"s3,omitempty" yaml:"s3,omitempty"`
	File      *FileStorageSettings `json:"file,omitempty" yaml:"file,omitempty"`
	Etcd      *EtcdStorageSettings `json:"etcd,omitempty" yaml:"etcd,omitempty"`
}

func ConfigStorageSettingsFromString added in v1.2.9

func ConfigStorageSettingsFromString(config string) (ConfigStorageSettings, error)

func ConfigStorageSettingsFromStringEtcd added in v1.2.9

func ConfigStorageSettingsFromStringEtcd(config string) (ConfigStorageSettings, error)

func ConfigStorageSettingsFromStringFile added in v1.2.9

func ConfigStorageSettingsFromStringFile(config string) (ConfigStorageSettings, error)

func ConfigStorageSettingsFromStringS3 added in v1.2.9

func ConfigStorageSettingsFromStringS3(config string) (ConfigStorageSettings, error)

func (*ConfigStorageSettings) Validate added in v1.2.9

func (css *ConfigStorageSettings) Validate() error

Validate validates configuration storage settings.

type ConfigStorageType added in v1.2.9

type ConfigStorageType string

ConfigStorageType describes type of configuration storage.

const (
	// ConfigStorageTypeEtcd is an etcd storage.
	ConfigStorageTypeEtcd ConfigStorageType = "etcd"
	// ConfigurationStorageTypeS3 is an AWS S3 storage.
	ConfigStorageTypeS3 ConfigStorageType = "s3"
	// ConfigurationStorageTypeFile is a config file.
	ConfigStorageTypeFile ConfigStorageType = "file"
)

type ConfigurationStorage

type ConfigurationStorage interface {
	WriteConfig(ServerSettings) error
	LoadServerSettings(*ServerSettings) error
	InsertKeys(keys *JWTKeys) error
	LoadKeys(ijwt.TokenSignatureAlgorithm) (*JWTKeys, error)
	GetUpdateChan() chan interface{}
	CloseUpdateChan()
}

ConfigurationStorage stores server configuration.

type ConfigurationWatcher

type ConfigurationWatcher interface {
	Watch()
	WatchChan() chan interface{}
	Stop()
}

ConfigurationWatcher is a global server configuration watcher.

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 CorsOptions

type CorsOptions struct {
	Admin *cors.Options
	API   *cors.Options
	HTML  *cors.Options
}

CorsOptions are options for routers CORS.

type DatabaseSettings

type DatabaseSettings struct {
	Type     DatabaseType `yaml:"type,omitempty" json:"type,omitempty"`
	Name     string       `yaml:"name,omitempty" json:"name,omitempty"`
	Endpoint string       `yaml:"endpoint,omitempty" json:"endpoint,omitempty"`
	Region   string       `yaml:"region,omitempty" json:"region,omitempty"`
	Path     string       `yaml:"path,omitempty" json:"path,omitempty"`
}

DatabaseSettings holds together all settings applicable to a particular database.

func (*DatabaseSettings) Validate

func (dbs *DatabaseSettings) Validate() error

Validate validates database settings.

type DatabaseType

type DatabaseType string

DatabaseType is a type of database.

const (
	DBTypeBoltDB   DatabaseType = "boltdb"   // DBTypeBoltDB is for BoltDB.
	DBTypeMongoDB  DatabaseType = "mongodb"  // DBTypeMongoDB is for MongoDB.
	DBTypeDynamoDB DatabaseType = "dynamodb" // DBTypeDynamoDB is for DynamoDB.
	DBTypeFake     DatabaseType = "fake"     // DBTypeFake is for in-memory storage.
)

type EmailService

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

	SendTemplateEmail(subject, recipient string, template *template.Template, data interface{}) error
	SendResetEmail(subject, recipient string, data ResetEmailData) error
	SendInviteEmail(subject, recipient string, data InviteEmailData) error
	SendWelcomeEmail(subject, recipient string, data WelcomeEmailData) error
	SendVerifyEmail(subject, recipient string, data VerifyEmailData) error
	SendTFAEmail(subject, recipient string, data SendTFAEmailData) error

	Templater() *EmailTemplater
}

EmailService manages sending emails.

type EmailServiceSettings

type EmailServiceSettings struct {
	Type       EmailServiceType `yaml:"type,omitempty" json:"type,omitempty"`
	Domain     string           `yaml:"domain,omitempty" json:"domain,omitempty"`
	PublicKey  string           `yaml:"publicKey,omitempty" json:"public_key,omitempty"`
	PrivateKey string           `yaml:"privateKey,omitempty" json:"private_key,omitempty"`
	Sender     string           `yaml:"sender,omitempty" json:"sender,omitempty"`
	Region     string           `yaml:"region,omitempty" json:"region,omitempty"`
}

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 EmailTemplater

type EmailTemplater struct {
	WelcomeTemplate       *template.Template
	ResetPasswordTemplate *template.Template
	InviteTemplate        *template.Template
	VerifyTemplate        *template.Template
	TFATemplate           *template.Template
}

EmailTemplater stores pointers to email templates.

func NewEmailTemplater

func NewEmailTemplater(staticFilesStorage StaticFilesStorage) (*EmailTemplater, error)

NewEmailTemplater creates new email templater.

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 EtcdStorageSettings added in v1.2.9

type EtcdStorageSettings struct {
	Endpoints []string `json:"endpoints,omitempty" yaml:"endpoints,omitempty"`
	Key       string   `json:"key,omitempty" yaml:"key,omitempty"`
	Username  string   `json:"username,omitempty" yaml:"username,omitempty"`
	Password  string   `json:"password,omitempty" yaml:"password,omitempty"`
}

type ExternalServicesSettings

type ExternalServicesSettings struct {
	EmailService EmailServiceSettings `yaml:"emailService,omitempty" json:"email_service,omitempty"`
	SMSService   SMSServiceSettings   `yaml:"smsService,omitempty" json:"sms_service,omitempty"`
}

ExternalServicesSettings are settings for external services.

func (*ExternalServicesSettings) Validate

func (ess *ExternalServicesSettings) Validate() error

Validate validates external services settings.

type FederatedIdentityProvider

type FederatedIdentityProvider string

FederatedIdentityProvider is an external federated identity provider type. If you are missing the provider you need, please feel free to add it here.

var (
	// FacebookIDProvider is a Facebook ID provider.
	FacebookIDProvider FederatedIdentityProvider = "FACEBOOK"
	// GoogleIDProvider is a Google ID provider.
	GoogleIDProvider FederatedIdentityProvider = "GOOGLE"
	// TwitterIDProvider is a Twitter ID provider.
	TwitterIDProvider FederatedIdentityProvider = "TWITTER"
	// AppleIDProvider is an Apple ID provider.
	AppleIDProvider FederatedIdentityProvider = "APPLE"
)

func (FederatedIdentityProvider) IsValid

func (fid FederatedIdentityProvider) IsValid() bool

IsValid has to be called everywhere input happens, otherwise you risk to operate on bad data - no guarantees.

type FileStorageSettings added in v1.2.9

type FileStorageSettings struct {
	// just a file name
	FileName string `yaml:"file_name,omitempty" json:"file_name,omitempty" bson:"file_name,omitempty"`
}

type GeneralServerSettings

type GeneralServerSettings struct {
	Host      string `yaml:"host,omitempty" json:"host,omitempty"`
	Issuer    string `yaml:"issuer,omitempty" json:"issuer,omitempty"`
	Algorithm string `yaml:"algorithm,omitempty" json:"algorithm,omitempty"`
}

GeneralServerSettings are general server settings.

func (*GeneralServerSettings) Validate

func (gss *GeneralServerSettings) Validate() error

Validate validates general services settings.

type Invite added in v1.2.4

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 added in v1.2.4

func (i Invite) Validate() error

Validate validates the Invite model.

type InviteEmailData added in v1.2.8

type InviteEmailData struct {
	Requester User
	Token     string
	URL       string
	Host      string
	Query     string
	App       string
	Scopes    string
	Callback  string
	Data      interface{}
}

type InviteStorage added in v1.2.4

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
}

InviteStorage is a storage for invites.

type JWTKeys

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

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

type KeyStorage

type KeyStorage interface {
	InsertKeys(keys *JWTKeys) error
	LoadKeys(alg ijwt.TokenSignatureAlgorithm) (*JWTKeys, error)
}

KeyStorage stores keys used for signing and verifying JWT tokens.

type KeyStorageFileSettings added in v1.2.9

type KeyStorageFileSettings struct {
	PrivateKeyPath string `json:"private_key_path,omitempty" yaml:"private_key_path,omitempty"`
	PublicKeyPath  string `json:"public_key_path,omitempty" yaml:"public_key_path,omitempty"`
}

type KeyStorageSettings

type KeyStorageSettings struct {
	Type KeyStorageType          `yaml:"type,omitempty" json:"type,omitempty"`
	S3   *S3KeyStorageSettings   `yaml:"s3,omitempty" json:"s3,omitempty"`
	File *KeyStorageFileSettings `yaml:"file,omitempty" json:"file,omitempty"`
}

KeyStorageSettings are settings for the key storage.

func (*KeyStorageSettings) Validate

func (kss *KeyStorageSettings) Validate() error

Validate validates key storage settings.

type KeyStorageType

type KeyStorageType string

KeyStorageType is a type of the key storage.

type LoggerSettings added in v1.2.3

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

type LoginSettings

type LoginSettings struct {
	LoginWith LoginWith `yaml:"loginWith,omitempty" json:"login_with,omitempty"`
	TFAType   TFAType   `yaml:"tfaType,omitempty" json:"tfa_type,omitempty"`
}

LoginSettings are settings of login.

type LoginWith

type LoginWith struct {
	Username  bool `yaml:"username" json:"username,omitempty"`
	Phone     bool `yaml:"phone" json:"phone,omitempty"`
	Federated bool `yaml:"federated" json:"federated,omitempty"`
}

LoginWith is a type for configuring supported login ways.

type ResetEmailData added in v1.2.8

type ResetEmailData struct {
	User  User
	Token string
	URL   string
	Host  string
	Data  interface{}
}

ResetEmailData represents data to be send to the user for reset email

type Router

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

Router handles all incoming http requests.

type S3KeyStorageSettings added in v1.2.9

type S3KeyStorageSettings struct {
	Region        string `yaml:"region,omitempty" json:"region,omitempty" bson:"region,omitempty"`
	Bucket        string `yaml:"bucket,omitempty" json:"bucket,omitempty" bson:"bucket,omitempty"`
	PublicKeyKey  string `yaml:"public_key_key,omitempty" json:"public_key_key,omitempty" bson:"public_key_key,omitempty"`
	PrivateKeyKey string `yaml:"private_key_key,omitempty" json:"private_key_key,omitempty" bson:"private_key_key,omitempty"`
}

type S3StorageSettings added in v1.2.9

type S3StorageSettings struct {
	Region string `yaml:"region,omitempty" json:"region,omitempty" bson:"region,omitempty"`
	Bucket string `yaml:"bucket,omitempty" json:"bucket,omitempty" bson:"bucket,omitempty"`
	Key    string `yaml:"key,omitempty" json:"key,omitempty" bson:"key,omitempty"`
}

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,omitempty" json:"type,omitempty"`

	// Twilio related config.
	AccountSid string `yaml:"accountSid,omitempty" json:"account_sid,omitempty"`
	AuthToken  string `yaml:"authToken,omitempty" json:"auth_token,omitempty"`
	ServiceSid string `yaml:"serviceSid,omitempty" json:"service_sid,omitempty"`

	// Nexmo related config.
	APIKey    string `yaml:"apiKey,omitempty" json:"api_key,omitempty"`
	APISecret string `yaml:"apiSecret,omitempty" json:"api_secret,omitempty"`

	// RouteMobile related config.
	Username string `yaml:"username,omitempty" json:"username,omitempty"`
	Password string `yaml:"password,omitempty" json:"password,omitempty"`
	Source   string `yaml:"source,omitempty" json:"source,omitempty"`
	Region   string `yaml:"region,omitempty" json:"region,omitempty"`
}

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 SendTFAEmailData added in v1.2.8

type SendTFAEmailData struct {
	User User
	OTP  string
	Data interface{}
}

type Server

type Server interface {
	Router() Router
	AppStorage() AppStorage
	UserStorage() UserStorage
	ConfigurationStorage() ConfigurationStorage
	ImportApps(filename string) error
	ImportUsers(filename string) error
	Settings() ServerSettings
	Close()
}

Server holds together all dependencies.

type ServerSettings

type ServerSettings struct {
	General            GeneralServerSettings      `yaml:"general,omitempty" json:"general,omitempty"`
	AdminAccount       AdminAccountSettings       `yaml:"adminAccount,omitempty" json:"admin_account,omitempty"`
	Storage            StorageSettings            `yaml:"storage,omitempty" json:"storage,omitempty"`
	SessionStorage     SessionStorageSettings     `yaml:"sessionStorage,omitempty" json:"session_storage,omitempty"`
	StaticFilesStorage StaticFilesStorageSettings `yaml:"staticFilesStorage,omitempty" json:"static_files_storage,omitempty"`
	ExternalServices   ExternalServicesSettings   `yaml:"externalServices,omitempty" json:"external_services,omitempty"`
	Login              LoginSettings              `yaml:"login,omitempty" json:"login,omitempty"`
	KeyStorage         KeyStorageSettings         `yaml:"keyStorage,omitempty" json:"keyStorage,omitempty"`
	Config             ConfigStorageSettings      `yaml:"config,omitempty" json:"config,omitempty"`
	Logger             LoggerSettings             `yaml:"logger,omitempty" json:"logger,omitempty"`
}

ServerSettings are server settings.

func (ServerSettings) GetPort

func (ss ServerSettings) GetPort() string

GetPort returns port on which host listens to incoming connections.

func (*ServerSettings) Validate

func (ss *ServerSettings) Validate() error

Validate makes sure that all crucial fields are set.

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
}

SessionStorage is an interface for session storage.

type SessionStorageSettings

type SessionStorageSettings struct {
	Type            SessionStorageType `yaml:"type,omitempty" json:"type,omitempty"`
	SessionDuration SessionDuration    `yaml:"sessionDuration,omitempty" json:"session_duration,omitempty"`
	Address         string             `yaml:"address,omitempty" json:"address,omitempty"`
	Password        string             `yaml:"password,omitempty" json:"password,omitempty"`
	DB              int                `yaml:"db,omitempty" json:"db,omitempty"`
	Region          string             `yaml:"region,omitempty" json:"region,omitempty"`
	Endpoint        string             `yaml:"endpoint,omitempty" json:"endpoint,omitempty"`
}

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 StaticFilesStorage

type StaticFilesStorage interface {
	GetFile(name string) ([]byte, error)
	UploadFile(name string, contents []byte) error
	ParseTemplate(templateName string) (*template.Template, error)
	GetAppleFile(name string) ([]byte, error)
	AssetHandlers() *AssetHandlers
	AdminPanelHandlers() *AdminPanelHandlers
	WebHandlers() *WebHandlers
	Close()
}

StaticFilesStorage is a wrapper over static files storages.

type StaticFilesStorageSettings

type StaticFilesStorageSettings struct {
	Type             StaticFilesStorageType `yaml:"type,omitempty" json:"type,omitempty"`
	ServerConfigPath string                 `yaml:"serverConfigPath,omitempty" json:"server_config_path,omitempty"`
	Folder           string                 `yaml:"folder,omitempty" json:"folder,omitempty"`
	Bucket           string                 `yaml:"bucket,omitempty" json:"bucket,omitempty"`
	Region           string                 `yaml:"region,omitempty" json:"region,omitempty"`
	Endpoint         string                 `yaml:"endpoint,omitempty" json:"endpoint,omitempty"`
	ServeAdminPanel  bool                   `yaml:"serveAdminPanel,omitempty" json:"serve_admin_panel,omitempty"`
	ServeNewWeb      bool                   `yaml:"serveNewWeb,omitempty" json:"serve_new_web,omitempty"`
}

StaticFilesStorageSettings are settings for static files storage.

func (*StaticFilesStorageSettings) Validate

func (sfs *StaticFilesStorageSettings) Validate() error

Validate validates static files storage settings.

type StaticFilesStorageType

type StaticFilesStorageType string

StaticFilesStorageType is a type of static files storage.

type StaticPages

type StaticPages struct {
	DisableTFA            string
	DisableTFASuccess     string
	ForgotPassword        string
	ForgotPasswordSuccess string
	InviteEmail           string
	Login                 string
	Misconfiguration      string
	Registration          string
	ResetPassword         string
	ResetPasswordEmail    string
	ResetPasswordSuccess  string
	ResetTFA              string
	ResetTFASuccess       string
	TFAEmail              string
	TokenError            string
	VerifyEmail           string
	WebMessage            string
	WelcomeEmail          string
}

StaticPages holds together all paths to static pages.

type StorageSettings

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

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,omitempty" bson:"is_enabled,omitempty"`
	HOTPCounter   int       `json:"hotp_counter,omitempty" bson:"hotp_counter,omitempty"`
	HOTPExpiredAt time.Time `json:"hotp_expired_at,omitempty" bson:"hotp_expired_at,omitempty"`
	Secret        string    `json:"secret,omitempty" bson:"secret,omitempty"`
}

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 TokenBlacklist

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

TokenBlacklist is a storage for blacklisted tokens.

type TokenPayloadProvider added in v1.2.3

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

TokenPayloadProvider provides additional user payload to include to the token

type TokenPayloadServiceHttpSettings added in v1.2.3

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 added in v1.2.3

type TokenPayloadServicePluginSettings struct {
	Name string `json:"name,omitempty" bson:"name,omitempty"`
}

TokenPayloadServicePluginSettings settings for token payload service

type TokenPayloadServiceType added in v1.2.3

type TokenPayloadServiceType string

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

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 User

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

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 added in v1.2.4

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

UserFromJSON deserialize user data from JSON.

func (User) Deanonimized added in v1.2.4

func (u User) Deanonimized() User

Deanonimized returns model with all fields set for deanonimized user

func (User) Sanitized added in v1.2.4

func (u User) Sanitized() User

Sanitized returns data structure without sensitive information

func (User) SanitizedTFA added in v1.2.4

func (u User) SanitizedTFA() User

SanitizedTFA returns data structure with masked sensitive data

type UserStorage

type UserStorage interface {
	UserByPhone(phone string) (User, error)
	AddUserByPhone(phone, role string) (User, error)
	UserByID(id string) (User, error)
	UserByEmail(email string) (User, error)
	IDByName(name string) (string, error)
	AttachDeviceToken(id, token string) error
	DetachDeviceToken(token string) error
	UserByNamePassword(name, password string) (User, error)
	AddUserByNameAndPassword(username, password, role string, isAnonymous bool) (User, error)
	UserExists(name string) bool
	UserByFederatedID(provider FederatedIdentityProvider, id string) (User, error)
	AddUserWithFederatedID(provider FederatedIdentityProvider, id, role string) (User, error)
	UpdateUser(userID string, newUser User) (User, error)
	ResetPassword(id, password string) error
	DeleteUser(id string) error
	FetchUsers(search string, skip, limit int) ([]User, int, error)

	RequestScopes(userID string, scopes []string) ([]string, error)
	Scopes() []string
	ImportJSON(data []byte) error
	UpdateLoginMetadata(userID string)
	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.

type VerifyEmailData added in v1.2.8

type VerifyEmailData struct {
	User  User
	Token string
	URL   string
	Data  interface{}
}

type WebHandlers added in v1.2.7

type WebHandlers struct {
	AppHandler http.Handler
}

type WelcomeEmailData added in v1.2.8

type WelcomeEmailData struct {
	User User
	Data interface{}
}

Jump to

Keyboard shortcuts

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