dataprovider

package
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2020 License: GPL-3.0 Imports: 50 Imported by: 0

Documentation

Overview

Package dataprovider provides data access. It abstracts different data providers and exposes a common API.

Index

Constants

View Source
const (
	// SQLiteDataProviderName name for SQLite database provider
	SQLiteDataProviderName = "sqlite"
	// PGSQLDataProviderName name for PostgreSQL database provider
	PGSQLDataProviderName = "postgresql"
	// MySQLDataProviderName name for MySQL database provider
	MySQLDataProviderName = "mysql"
	// BoltDataProviderName name for bbolt key/value store provider
	BoltDataProviderName = "bolt"
	// MemoryDataProviderName name for memory provider
	MemoryDataProviderName = "memory"
)
View Source
const (
	OrderASC  = "ASC"
	OrderDESC = "DESC"
)

ordering constants

View Source
const (
	// All permissions are granted
	PermAny = "*"
	// List items such as files and directories is allowed
	PermListItems = "list"
	// download files is allowed
	PermDownload = "download"
	// upload files is allowed
	PermUpload = "upload"
	// overwrite an existing file, while uploading, is allowed
	// upload permission is required to allow file overwrite
	PermOverwrite = "overwrite"
	// delete files or directories is allowed
	PermDelete = "delete"
	// rename files or directories is allowed
	PermRename = "rename"
	// create directories is allowed
	PermCreateDirs = "create_dirs"
	// create symbolic links is allowed
	PermCreateSymlinks = "create_symlinks"
	// changing file or directory permissions is allowed
	PermChmod = "chmod"
	// changing file or directory owner and group is allowed
	PermChown = "chown"
	// changing file or directory access and modification time is allowed
	PermChtimes = "chtimes"
)

Available permissions for SFTP users

View Source
const (
	LoginMethodNoAuthTryed            = "no_auth_tryed"
	LoginMethodPassword               = "password"
	SSHLoginMethodPublicKey           = "publickey"
	SSHLoginMethodKeyboardInteractive = "keyboard-interactive"
	SSHLoginMethodKeyAndPassword      = "publickey+password"
	SSHLoginMethodKeyAndKeyboardInt   = "publickey+keyboard-interactive"
)

Available login methods

Variables

View Source
var (
	// SupportedProviders defines the supported data providers
	SupportedProviders = []string{SQLiteDataProviderName, PGSQLDataProviderName, MySQLDataProviderName,
		BoltDataProviderName, MemoryDataProviderName}
	// ValidPerms defines all the valid permissions for a user
	ValidPerms = []string{PermAny, PermListItems, PermDownload, PermUpload, PermOverwrite, PermRename, PermDelete,
		PermCreateDirs, PermCreateSymlinks, PermChmod, PermChown, PermChtimes}
	// ValidSSHLoginMethods defines all the valid SSH login methods
	ValidSSHLoginMethods = []string{SSHLoginMethodPublicKey, LoginMethodPassword, SSHLoginMethodKeyboardInteractive,
		SSHLoginMethodKeyAndPassword, SSHLoginMethodKeyAndKeyboardInt}
	// SSHMultiStepsLoginMethods defines the supported Multi-Step Authentications
	SSHMultiStepsLoginMethods = []string{SSHLoginMethodKeyAndPassword, SSHLoginMethodKeyAndKeyboardInt}
	// ErrNoAuthTryed defines the error for connection closed before authentication
	ErrNoAuthTryed = errors.New("no auth tryed")
	// ValidProtocols defines all the valid protcols
	ValidProtocols = []string{"SSH", "FTP", "DAV"}
	// ErrNoInitRequired defines the error returned by InitProvider if no inizialization/update is required
	ErrNoInitRequired = errors.New("The data provider is already up to date")
	// ErrInvalidCredentials defines the error to return if the supplied credentials are invalid
	ErrInvalidCredentials = errors.New("Invalid credentials")
)

