mirror of
https://github.com/gtsteffaniak/filebrowser.git
synced 2026-11-26 08:29:41 -05:00
+11



![coderabbitai[bot]](/avatar/4a08c485fbe908b864e4cf902fddaff20a4dd8a58faf8f65f051648bd2ef3153?size=40)




45a14bf2f2
Signed-off-by: MichaIng <micha@dietpi.com> Co-authored-by: Kevin B. <kurami32_kbm@proton.me> Co-authored-by: Cursor <cursoragent@cursor.com> 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> Co-authored-by: yzxcj797 <54314860+yzxcj797@users.noreply.github.com> Co-authored-by: yzxcj797 <yzxcj797@users.noreply.github.com> Co-authored-by: DireMunchkin <dire.munchkin@proton.me> Co-authored-by: Chris <39135018+Chri6s@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: Aditya Raj Singh <github@adityaraj.com> Co-authored-by: tbsagdic <86909795+tbsagdic@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Ethan Lee Qi Yang <pluscompanyhqDEPT@gmail.com> Co-authored-by: Aditya Raj Singh <aditya@bncw.in> Co-authored-by: MichaIng <micha@dietpi.com> Co-authored-by: FandacqkaCorp <david@davidyloreto.com> Co-authored-by: FandacqkaCorp <275647464+FandacqkaCorp@users.noreply.github.com> Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: connorjfarrell <connorjfarrell@users.noreply.github.com>
329 lines
9.7 KiB
Go
329 lines
9.7 KiB
Go
package cmd
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"reflect"
|
|
"strings"
|
|
|
|
"github.com/gtsteffaniak/filebrowser/backend/internal/adapters/fs/fileutils"
|
|
"github.com/gtsteffaniak/filebrowser/backend/internal/database/users"
|
|
"github.com/gtsteffaniak/filebrowser/backend/internal/state"
|
|
"github.com/gtsteffaniak/filebrowser/backend/internal/usersidebar"
|
|
"github.com/gtsteffaniak/filebrowser/backend/pkg/settings"
|
|
"github.com/gtsteffaniak/go-logger/logger"
|
|
)
|
|
|
|
var createBackup = false
|
|
|
|
// addApiToken registers a raw API token's hash with access storage. It is a
|
|
// variable so tests can inject a failing registration deterministically.
|
|
var addApiToken = state.AddApiToken
|
|
|
|
func validateUserInfo(newDB bool) {
|
|
// update source info for users if names/sources/paths might have changed
|
|
usersList, err := state.GetAllUsers()
|
|
if err != nil {
|
|
logger.Fatalf("could not load users: %v", err)
|
|
}
|
|
for i := range usersList {
|
|
user := &usersList[i]
|
|
changedFields := make([]string, 0, 8)
|
|
changePass := false
|
|
|
|
scopesChanged := updateUserScopes(user)
|
|
if scopesChanged {
|
|
changedFields = append(changedFields, "backendScopes")
|
|
}
|
|
if updatePermissions(user) {
|
|
changedFields = append(changedFields, "permissions", "perm", "version")
|
|
}
|
|
if updateSourcePermissions(user) {
|
|
changedFields = append(changedFields, "backendScopes", "backendSourcePermissions", "version")
|
|
}
|
|
if updatePreviewSettings(user) {
|
|
changedFields = append(changedFields, "preview")
|
|
}
|
|
if updateLoginType(user) {
|
|
changedFields = append(changedFields, "loginMethod")
|
|
}
|
|
if updateShowFirstLogin(user) {
|
|
changedFields = append(changedFields, "showFirstLogin")
|
|
}
|
|
if updateSidebarLinks(user, scopesChanged) {
|
|
changedFields = append(changedFields, "sidebarLinks")
|
|
}
|
|
if updateTokens(user) {
|
|
changedFields = append(changedFields, "tokens", "version")
|
|
}
|
|
if normalizeApiTokenPermissions(user) {
|
|
changedFields = append(changedFields, "tokens")
|
|
}
|
|
tokenBackfillChanged, tokenBackfillFailed := updateTokenHashBackfill(user)
|
|
if tokenBackfillChanged && !tokenBackfillFailed {
|
|
changedFields = append(changedFields, "tokens", "version")
|
|
} else if tokenBackfillChanged {
|
|
changedFields = append(changedFields, "tokens")
|
|
}
|
|
if state.ApplyEnforcedSyncToUser(user) {
|
|
changedFields = append(changedFields, settings.UserJSONFieldsForEnforcedSync()...)
|
|
}
|
|
if state.ApplyEnforcedSourcePermissionsSyncToUser(user) {
|
|
changedFields = append(changedFields, "backendScopes", "backendSourcePermissions")
|
|
}
|
|
if bumpToNewestVersion(user, tokenBackfillFailed) {
|
|
changedFields = append(changedFields, "version")
|
|
}
|
|
adminUser := settings.PasswordAdminUsername()
|
|
if user.Username == adminUser && user.Permissions.Admin {
|
|
adminPerms := settings.AdminPerms()
|
|
if user.Permissions.Share != adminPerms.Share || user.Permissions.Api != adminPerms.Api {
|
|
user.Permissions.Share = adminPerms.Share
|
|
user.Permissions.Api = adminPerms.Api
|
|
user.Permissions.Admin = true
|
|
changedFields = append(changedFields, "permissions")
|
|
}
|
|
}
|
|
if user.Username == adminUser && settings.ConfigTriggersAdminPasswordReset() && user.LoginMethod == users.LoginMethodPassword {
|
|
logger.Info("Resetting admin user to default username and password.")
|
|
user.Permissions = settings.AdminPerms()
|
|
user.Password = settings.PasswordAdminPassword()
|
|
user.LoginMethod = users.LoginMethodPassword
|
|
changedFields = append(changedFields, "permissions", "password", "loginMethod")
|
|
changePass = true
|
|
}
|
|
|
|
changedFields = dedupeFields(changedFields)
|
|
if len(changedFields) == 0 {
|
|
continue
|
|
}
|
|
|
|
skipCreateBackup := os.Getenv("FILEBROWSER_DISABLE_AUTOMATIC_BACKUP") == "true" || newDB
|
|
if createBackup && !skipCreateBackup {
|
|
logger.Warning("Incompatible user settings detected, creating backup of database before converting.")
|
|
err = fileutils.CopyFile(settings.Config.Server.DatabaseV2.Path, fmt.Sprintf("%s.bak", settings.Config.Server.DatabaseV2.Path))
|
|
if err != nil {
|
|
logger.Fatalf("Unable to create automatic backup of database due to error: %v", err)
|
|
}
|
|
}
|
|
plainPass := ""
|
|
if changePass {
|
|
plainPass = user.Password
|
|
}
|
|
if err := state.UpdateUser(user, plainPass, changedFields...); err != nil {
|
|
logger.Errorf("could not update user: %v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func dedupeFields(fields []string) []string {
|
|
seen := make(map[string]struct{}, len(fields))
|
|
out := make([]string, 0, len(fields))
|
|
for _, field := range fields {
|
|
field = strings.TrimSpace(field)
|
|
if field == "" {
|
|
continue
|
|
}
|
|
key := strings.ToLower(field)
|
|
if _, ok := seen[key]; ok {
|
|
continue
|
|
}
|
|
seen[key] = struct{}{}
|
|
out = append(out, field)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func updateUserScopes(user *users.User) bool {
|
|
newScopes := settings.MergeDefaultEnabledBackendScopes(user.BackendScopes, user.DeclinedDefaultSources)
|
|
changed := !reflect.DeepEqual(user.BackendScopes, newScopes)
|
|
user.BackendScopes = newScopes
|
|
return changed
|
|
}
|
|
|
|
func updateSourcePermissions(user *users.User) bool {
|
|
changed := false
|
|
if user.Version < users.SourcePermissionsMigrationVersion {
|
|
if users.MigrateToSourcePermissions(user) {
|
|
changed = true
|
|
}
|
|
}
|
|
if users.EnsureSourcePermissionsForScopes(
|
|
user,
|
|
settings.DefaultSourceFilePermissions(),
|
|
settings.AdminSourceFilePermissions(),
|
|
) {
|
|
changed = true
|
|
}
|
|
return changed
|
|
}
|
|
|
|
func updateShowFirstLogin(user *users.User) bool {
|
|
if user.ShowFirstLogin && !settings.Env.IsFirstLoad {
|
|
user.ShowFirstLogin = false
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// func to convert legacy user with perm key to permissions
|
|
func updatePermissions(user *users.User) bool {
|
|
if user.Version >= users.PermMigrationVersion {
|
|
return false
|
|
}
|
|
updateUser := true
|
|
user.Permissions.Download = true
|
|
// if any keys are true, set the permissions to true
|
|
if user.Perm.Api {
|
|
user.Permissions.Api = true
|
|
user.Perm.Api = false
|
|
updateUser = true
|
|
}
|
|
if user.Perm.Admin {
|
|
user.Permissions.Admin = true
|
|
user.Perm.Admin = false
|
|
updateUser = true
|
|
}
|
|
if user.Perm.Modify {
|
|
user.Permissions.Modify = true
|
|
user.Perm.Modify = false
|
|
updateUser = true
|
|
}
|
|
if user.Perm.Share {
|
|
user.Permissions.Share = true
|
|
user.Perm.Share = false
|
|
updateUser = true
|
|
}
|
|
if user.Perm.Create {
|
|
user.Permissions.Create = true
|
|
user.Perm.Create = false
|
|
updateUser = true
|
|
}
|
|
if user.Perm.Create {
|
|
user.Permissions.Create = true
|
|
user.Perm.Create = false
|
|
updateUser = true
|
|
}
|
|
if user.Perm.Download {
|
|
user.Permissions.Download = true
|
|
user.Perm.Download = false
|
|
updateUser = true
|
|
}
|
|
if user.Permissions.Modify {
|
|
user.Permissions.Create = true
|
|
user.Permissions.Delete = true
|
|
updateUser = true
|
|
}
|
|
user.Version = users.PermMigrationVersion
|
|
if updateUser {
|
|
createBackup = true
|
|
}
|
|
return updateUser
|
|
}
|
|
|
|
func updateLoginType(user *users.User) bool {
|
|
if user.LoginMethod == "" {
|
|
user.LoginMethod = users.LoginMethodPassword
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
func updatePreviewSettings(user *users.User) bool {
|
|
// if user hasn't been updated yet
|
|
if user.LoginMethod == "" {
|
|
user.Preview.Image = true
|
|
user.Preview.PopUp = true
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// updateSidebarLinks normalizes saved links and adds defaults for new or changed scopes.
|
|
func updateSidebarLinks(user *users.User, scopesChanged bool) bool {
|
|
links, changed := usersidebar.NormalizeSidebarLinks(user.SidebarLinks)
|
|
if scopesChanged || user.SidebarLinks == nil {
|
|
links, changed = usersidebar.PrepareSidebarLinksForPersist(user.SidebarLinks, user.BackendScopes)
|
|
}
|
|
if !changed {
|
|
return false
|
|
}
|
|
|
|
user.SidebarLinks = links
|
|
return true
|
|
}
|
|
|
|
func updateTokens(user *users.User) bool {
|
|
if user.Version >= users.TokenMigrationVersion {
|
|
return false
|
|
}
|
|
if user.ApiKeys != nil {
|
|
user.Tokens = make(map[string]users.AuthToken)
|
|
for name, token := range user.ApiKeys {
|
|
token.Token = token.Key
|
|
token.Name = name
|
|
users.StoreToken(user.Tokens, token)
|
|
}
|
|
}
|
|
user.Version = users.TokenMigrationVersion
|
|
return true
|
|
}
|
|
|
|
func normalizeApiTokenPermissions(user *users.User) bool {
|
|
if user == nil || len(user.Tokens) == 0 {
|
|
return false
|
|
}
|
|
changed := false
|
|
for name, token := range user.Tokens {
|
|
if token.Name == "" || name != token.Name {
|
|
continue
|
|
}
|
|
sanitized := users.SanitizeTokenPermissions(token.Permissions)
|
|
if sanitized != token.Permissions {
|
|
token.Permissions = sanitized
|
|
user.Tokens[name] = token
|
|
changed = true
|
|
}
|
|
}
|
|
return changed
|
|
}
|
|
|
|
// updateTokenHashBackfill promotes legacy ApiKeys into Tokens and registers a
|
|
// hashed_tokens row for every stored raw JWT so strict server-side auth (which
|
|
// ignores BelongsTo) accepts pre-2.0.8 tokens. Runs once per user via
|
|
// TokenHashBackfillVersion. It reports (changed, failed): when hash
|
|
// registration fails the version is left alone so callers skip the newest
|
|
// bump and the backfill retries on next startup.
|
|
func updateTokenHashBackfill(user *users.User) (bool, bool) {
|
|
if user == nil || user.Version >= users.TokenHashBackfillVersion {
|
|
return false, false
|
|
}
|
|
before := len(user.Tokens)
|
|
promoteLegacyApiKeysBeforeSQLite(user)
|
|
changed := len(user.Tokens) != before
|
|
hashesRegistered := true
|
|
for _, raw := range state.CollectStoredRawTokens(user) {
|
|
if err := addApiToken(raw, user.ID); err != nil {
|
|
logger.Errorf("could not register token hash for user %s: %v", user.Username, err)
|
|
hashesRegistered = false
|
|
}
|
|
}
|
|
if hashesRegistered {
|
|
user.Version = users.TokenHashBackfillVersion
|
|
createBackup = true
|
|
return true, false
|
|
}
|
|
return changed, true
|
|
}
|
|
|
|
// bumpToNewestVersion stamps the user at NewestUserVersion. It is skipped when
|
|
// a migration failed so the failed migration retries on next startup instead
|
|
// of being buried by the catch-all bump.
|
|
func bumpToNewestVersion(user *users.User, migrationFailed bool) bool {
|
|
if migrationFailed || user == nil || user.Version >= users.NewestUserVersion {
|
|
return false
|
|
}
|
|
user.Version = users.NewestUserVersion
|
|
return true
|
|
}
|