forked from upstream/filebrowser
Co-authored-by: Mattijs Bliek <mattijs@mattijsbliek.com> Co-authored-by: GammelSami <39372285+GammelSami@users.noreply.github.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
367 lines
18 KiB
Go
367 lines
18 KiB
Go
package users
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
jwt "github.com/golang-jwt/jwt/v4"
|
|
)
|
|
|
|
// ProfileStorageVersion is the user version after nested profile JSON in user_data.
|
|
const ProfileStorageVersion = 5
|
|
|
|
// CurrentUserMigrationVersion is persisted for newly created accounts and after legacy migrations finish.
|
|
const CurrentUserMigrationVersion = ProfileStorageVersion
|
|
|
|
type LoginMethod string
|
|
|
|
const (
|
|
LoginMethodPassword LoginMethod = "password"
|
|
LoginMethodProxy LoginMethod = "proxy"
|
|
LoginMethodOidc LoginMethod = "oidc"
|
|
LoginMethodLdap LoginMethod = "ldap"
|
|
LoginMethodJwt LoginMethod = "jwt"
|
|
)
|
|
|
|
// AnonymousUserName is the username for unauthenticated requests (user_id 0).
|
|
const AnonymousUserName = "anonymous"
|
|
|
|
var reservedUsernames = map[string]struct{}{
|
|
strings.ToLower(AnonymousUserName): {},
|
|
}
|
|
|
|
// ValidateUsername rejects empty and reserved login names.
|
|
func ValidateUsername(username string) error {
|
|
username = strings.TrimSpace(username)
|
|
if username == "" {
|
|
return fmt.Errorf("username is empty")
|
|
}
|
|
if _, reserved := reservedUsernames[strings.ToLower(username)]; reserved {
|
|
return fmt.Errorf("username %q is reserved", username)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// WebAuthnCredentialFlags mirrors the boolean flags from authenticator data.
|
|
type WebAuthnCredentialFlags struct {
|
|
UserPresent bool `json:"userPresent"`
|
|
UserVerified bool `json:"userVerified"`
|
|
BackupEligible bool `json:"backupEligible"`
|
|
BackupState bool `json:"backupState"`
|
|
}
|
|
|
|
// WebAuthnCredential stores a single passkey credential in BoltDB-friendly format.
|
|
type WebAuthnCredential struct {
|
|
ID string `json:"id"`
|
|
PublicKey string `json:"publicKey"`
|
|
AttestationType string `json:"attestationType"`
|
|
AttestationFormat string `json:"attestationFormat"`
|
|
Transport []string `json:"transport"`
|
|
Flags WebAuthnCredentialFlags `json:"flags"`
|
|
AAGUID string `json:"aaguid"`
|
|
SignCount uint32 `json:"signCount"`
|
|
CloneWarning bool `json:"cloneWarning"`
|
|
Name string `json:"name"`
|
|
CreatedAt int64 `json:"createdAt"`
|
|
LastUsedAt int64 `json:"lastUsedAt"`
|
|
ClientDataJSON string `json:"clientDataJSON"`
|
|
ClientDataHash string `json:"clientDataHash"`
|
|
AuthenticatorData string `json:"authenticatorData"`
|
|
PublicKeyAlg int64 `json:"publicKeyAlg"`
|
|
AttestationObj string `json:"attestationObj"`
|
|
}
|
|
|
|
type AuthToken struct {
|
|
MinimalAuthToken
|
|
Key string `json:"key,omitempty"` // for backward compatibility
|
|
Token string `json:"token,omitempty"`
|
|
Name string `json:"name,omitempty"`
|
|
Username string `json:"username,omitempty"`
|
|
BelongsTo uint64 `json:"belongsTo,omitempty"` // numeric user id in JWT claims (bolt-era small ids still work)
|
|
IssuedAt int64 `json:"issuedAt,omitempty"`
|
|
ExpiresAt int64 `json:"expiresAt,omitempty"`
|
|
Permissions Permissions `json:"Permissions,omitempty"`
|
|
}
|
|
|
|
// MinimalAuthToken is used for tokens that only include JWT standard claims
|
|
type MinimalAuthToken struct {
|
|
jwt.RegisteredClaims `swaggerignore:"true"`
|
|
}
|
|
|
|
type Permissions struct {
|
|
Api bool `json:"api"` // allow api access
|
|
Admin bool `json:"admin"` // allow admin access
|
|
Modify bool `json:"modify,omitempty"` // deprecated: legacy user migration only; not used for API tokens
|
|
Share bool `json:"share"` // allow sharing files
|
|
Realtime bool `json:"realtime"` // allow realtime updates
|
|
Delete bool `json:"delete,omitempty"` // deprecated: legacy user migration only; not used for API tokens
|
|
Create bool `json:"create,omitempty"` // deprecated: legacy user migration only; not used for API tokens
|
|
Download bool `json:"download,omitempty"` // deprecated: legacy user migration only; not used for API tokens
|
|
View bool `json:"view,omitempty"` // deprecated: legacy user migration only; not used for API tokens
|
|
}
|
|
|
|
// SourceFilePermissions holds per-source file operation permissions (v4+).
|
|
type SourceFilePermissions struct {
|
|
View bool `json:"view"`
|
|
Download bool `json:"download"`
|
|
Modify bool `json:"modify"`
|
|
Delete bool `json:"delete"`
|
|
Create bool `json:"create"`
|
|
Configured bool `json:"configured,omitempty"` // true when explicitly set (allows intentional deny-all)
|
|
}
|
|
|
|
// MarkSourceFilePermissionsConfigured marks permissions as explicitly set (including deny-all).
|
|
func MarkSourceFilePermissionsConfigured(p SourceFilePermissions) SourceFilePermissions {
|
|
p.Configured = true
|
|
return p
|
|
}
|
|
|
|
// DenyAllSourceFilePermissions returns a SourceFilePermissions with all flags false and Configured set.
|
|
func DenyAllSourceFilePermissions() SourceFilePermissions {
|
|
return MarkSourceFilePermissionsConfigured(SourceFilePermissions{})
|
|
}
|
|
|
|
// IsUnset reports whether no permission bit is set and the value was never explicitly configured.
|
|
func (p SourceFilePermissions) IsUnset() bool {
|
|
if p.Configured {
|
|
return false
|
|
}
|
|
return !p.View && !p.Download && !p.Modify && !p.Delete && !p.Create
|
|
}
|
|
|
|
// HasAnyFilePermission reports whether any file-operation flag is set on token/global claims.
|
|
func (p Permissions) HasAnyFilePermission() bool {
|
|
return p.View || p.Download || p.Modify || p.Delete || p.Create
|
|
}
|
|
|
|
// SortingSettings represents the sorting settings.
|
|
type Sorting struct {
|
|
By string `json:"by"`
|
|
Asc bool `json:"asc"`
|
|
}
|
|
|
|
type Preview struct {
|
|
DisableHideSidebar bool `json:"disableHideSidebar"` // disable the hide sidebar preview for previews and editors
|
|
Image bool `json:"image"` // show thumbnail preview image for image files
|
|
Video bool `json:"video"` // show thumbnail preview image for video files
|
|
Audio bool `json:"audio"` // show thumbnail preview image for audio files
|
|
MotionVideoPreview bool `json:"motionVideoPreview"` // show multiple frames for videos in thumbnail preview when hovering
|
|
Office bool `json:"office"` // show thumbnail preview image for office files
|
|
PopUp bool `json:"popup"` // show larger popup preview when hovering over thumbnail
|
|
AutoplayMedia bool `json:"autoplayMedia"` // autoplay media files in preview
|
|
Folder bool `json:"folder"` // show thumbnail preview image for folder files
|
|
Models bool `json:"models"` // show live thumbnails for 3D models files
|
|
}
|
|
|
|
// FrontendUser holds fields safe to return from user APIs (embedded on User).
|
|
type FrontendUser struct {
|
|
NonAdminEditable
|
|
DisableSettings bool `json:"disableSettings"`
|
|
Username string `json:"username"`
|
|
FrontendScopes []FrontendScope `json:"scopes"`
|
|
LockPassword bool `json:"lockPassword"`
|
|
Permissions Permissions `json:"permissions"` // global: admin, api, share, realtime
|
|
SourcePermissions map[string]SourceFilePermissions `json:"sourcePermissions,omitempty"` // deprecated: use scopes[].permissions
|
|
LoginMethod LoginMethod `json:"loginMethod"`
|
|
OtpEnabled bool `json:"otpEnabled"`
|
|
ShowFirstLogin bool `json:"showFirstLogin"`
|
|
Perm Permissions `json:"perm,omitzero"`
|
|
}
|
|
|
|
// PinnedItems maps source filesystem path -> index directory path -> pinned item names.
|
|
type PinnedItems map[string]map[string][]string
|
|
|
|
// UserLegacyFields holds v1.x user JSON keys migrated on startup (Bolt/SQLite user_data).
|
|
type UserLegacyFields struct {
|
|
ApiKeys map[string]AuthToken `json:"apiKeys,omitempty"`
|
|
}
|
|
|
|
// User is the persisted user: profile/settings in user_data, plus BackendScopes for source access.
|
|
type User struct {
|
|
FrontendUser
|
|
ID uint64 `json:"id,omitempty"`
|
|
// BackendScopes is the authoritative, persisted access list (SourceScope.Name = backend source path).
|
|
// SQLite stores this inside user_data JSON under the key "scopes" (see sqldb.UserData).
|
|
BackendScopes []BackendScope `json:"backendScopes,omitempty"`
|
|
BackendSourcePermissions map[string]SourceFilePermissions `json:"backendSourcePermissions,omitempty"` // key = source path
|
|
Tokens map[string]AuthToken `json:"tokens,omitempty"`
|
|
TOTPSecret string `json:"totpSecret,omitempty"`
|
|
TOTPNonce string `json:"totpNonce,omitempty"`
|
|
PasskeyCredentials []WebAuthnCredential `json:"passkeyCredentials,omitempty"`
|
|
PinnedItems PinnedItems `json:"pinnedItems,omitempty"`
|
|
Version int `json:"version"`
|
|
UserLegacyFields `json:",inline"`
|
|
}
|
|
|
|
type FrontendScope struct {
|
|
Name string `json:"name"` // Bolt: filesystem path; JSON API: display name after prepForFrontend
|
|
Scope string `json:"scope"` // index path within that source
|
|
Permissions *SourceFilePermissions `json:"permissions,omitempty"`
|
|
}
|
|
|
|
type BackendScope struct {
|
|
Path string `json:"path"` // real path for the source
|
|
Scope string `json:"scope"` // index path within that source
|
|
Permissions SourceFilePermissions `json:"permissions,omitempty"`
|
|
}
|
|
|
|
// json tags must match variable name with smaller case first letter
|
|
type NonAdminEditable struct {
|
|
EditorQuickSave bool `json:"editorQuickSave"` // show quick save button in editor
|
|
HideSidebarFileActions bool `json:"hideSidebarFileActions"` // hide the file actions in the sidebar
|
|
DisableQuickToggles bool `json:"disableQuickToggles"` // disable the quick toggles in the sidebar
|
|
DisableSearchOptions bool `json:"disableSearchOptions"` // disable the search options in the search bar
|
|
DeleteWithoutConfirming bool `json:"deleteWithoutConfirming"` // delete files without confirmation
|
|
Preview Preview `json:"preview"`
|
|
StickySidebar bool `json:"stickySidebar"` // keep sidebar open when navigating
|
|
DarkMode bool `json:"darkMode"` // should dark mode be enabled
|
|
Password string `json:"password,omitempty"`
|
|
Locale string `json:"locale"` // language to use: eg. de, en, or fr
|
|
ViewMode string `json:"viewMode"` // view mode to use: eg. normal, list, grid, or compact
|
|
SingleClick bool `json:"singleClick"` // open directory on single click, also enables middle click to open in new tab
|
|
Sorting Sorting `json:"sorting"`
|
|
ShowHidden bool `json:"showHidden"` // show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files
|
|
HideFileExt string `json:"hideFileExt"` // space separated list of file extensions to hide in UI and API
|
|
DateFormat bool `json:"dateFormat"` // when false, the date is relative, when true, the date is an exact timestamp
|
|
GallerySize int `json:"gallerySize"` // 0-9 - the size of the gallery thumbnails
|
|
ThemeColor string `json:"themeColor"` // theme color to use: eg. #ff0000, or var(--red), var(--purple), etc
|
|
QuickDownload bool `json:"quickDownload"` // show icon to download in one click
|
|
DisableUpdateNotifications bool `json:"disableUpdateNotifications"` // disable update notifications
|
|
FileLoading FileLoading `json:"fileLoading"` // upload and download settings
|
|
DisableOfficePreviewExt string `json:"disableOfficePreviewExt"` // deprecated
|
|
DisableOnlyOfficeExt string `json:"disableOnlyOfficeExt"` // deprecated
|
|
DisablePreviewExt string `json:"disablePreviewExt"` // space separated list of file extensions to disable preview for
|
|
DisableViewingExt string `json:"disableViewingExt"` // space separated list of file extensions to disable viewing for
|
|
CustomTheme string `json:"customTheme"` // Name of theme to use chosen from custom themes config.
|
|
ShowSelectMultiple bool `json:"showSelectMultiple"` // show select multiple files on desktop
|
|
ShowCopyPath bool `json:"showCopyPath"` // show copy path action in the context menu
|
|
ShowToolsInSidebar bool `json:"showToolsInSidebar"` // when false, sidebar hides links with category "tool" (default: true)
|
|
DebugOffice bool `json:"debugOffice"` // debug onlyoffice editor
|
|
SidebarLinks []SidebarLink `json:"sidebarLinks"` // customizable sidebar links
|
|
HideFilesInTree bool `json:"hideFilesInTree"` // hide files in the sidebar tree navigation, when true, will show only directories.
|
|
DeleteAfterArchive bool `json:"deleteAfterArchive"` // delete source files after successful creation/extraction of archives
|
|
PreferEditorForMarkdown bool `json:"preferEditorForMarkdown"` // prefer editor first for markdown files instead of the Markdown Viewer
|
|
ShowFirstLogin bool `json:"showFirstLogin"`
|
|
PasskeyCredentials []WebAuthnCredential `json:"passkeyCredentials,omitempty"`
|
|
}
|
|
|
|
type FileLoading struct {
|
|
MaxConcurrent int `json:"maxConcurrentUpload"`
|
|
UploadChunkSize int `json:"uploadChunkSizeMb"`
|
|
ClearAll bool `json:"clearAll"`
|
|
DownloadChunkSize int `json:"downloadChunkSizeMb"`
|
|
}
|
|
|
|
// SidebarLink represents a customizable link in the sidebar.
|
|
type SidebarLink struct {
|
|
Name string `json:"name"` // Display name of the link
|
|
Category string `json:"category"` // Category type: "source", "source-link", "share", "tool", "custom", etc.
|
|
Target string `json:"target"` // Target path/URL for the link (relative for source/share)
|
|
Icon string `json:"icon"` // Material icon name
|
|
SourceName string `json:"sourceName,omitempty"` // Bolt: filesystem path. JSON out: display name (after prepForFrontend).
|
|
}
|
|
|
|
func CleanUsername(s string) string {
|
|
// Remove any trailing space to avoid ending on -
|
|
s = strings.Trim(s, " ")
|
|
s = strings.Replace(s, "..", "", -1)
|
|
return s
|
|
}
|
|
|
|
// SourceNameResolver is a function type that resolves source names to source paths
|
|
// This avoids circular dependencies by allowing the settings package to provide the resolver
|
|
type SourceNameResolver func(sourceName string) (sourcePath string, err error)
|
|
|
|
// SourceInfo represents basic information about a source needed for user operations
|
|
type SourceInfo struct {
|
|
Path string
|
|
Name string
|
|
DefaultUserScope string
|
|
}
|
|
|
|
// SourceConfigProvider provides access to source configuration
|
|
type SourceConfigProvider struct {
|
|
GetSourceByPath func(path string) (SourceInfo, bool)
|
|
GetSourceByName func(name string) (SourceInfo, bool)
|
|
GetAllSources func() []SourceInfo
|
|
GetDefaultScopes func() []BackendScope
|
|
}
|
|
|
|
// Global variables set by the settings package
|
|
var (
|
|
sourceNameResolver SourceNameResolver
|
|
sourceConfig *SourceConfigProvider
|
|
)
|
|
|
|
// SetSourceNameResolver sets the global source name resolver
|
|
// This should be called once during initialization by the settings package
|
|
func SetSourceNameResolver(resolver SourceNameResolver) {
|
|
sourceNameResolver = resolver
|
|
}
|
|
|
|
// SetSourceConfig sets the global source configuration provider
|
|
// This should be called once during initialization by the settings package
|
|
func SetSourceConfig(config *SourceConfigProvider) {
|
|
sourceConfig = config
|
|
}
|
|
|
|
// GetSourceConfig returns the current source configuration provider, or nil if unset.
|
|
func GetSourceConfig() *SourceConfigProvider {
|
|
return sourceConfig
|
|
}
|
|
|
|
// GetSourceNameResolver returns the current source name resolver, or nil if unset.
|
|
func GetSourceNameResolver() SourceNameResolver {
|
|
return sourceNameResolver
|
|
}
|
|
|
|
// SourceConfigLoaded reports whether SetSourceConfig has been called (needed for ResolveSourceKey).
|
|
func SourceConfigLoaded() bool {
|
|
return sourceConfig != nil
|
|
}
|
|
|
|
// GetScopeForSourcePath returns the scope for a given source path (backend-style)
|
|
// This method works with backend-style scopes where Name is the source path
|
|
func (u *User) GetScopeForSourcePath(sourcePath string) (string, error) {
|
|
for _, scope := range u.BackendScopes {
|
|
if scope.Path == sourcePath {
|
|
return scope.Scope, nil
|
|
}
|
|
}
|
|
return "", fmt.Errorf("scope not found for source %v", sourcePath)
|
|
}
|
|
|
|
// GetScopeForSourceName returns the scope for a given source name (frontend-style)
|
|
// Uses the global SourceNameResolver to convert source names to paths
|
|
func (u *User) GetScopeForSourceName(sourceName string) (string, error) {
|
|
if sourceNameResolver == nil {
|
|
return "", fmt.Errorf("source name resolver not initialized")
|
|
}
|
|
|
|
sourcePath, err := sourceNameResolver(sourceName)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return u.GetScopeForSourcePath(sourcePath)
|
|
}
|
|
|
|
// HasSourceByPath checks if the user has access to a given source path
|
|
func (u *User) HasSourceByPath(sourcePath string) bool {
|
|
for _, scope := range u.BackendScopes {
|
|
if scope.Path == sourcePath {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// GetSourcePaths returns all source paths the user has access to
|
|
func (u *User) GetSourcePaths() []string {
|
|
paths := make([]string, 0, len(u.BackendScopes))
|
|
for _, scope := range u.BackendScopes {
|
|
paths = append(paths, scope.Path)
|
|
}
|
|
return paths
|
|
}
|