2019-02-15 23:12:02 +08:00
|
|
|
package settings
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2022-06-03 21:59:36 +08:00
|
|
|
"fmt"
|
2019-02-15 23:12:02 +08:00
|
|
|
"log"
|
|
|
|
"os"
|
2022-06-03 21:59:36 +08:00
|
|
|
"path"
|
2019-02-15 23:12:02 +08:00
|
|
|
"regexp"
|
|
|
|
"strings"
|
2019-04-20 21:15:28 +08:00
|
|
|
|
|
|
|
"github.com/spf13/afero"
|
2019-02-15 23:12:02 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
invalidFilenameChars = regexp.MustCompile(`[^0-9A-Za-z@_\-.]`)
|
|
|
|
|
|
|
|
dashes = regexp.MustCompile(`[\-]+`)
|
|
|
|
)
|
|
|
|
|
2019-04-20 21:15:28 +08:00
|
|
|
// MakeUserDir makes the user directory according to settings.
|
2020-06-01 07:12:36 +08:00
|
|
|
func (s *Settings) MakeUserDir(username, userScope, serverRoot string) (string, error) {
|
2019-02-15 23:12:02 +08:00
|
|
|
userScope = strings.TrimSpace(userScope)
|
2022-06-03 21:59:36 +08:00
|
|
|
if userScope == "" && s.CreateUserDir {
|
|
|
|
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")
|
2019-02-15 23:12:02 +08:00
|
|
|
}
|
2022-06-03 21:59:36 +08:00
|
|
|
userScope = path.Join(s.UserHomeBasePath, username)
|
2019-02-15 23:12:02 +08:00
|
|
|
}
|
|
|
|
|
2022-06-03 21:59:36 +08:00
|
|
|
userScope = path.Join("/", userScope)
|
2019-02-15 23:12:02 +08:00
|
|
|
|
2022-06-03 21:59:36 +08:00
|
|
|
fs := afero.NewBasePathFs(afero.NewOsFs(), serverRoot)
|
|
|
|
if err := fs.MkdirAll(userScope, os.ModePerm); err != nil {
|
|
|
|
return "", fmt.Errorf("failed to create user home dir: [%s]: %w", userScope, err)
|
2019-02-15 23:12:02 +08:00
|
|
|
}
|
2022-06-03 21:59:36 +08:00
|
|
|
return userScope, nil
|
2019-02-15 23:12:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
2019-04-20 21:15:28 +08:00
|
|
|
}
|