From 489bcb571f21b7f158bb7c8a393ff6768e243858 Mon Sep 17 00:00:00 2001 From: Maina Wycliffe Date: Fri, 13 Dec 2019 05:20:39 +0300 Subject: [PATCH] feat: add command to add multiple users from file --- cmd/addUsers.go | 60 +++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 48 insertions(+), 12 deletions(-) diff --git a/cmd/addUsers.go b/cmd/addUsers.go index 3d489d9..9168bc2 100644 --- a/cmd/addUsers.go +++ b/cmd/addUsers.go @@ -1,8 +1,13 @@ package cmd import ( + "context" "fmt" + "os" + "github.com/logrusorgru/aurora" + "github.com/mainawycliffe/kamanda/firebase/auth" + "github.com/mainawycliffe/kamanda/utils" "github.com/spf13/cobra" ) @@ -10,22 +15,53 @@ import ( var addUsersCmd = &cobra.Command{ Use: "addUsers", Aliases: []string{"add-users"}, - Short: "Add multiple Firebase Auth Users from file - JSON or YAML Supported!", + Short: "Add multiple users from file (JSON/YAML)", Run: func(cmd *cobra.Command, args []string) { - fmt.Println("addUsers called") + sourceFile, _ := cmd.Flags().GetString("source") + sourceFileExtension, _ := cmd.Flags().GetString("extension") + file, err := os.Stat(sourceFile) + if err != nil && !os.IsNotExist(err) { + utils.StdOutError("Source file doesn't exist!") + os.Exit(1) + } + if file.IsDir() { + utils.StdOutError("%s Source file is a directory not folder!", sourceFile) + os.Exit(1) + } + usersToCreate := make([]auth.NewUser, 0) + err = utils.UnmashalMarkupFile(sourceFile, sourceFileExtension, usersToCreate) + if err != nil { + utils.StdOutError("Error decoding your config file: %s", err.Error()) + os.Exit(1) + } + failedAccountCreation := 0 + for _, v := range usersToCreate { + userRecord, err := auth.NewFirebaseUser(context.Background(), &v) + if err != nil { + utils.StdOutError("%s Failed!", v.Email) + failedAccountCreation++ + continue + } + utils.StdOutSuccess("✔✔ email: %s SUCCESS \t uid: %s \n", userRecord.Email, userRecord.UID) + // @todo probably also add custom claims + } + if failedAccountCreation > 0 { + os.Exit(1) + } + os.Exit(0) }, } func init() { authCmd.AddCommand(addUsersCmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // addUsersCmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // addUsersCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") + addUsersCmd.Flags().StringP("source", "s", "", "file with list of users to create") + if err := addUsersCmd.MarkFlagRequired("source"); err != nil { + fmt.Print(aurora.Sprintf(aurora.Red("%s\n"), err.Error())) + os.Exit(1) + } + addUsersCmd.Flags().StringP("extension", "e", "yaml", "Source file type - json or yaml") + if err := addUsersCmd.MarkFlagRequired("extension"); err != nil { + fmt.Print(aurora.Sprintf(aurora.Red("%s\n"), err.Error())) + os.Exit(1) + } }