filebrowser/cmd/users_import.go
Henrique Dias 802318f903 feat: config/users import/export (#613)
Supports json and yaml.

Former-commit-id: d36b07953ede1842942b7ab477effeb2e5aa7d5b [formerly 51d0d5691d19e0649935816779a34b1b700e088a] [formerly 342f636293be8e38e7907453a67c67e5e9195c78 [formerly 73b8d2ee7e]]
Former-commit-id: 8ef6a1563ebe425a15a8229165d2ddb043cefb21 [formerly 01c4ac1d89e0d5c6ed16bb7f23c2bbe62085d6e5]
Former-commit-id: 6d197ee1931889571c61ad0920e4352d4b02b264
2019-01-08 08:57:24 +00:00

66 lines
1.7 KiB
Go

package cmd
import (
"errors"
"os"
"strconv"
"github.com/filebrowser/filebrowser/v2/users"
"github.com/spf13/cobra"
)
func init() {
usersCmd.AddCommand(usersImportCmd)
usersImportCmd.Flags().Bool("overwrite", false, "overwrite users with the same id/username combo")
}
var usersImportCmd = &cobra.Command{
Use: "import <filename>",
Short: "Import users from a file.",
Args: jsonYamlArg,
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
fd, err := os.Open(args[0])
checkErr(err)
defer fd.Close()
list := []*users.User{}
err = unmarshal(args[0], &list)
checkErr(err)
for _, user := range list {
err = user.Clean("")
checkErr(err)
}
overwrite := mustGetBool(cmd, "overwrite")
for _, user := range list {
old, err := d.store.Users.Get("", user.ID)
// User exists in DB.
if err == nil {
if !overwrite {
checkErr(errors.New("user " + strconv.Itoa(int(user.ID)) + " is already registred"))
}
// If the usernames mismatch, check if there is another one in the DB
// with the new username. If there is, print an error and cancel the
// operation
if user.Username != old.Username {
conflictuous, err := d.store.Users.Get("", user.Username)
if err == nil {
checkErr(usernameConflictError(user.Username, conflictuous.ID, user.ID))
}
}
}
err = d.store.Users.Save(user)
checkErr(err)
}
}, pythonConfig{}),
}
func usernameConflictError(username string, original, new uint) error {
return errors.New("can't import user with ID " + strconv.Itoa(int(new)) + " and username \"" + username + "\" because the username is already registred with the user " + strconv.Itoa(int(original)))
}