Functions

func AddFolder

func AddFolder(folder vfs.BaseVirtualFolder) error

AddFolder adds a new virtual folder. ManageUsers configuration must be set to 1 to enable this method

func AddUser

func AddUser(user User) error

AddUser adds a new SFTPGo user. ManageUsers configuration must be set to 1 to enable this method

func CacheWebDAVUser added in v1.1.0

func CacheWebDAVUser(cachedUser *CachedUser, maxSize int)

CacheWebDAVUser add a user to the WebDAV cache

func Close

func Close() error

Close releases all provider resources. This method is used in test cases. Closing an uninitialized provider is not supported

func DeleteFolder

func DeleteFolder(folder vfs.BaseVirtualFolder) error

DeleteFolder deletes an existing folder. ManageUsers configuration must be set to 1 to enable this method

func DeleteUser

func DeleteUser(user User) error

DeleteUser deletes an existing SFTPGo user. ManageUsers configuration must be set to 1 to enable this method

func ExecutePostLoginHook added in v1.1.0

func ExecutePostLoginHook(username, loginMethod, ip, protocol string, err error)

ExecutePostLoginHook executes the post login hook if defined

func GetCachedWebDAVUser added in v1.1.0

func GetCachedWebDAVUser(username string) (interface{}, bool)

GetCachedWebDAVUser returns a previously cached WebDAV user

func GetFolderByPath

func GetFolderByPath(mappedPath string) (vfs.BaseVirtualFolder, error)

GetFolderByPath returns the folder with the specified path if any

func GetFolders

func GetFolders(limit, offset int, order, folderPath string) ([]vfs.BaseVirtualFolder, error)

GetFolders returns an array of folders respecting limit and offset

func GetProviderStatus

func GetProviderStatus() error

GetProviderStatus returns an error if the provider is not available

func GetQuotaTracking

func GetQuotaTracking() int

GetQuotaTracking returns the configured mode for user's quota tracking

func GetUsedQuota

func GetUsedQuota(username string) (int, int64, error)

GetUsedQuota returns the used quota for the given SFTP user.

func GetUsedVirtualFolderQuota

func GetUsedVirtualFolderQuota(mappedPath string) (int, int64, error)

GetUsedVirtualFolderQuota returns the used quota for the given virtual folder.

func Initialize

func Initialize(cnf Config, basePath string) error

Initialize the data provider. An error is returned if the configured driver is invalid or if the data provider cannot be initialized

func InitializeDatabase

func InitializeDatabase(cnf Config, basePath string) error

InitializeDatabase creates the initial database structure

func ReloadConfig

func ReloadConfig() error

ReloadConfig reloads provider configuration. Currently only implemented for memory provider, allows to reload the users from the configured file, if defined

func RemoveCachedWebDAVUser added in v1.1.0

func RemoveCachedWebDAVUser(username string)

RemoveCachedWebDAVUser removes a cached WebDAV user

func UpdateLastLogin

func UpdateLastLogin(user User) error

UpdateLastLogin updates the last login fields for the given SFTP user

func UpdateUser

func UpdateUser(user User) error

UpdateUser updates an existing SFTPGo user. ManageUsers configuration must be set to 1 to enable this method

func UpdateUserQuota

func UpdateUserQuota(user User, filesAdd int, sizeAdd int64, reset bool) error

UpdateUserQuota updates the quota for the given SFTP user adding filesAdd and sizeAdd. If reset is true filesAdd and sizeAdd indicates the total files and the total size instead of the difference.

func UpdateVirtualFolderQuota

func UpdateVirtualFolderQuota(vfolder vfs.BaseVirtualFolder, filesAdd int, sizeAdd int64, reset bool) error

UpdateVirtualFolderQuota updates the quota for the given virtual folder adding filesAdd and sizeAdd. If reset is true filesAdd and sizeAdd indicates the total files and the total size instead of the difference.

