mirror of
https://github.com/filebrowser/filebrowser.git
synced 2024-06-07 23:00:43 +00:00
fa86894550
License: MIT
Signed-off-by: Henrique Dias <hacdias@gmail.com>
Former-commit-id: 984c56e0b9a9169b10c6017fbd68ab4fbd3868d7 [formerly 27c43314222c723a220b9b1d2141e1509ed05627] [formerly 0a9f6c47bff2d653035c93765ea08ade73ec450c [formerly b7fdcc3ee9
]]
Former-commit-id: c27e7fa41f20f433a9a0a97ecc40ab78968b43dc [formerly 185db4a17969cd4fb76cc2b06bd58221c9c6c100]
Former-commit-id: 9b26d1b0642c61cd38f7cdf422f95b2bf9a9614d
79 lines
2.1 KiB
Go
79 lines
2.1 KiB
Go
package settings
|
|
|
|
import (
|
|
"errors"
|
|
"log"
|
|
"os"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/spf13/afero"
|
|
)
|
|
|
|
var (
|
|
invalidFilenameChars = regexp.MustCompile(`[^0-9A-Za-z@_\-.]`)
|
|
|
|
dashes = regexp.MustCompile(`[\-]+`)
|
|
)
|
|
|
|
// MakeUserDir makes the user directory according to settings.
|
|
func (settings *Settings) MakeUserDir(username, userScope, serverRoot string) (string, error) {
|
|
var err error
|
|
userScope = strings.TrimSpace(userScope)
|
|
if userScope == "" || userScope == "./" {
|
|
userScope = "."
|
|
}
|
|
|
|
if !settings.CreateUserDir {
|
|
return userScope, nil
|
|
}
|
|
|
|
fs := afero.NewBasePathFs(afero.NewOsFs(), serverRoot)
|
|
|
|
//use the default auto create logic only if specific scope is not the default scope
|
|
if userScope != settings.Defaults.Scope {
|
|
//try create the dir, for example: settings.Defaults.Scope == "." and userScope == "./foo"
|
|
if userScope != "." {
|
|
err = fs.MkdirAll(userScope, os.ModePerm)
|
|
if err != nil {
|
|
log.Printf("create user: failed to mkdir user home dir: [%s]", userScope)
|
|
}
|
|
}
|
|
return userScope, err
|
|
}
|
|
|
|
//clean username first
|
|
username = cleanUsername(username)
|
|
if username == "" || username == "-" || username == "." {
|
|
log.Printf("create user: invalid user for home dir creation: [%s]", username)
|
|
return "", errors.New("invalid user for home dir creation")
|
|
}
|
|
|
|
//create default user dir
|
|
userHomeBase := settings.Defaults.Scope + string(os.PathSeparator) + "users"
|
|
userHome := userHomeBase + string(os.PathSeparator) + username
|
|
err = fs.MkdirAll(userHome, os.ModePerm)
|
|
if err != nil {
|
|
log.Printf("create user: failed to mkdir user home dir: [%s]", userHome)
|
|
} else {
|
|
log.Printf("create user: mkdir user home dir: [%s] successfully.", userHome)
|
|
}
|
|
return userHome, err
|
|
}
|
|
|
|
func cleanUsername(s string) string {
|
|
|
|
// Remove any trailing space to avoid ending on -
|
|
s = strings.Trim(s, " ")
|
|
|
|
s = strings.Replace(s, "..", "", -1)
|
|
|
|
// Replace all characters which not in the list `0-9A-Za-z@_\-.` with a dash
|
|
s = invalidFilenameChars.ReplaceAllString(s, "-")
|
|
|
|
// Remove any multiple dashes caused by replacements above
|
|
s = dashes.ReplaceAllString(s, "-")
|
|
|
|
return s
|
|
}
|