Types

type Argon2Options added in v1.1.0

type Argon2Options struct {
	Memory      uint32 `json:"memory" mapstructure:"memory"`
	Iterations  uint32 `json:"iterations" mapstructure:"iterations"`
	Parallelism uint8  `json:"parallelism" mapstructure:"parallelism"`
}

Argon2Options defines the options for argon2 password hashing

type BackupData

type BackupData struct {
	Users   []User                  `json:"users"`
	Folders []vfs.BaseVirtualFolder `json:"folders"`
}

BackupData defines the structure for the backup/restore files

func DumpData

func DumpData() (BackupData, error)

DumpData returns all users and folders

type BoltProvider

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

BoltProvider auth provider for bolt key/value store

type CachedUser added in v1.1.0

type CachedUser struct {
	User       User
	Expiration time.Time
	Password   string
	LockSystem webdav.LockSystem
}

CachedUser adds fields useful for caching to a SFTPGo user

func (*CachedUser) IsExpired added in v1.1.0

func (c *CachedUser) IsExpired() bool

IsExpired returns true if the cached user is expired

type Config

type Config struct {
	// Driver name, must be one of the SupportedProviders
	Driver string `json:"driver" mapstructure:"driver"`
	// Database name. For driver sqlite this can be the database name relative to the config dir
	// or the absolute path to the SQLite database.
	Name string `json:"name" mapstructure:"name"`
	// Database host
	Host string `json:"host" mapstructure:"host"`
	// Database port
	Port int `json:"port" mapstructure:"port"`
	// Database username
	Username string `json:"username" mapstructure:"username"`
	// Database password
	Password string `json:"password" mapstructure:"password"`
	// Used for drivers mysql and postgresql.
	// 0 disable SSL/TLS connections.
	// 1 require ssl.
	// 2 set ssl mode to verify-ca for driver postgresql and skip-verify for driver mysql.
	// 3 set ssl mode to verify-full for driver postgresql and preferred for driver mysql.
	SSLMode int `json:"sslmode" mapstructure:"sslmode"`
	// Custom database connection string.
	// If not empty this connection string will be used instead of build one using the previous parameters
	ConnectionString string `json:"connection_string" mapstructure:"connection_string"`
	// prefix for SQL tables
	SQLTablesPrefix string `json:"sql_tables_prefix" mapstructure:"sql_tables_prefix"`
	// Set to 0 to disable users management, 1 to enable
	ManageUsers int `json:"manage_users" mapstructure:"manage_users"`
	// Set the preferred way to track users quota between the following choices:
	// 0, disable quota tracking. REST API to scan user dir and update quota will do nothing
	// 1, quota is updated each time a user upload or delete a file even if the user has no quota restrictions
	// 2, quota is updated each time a user upload or delete a file but only for users with quota restrictions
	//    and for virtual folders.
	//    With this configuration the "quota scan" REST API can still be used to periodically update space usage
	//    for users without quota restrictions
	TrackQuota int `json:"track_quota" mapstructure:"track_quota"`
	// Sets the maximum number of open connections for mysql and postgresql driver.
	// Default 0 (unlimited)
	PoolSize int `json:"pool_size" mapstructure:"pool_size"`
	// Users default base directory.
	// If no home dir is defined while adding a new user, and this value is
	// a valid absolute path, then the user home dir will be automatically
	// defined as the path obtained joining the base dir and the username
	UsersBaseDir string `json:"users_base_dir" mapstructure:"users_base_dir"`
	// Actions to execute on user add, update, delete.
	// Update action will not be fired for internal updates such as the last login or the user quota fields.
	Actions UserActions `json:"actions" mapstructure:"actions"`
	// Absolute path to an external program or an HTTP URL to invoke for users authentication.
	// Leave empty to use builtin authentication.
	// If the authentication succeed the user will be automatically added/updated inside the defined data provider.
	// Actions defined for user added/updated will not be executed in this case.
	// This method is slower than built-in authentication methods, but it's very flexible as anyone can
	// easily write his own authentication hooks.
	ExternalAuthHook string `json:"external_auth_hook" mapstructure:"external_auth_hook"`
	// ExternalAuthScope defines the scope for the external authentication hook.
	// - 0 means all supported authentication scopes, the external hook will be executed for password,
	//     public key and keyboard interactive authentication
	// - 1 means passwords only
	// - 2 means public keys only
	// - 4 means keyboard interactive only
	// you can combine the scopes, for example 3 means password and public key, 5 password and keyboard
	// interactive and so on
	ExternalAuthScope int `json:"external_auth_scope" mapstructure:"external_auth_scope"`
	// CredentialsPath defines the directory for storing user provided credential files such as
	// Google Cloud Storage credentials. It can be a path relative to the config dir or an
	// absolute path
	CredentialsPath string `json:"credentials_path" mapstructure:"credentials_path"`
	// Absolute path to an external program or an HTTP URL to invoke just before the user login.
	// This program/URL allows to modify or create the user trying to login.
	// It is useful if you have users with dynamic fields to update just before the login.
	// Please note that if you want to create a new user, the pre-login hook response must
	// include all the mandatory user fields.
	//
	// The pre-login hook must finish within 30 seconds.
	//
	// If an error happens while executing the "PreLoginHook" then login will be denied.
	// PreLoginHook and ExternalAuthHook are mutally exclusive.
	// Leave empty to disable.
	PreLoginHook string `json:"pre_login_hook" mapstructure:"pre_login_hook"`
	// Absolute path to an external program or an HTTP URL to invoke after the user login.
	// Based on the configured scope you can choose if notify failed or successful logins
	// or both
	PostLoginHook string `json:"post_login_hook" mapstructure:"post_login_hook"`
	// PostLoginScope defines the scope for the post-login hook.
	// - 0 means notify both failed and successful logins
	// - 1 means notify failed logins
	// - 2 means notify successful logins
	PostLoginScope int `json:"post_login_scope" mapstructure:"post_login_scope"`
	// Absolute path to an external program or an HTTP URL to invoke just before password
	// authentication. This hook allows you to externally check the provided password,
	// its main use case is to allow to easily support things like password+OTP for protocols
	// without keyboard interactive support such as FTP and WebDAV. You can ask your users
	// to login using a string consisting of a fixed password and a One Time Token, you
	// can verify the token inside the hook and ask to SFTPGo to verify the fixed part.
	CheckPasswordHook string `json:"check_password_hook" mapstructure:"check_password_hook"`
	// CheckPasswordScope defines the scope for the check password hook.
	// - 0 means all protocols
	// - 1 means SSH
	// - 2 means FTP
	// - 4 means WebDAV
	// you can combine the scopes, for example 6 means FTP and WebDAV
	CheckPasswordScope int `json:"check_password_scope" mapstructure:"check_password_scope"`
	// Defines how the database will be initialized/updated:
	// - 0 means automatically
	// - 1 means manually using the initprovider sub-command
	UpdateMode int `json:"update_mode" mapstructure:"update_mode"`
	// PasswordHashing defines the configuration for password hashing
	PasswordHashing PasswordHashing `json:"password_hashing" mapstructure:"password_hashing"`
	// PreferDatabaseCredentials indicates whether credential files (currently used for Google
	// Cloud Storage) should be stored in the database instead of in the directory specified by
	// CredentialsPath.
	PreferDatabaseCredentials bool `json:"prefer_database_credentials" mapstructure:"prefer_database_credentials"`
}

Config provider configuration

type ExtensionsFilter

type ExtensionsFilter struct {
	// Virtual path, if no other specific filter is defined, the filter apply for
	// sub directories too.
	// For example if filters are defined for the paths "/" and "/sub" then the
	// filters for "/" are applied for any file outside the "/sub" directory
	Path string `json:"path"`
	// only files with these, case insensitive, extensions are allowed.
	// Shell like expansion is not supported so you have to specify ".jpg" and
	// not "*.jpg". If you want shell like patterns use pattern filters
	AllowedExtensions []string `json:"allowed_extensions,omitempty"`
	// files with these, case insensitive, extensions are not allowed.
	// Denied file extensions are evaluated before the allowed ones
	DeniedExtensions []string `json:"denied_extensions,omitempty"`
}

ExtensionsFilter defines filters based on file extensions. These restrictions do not apply to files listing for performance reasons, so a denied file cannot be downloaded/overwritten/renamed but will still be in the list of files. System commands such as Git and rsync interacts with the filesystem directly and they are not aware about these restrictions so they are not allowed inside paths with extensions filters

type Filesystem

type Filesystem struct {
	Provider     FilesystemProvider `json:"provider"`
	S3Config     vfs.S3FsConfig     `json:"s3config,omitempty"`
	GCSConfig    vfs.GCSFsConfig    `json:"gcsconfig,omitempty"`
	AzBlobConfig vfs.AzBlobFsConfig `json:"azblobconfig,omitempty"`
}

Filesystem defines cloud storage filesystem details

type FilesystemProvider added in v1.1.0

type FilesystemProvider int

FilesystemProvider defines the supported storages

const (
	LocalFilesystemProvider     FilesystemProvider = iota // Local
	S3FilesystemProvider                                  // AWS S3 compatible
	GCSFilesystemProvider                                 // Google Cloud Storage
	AzureBlobFilesystemProvider                           // Azure Blob Storage
)

supported values for FilesystemProvider

type MemoryProvider

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

MemoryProvider auth provider for a memory store

type MethodDisabledError

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

MethodDisabledError raised if a method is disabled in config file. For example, if user management is disabled, this error is raised every time a user operation is done using the REST API

func (*MethodDisabledError) Error

func (e *MethodDisabledError) Error() string

Method disabled error details

type MySQLProvider

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

MySQLProvider auth provider for MySQL/MariaDB database

type PGSQLProvider

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

PGSQLProvider auth provider for PostgreSQL database

type PasswordHashing added in v1.1.0

type PasswordHashing struct {
	Argon2Options Argon2Options `json:"argon2_options" mapstructure:"argon2_options"`
}

PasswordHashing defines the configuration for password hashing

type PatternsFilter added in v1.2.2

type PatternsFilter struct {
	// Virtual path, if no other specific filter is defined, the filter apply for
	// sub directories too.
	// For example if filters are defined for the paths "/" and "/sub" then the
	// filters for "/" are applied for any file outside the "/sub" directory
	Path string `json:"path"`
	// files with these, case insensitive, patterns are allowed.
	// Denied file patterns are evaluated before the allowed ones
	AllowedPatterns []string `json:"allowed_patterns,omitempty"`
	// files with these, case insensitive, patterns are not allowed.
	// Denied file patterns are evaluated before the allowed ones
	DeniedPatterns []string `json:"denied_patterns,omitempty"`
}

PatternsFilter defines filters based on shell like patterns. These restrictions do not apply to files listing for performance reasons, so a denied file cannot be downloaded/overwritten/renamed but will still be in the list of files. System commands such as Git and rsync interacts with the filesystem directly and they are not aware about these restrictions so they are not allowed inside paths with extensions filters

type Provider

type Provider interface {
	// contains filtered or unexported methods
}

Provider defines the interface that data providers must implement.

type RecordNotFoundError

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

RecordNotFoundError raised if a requested user is not found

func (*RecordNotFoundError) Error

func (e *RecordNotFoundError) Error() string

type SQLiteProvider

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

SQLiteProvider auth provider for SQLite database

type User

type User struct {
	// Database unique identifier
	ID int64 `json:"id"`
	// 1 enabled, 0 disabled (login is not allowed)
	Status int `json:"status"`
	// Username
	Username string `json:"username"`
	// Account expiration date as unix timestamp in milliseconds. An expired account cannot login.
	// 0 means no expiration
	ExpirationDate int64 `json:"expiration_date"`
	// Password used for password authentication.
	// For users created using SFTPGo REST API the password is be stored using argon2id hashing algo.
	// Checking passwords stored with bcrypt, pbkdf2, md5crypt and sha512crypt is supported too.
	Password string `json:"password,omitempty"`
	// PublicKeys used for public key authentication. At least one between password and a public key is mandatory
	PublicKeys []string `json:"public_keys,omitempty"`
	// The user cannot upload or download files outside this directory. Must be an absolute path
	HomeDir string `json:"home_dir"`
	// Mapping between virtual paths and filesystem paths outside the home directory.
	// Supported for local filesystem only
	VirtualFolders []vfs.VirtualFolder `json:"virtual_folders,omitempty"`
	// If sftpgo runs as root system user then the created files and directories will be assigned to this system UID
	UID int `json:"uid"`
	// If sftpgo runs as root system user then the created files and directories will be assigned to this system GID
	GID int `json:"gid"`
	// Maximum concurrent sessions. 0 means unlimited
	MaxSessions int `json:"max_sessions"`
	// Maximum size allowed as bytes. 0 means unlimited
	QuotaSize int64 `json:"quota_size"`
	// Maximum number of files allowed. 0 means unlimited
	QuotaFiles int `json:"quota_files"`
	// List of the granted permissions
	Permissions map[string][]string `json:"permissions"`
	// Used quota as bytes
	UsedQuotaSize int64 `json:"used_quota_size"`
	// Used quota as number of files
	UsedQuotaFiles int `json:"used_quota_files"`
	// Last quota update as unix timestamp in milliseconds
	LastQuotaUpdate int64 `json:"last_quota_update"`
	// Maximum upload bandwidth as KB/s, 0 means unlimited
	UploadBandwidth int64 `json:"upload_bandwidth"`
	// Maximum download bandwidth as KB/s, 0 means unlimited
	DownloadBandwidth int64 `json:"download_bandwidth"`
	// Last login as unix timestamp in milliseconds
	LastLogin int64 `json:"last_login"`
	// Additional restrictions
	Filters UserFilters `json:"filters"`
	// Filesystem configuration details
	FsConfig Filesystem `json:"filesystem"`
}

User defines a SFTPGo user

func CheckKeyboardInteractiveAuth

func CheckKeyboardInteractiveAuth(username, authHook string, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (User, error)

CheckKeyboardInteractiveAuth checks the keyboard interactive authentication and returns the authenticated user or an error

func CheckUserAndPass

func CheckUserAndPass(username, password, ip, protocol string) (User, error)

CheckUserAndPass retrieves the SFTP user with the given username and password if a match is found or an error

func CheckUserAndPubKey

func CheckUserAndPubKey(username string, pubKey []byte, ip, protocol string) (User, string, error)

CheckUserAndPubKey retrieves the SFTP user with the given username and public key if a match is found or an error

func GetUserByID

func GetUserByID(ID int64) (User, error)

GetUserByID returns the user with the given database ID if a match is found or an error

func GetUsers

func GetUsers(limit, offset int, order string, username string) ([]User, error)

GetUsers returns an array of users respecting limit and offset and filtered by username exact match if not empty

func HideUserSensitiveData

func HideUserSensitiveData(user *User) User

HideUserSensitiveData hides user sensitive data

func UserExists

func UserExists(username string) (User, error)

UserExists checks if the given SFTP username exists, returns an error if no match is found

func (*User) AddVirtualDirs

func (u *User) AddVirtualDirs(list []os.FileInfo, sftpPath string) []os.FileInfo

AddVirtualDirs adds virtual folders, if defined, to the given files list

func (User) GetAllowedIPAsString

func (u User) GetAllowedIPAsString() string

GetAllowedIPAsString returns the allowed IP as comma separated string

func (*User) GetAllowedLoginMethods

func (u *User) GetAllowedLoginMethods() []string

GetAllowedLoginMethods returns the allowed login methods

func (*User) GetBandwidthAsString

func (u *User) GetBandwidthAsString() string

GetBandwidthAsString returns bandwidth limits if defines

func (User) GetDeniedIPAsString

func (u User) GetDeniedIPAsString() string

GetDeniedIPAsString returns the denied IP as comma separated string

func (*User) GetExpirationDateAsString

func (u *User) GetExpirationDateAsString() string

GetExpirationDateAsString returns expiration date formatted as YYYY-MM-DD

func (*User) GetFilesystem

func (u *User) GetFilesystem(connectionID string) (vfs.Fs, error)

GetFilesystem returns the filesystem for this user

func (*User) GetFiltersAsJSON

func (u *User) GetFiltersAsJSON() ([]byte, error)

GetFiltersAsJSON returns the filters as json byte array

func (*User) GetFsConfigAsJSON

func (u *User) GetFsConfigAsJSON() ([]byte, error)

GetFsConfigAsJSON returns the filesystem config as json byte array

func (*User) GetGID

func (u *User) GetGID() int

GetGID returns a validate gid, suitable for use with os.Chown

func (*User) GetHomeDir

func (u *User) GetHomeDir() string

GetHomeDir returns the shortest path name equivalent to the user's home directory

func (*User) GetInfoString

func (u *User) GetInfoString() string

GetInfoString returns user's info as string. Storage provider, number of public keys, max sessions, uid, gid, denied and allowed IP/Mask are returned

func (*User) GetNextAuthMethods

func (u *User) GetNextAuthMethods(partialSuccessMethods []string, isPasswordAuthEnabled bool) []string

GetNextAuthMethods returns the list of authentications methods that can continue for multi-step authentication

func (*User) GetPermissionsAsJSON

func (u *User) GetPermissionsAsJSON() ([]byte, error)

GetPermissionsAsJSON returns the permissions as json byte array

func (*User) GetPermissionsAsString

func (u *User) GetPermissionsAsString() string

GetPermissionsAsString returns the user's permissions as comma separated string

func (*User) GetPermissionsForPath

func (u *User) GetPermissionsForPath(p string) []string

GetPermissionsForPath returns the permissions for the given path. The path must be an SFTP path

func (*User) GetPublicKeysAsJSON

func (u *User) GetPublicKeysAsJSON() ([]byte, error)

GetPublicKeysAsJSON returns the public keys as json byte array

func (*User) GetQuotaSummary

func (u *User) GetQuotaSummary() string

GetQuotaSummary returns used quota and limits if defined

func (*User) GetUID

func (u *User) GetUID() int

GetUID returns a validate uid, suitable for use with os.Chown

func (*User) GetVirtualFolderForPath

func (u *User) GetVirtualFolderForPath(sftpPath string) (vfs.VirtualFolder, error)

GetVirtualFolderForPath returns the virtual folder containing the specified sftp path. If the path is not inside a virtual folder an error is returned

func (*User) HasNoQuotaRestrictions

func (u *User) HasNoQuotaRestrictions(checkFiles bool) bool

HasNoQuotaRestrictions returns true if no quota restrictions need to be applyed

func (*User) HasOverlappedMappedPaths

func (u *User) HasOverlappedMappedPaths() bool

HasOverlappedMappedPaths returns true if this user has virtual folders with overlapped mapped paths

func (*User) HasPerm

func (u *User) HasPerm(permission, path string) bool

HasPerm returns true if the user has the given permission or any permission

func (*User) HasPermissionsInside

func (u *User) HasPermissionsInside(sftpPath string) bool

HasPermissionsInside returns true if the specified sftpPath has no permissions itself and no subdirs with defined permissions

func (*User) HasPerms

func (u *User) HasPerms(permissions []string, path string) bool

HasPerms return true if the user has all the given permissions

func (*User) HasQuotaRestrictions

func (u *User) HasQuotaRestrictions() bool

HasQuotaRestrictions returns true if there is a quota restriction on number of files or size or both

func (*User) HasVirtualFoldersInside

func (u *User) HasVirtualFoldersInside(sftpPath string) bool

HasVirtualFoldersInside returns true if there are virtual folders inside the specified SFTP path. We assume that path are cleaned

func (*User) IsFileAllowed

func (u *User) IsFileAllowed(virtualPath string) bool

IsFileAllowed returns true if the specified file is allowed by the file restrictions filters

func (*User) IsLoginFromAddrAllowed

func (u *User) IsLoginFromAddrAllowed(remoteAddr string) bool

IsLoginFromAddrAllowed returns true if the login is allowed from the specified remoteAddr. If AllowedIP is defined only the specified IP/Mask can login. If DeniedIP is defined the specified IP/Mask cannot login. If an IP is both allowed and denied then login will be denied

func (*User) IsLoginMethodAllowed

func (u *User) IsLoginMethodAllowed(loginMethod string, partialSuccessMethods []string) bool

IsLoginMethodAllowed returns true if the specified login method is allowed

func (*User) IsMappedPath

func (u *User) IsMappedPath(fsPath string) bool

IsMappedPath returns true if the specified filesystem path has a virtual folder mapping. The filesystem path must be cleaned before calling this method

func (*User) IsPartialAuth

func (u *User) IsPartialAuth(loginMethod string) bool

IsPartialAuth returns true if the specified login method is a step for a multi-step Authentication. We support publickey+password and publickey+keyboard-interactive, so only publickey can returns partial success. We can have partial success if only multi-step Auth methods are enabled

func (*User) IsVirtualFolder

func (u *User) IsVirtualFolder(sftpPath string) bool

IsVirtualFolder returns true if the specified sftp path is a virtual folder

type UserActions added in v1.1.0

type UserActions struct {
	// Valid values are add, update, delete. Empty slice to disable
	ExecuteOn []string `json:"execute_on" mapstructure:"execute_on"`
	// Absolute path to an external program or an HTTP URL
	Hook string `json:"hook" mapstructure:"hook"`
}

UserActions defines the action to execute on user create, update, delete.

type UserFilters

type UserFilters struct {
	// only clients connecting from these IP/Mask are allowed.
	// IP/Mask must be in CIDR notation as defined in RFC 4632 and RFC 4291
	// for example "192.0.2.0/24" or "2001:db8::/32"
	AllowedIP []string `json:"allowed_ip,omitempty"`
	// clients connecting from these IP/Mask are not allowed.
	// Denied rules will be evaluated before allowed ones
	DeniedIP []string `json:"denied_ip,omitempty"`
	// these login methods are not allowed.
	// If null or empty any available login method is allowed
	DeniedLoginMethods []string `json:"denied_login_methods,omitempty"`
	// these protocols are not allowed.
	// If null or empty any available protocol is allowed
	DeniedProtocols []string `json:"denied_protocols,omitempty"`
	// filters based on file extensions.
	// Please note that these restrictions can be easily bypassed.
	FileExtensions []ExtensionsFilter `json:"file_extensions,omitempty"`
	// filter based on shell patterns
	FilePatterns []PatternsFilter `json:"file_patterns,omitempty"`
	// max size allowed for a single upload, 0 means unlimited
	MaxUploadFileSize int64 `json:"max_upload_file_size,omitempty"`
}

UserFilters defines additional restrictions for a user

type ValidationError

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

ValidationError raised if input data is not valid

func (*ValidationError) Error

func (e *ValidationError) Error() string

Validation error details

Jump to

Keyboard shortcuts

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