Skip to content
This repository has been archived by the owner on Mar 12, 2021. It is now read-only.

Commit

Permalink
Merge pull request #4 from magneticio/addnewuser
Browse files Browse the repository at this point in the history
Add new user
  • Loading branch information
bgokden authored Feb 11, 2019
2 parents 748bfe3 + 2021568 commit a076fa3
Show file tree
Hide file tree
Showing 5 changed files with 214 additions and 6 deletions.
84 changes: 84 additions & 0 deletions cmd/add.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Copyright © 2018 Developer [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
"errors"
"fmt"
"strings"

"github.com/magneticio/vampkubistcli/client"
"github.com/magneticio/vampkubistcli/util"
"github.com/spf13/cobra"
)

// addCmd represents the add command
var addCmd = &cobra.Command{
Use: "add",
Short: "Add a new user",
Long: AddAppName(`Add a new user:
$AppName add username
This will print command to login for a new user.
`),
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 2 {
return errors.New("Not Enough Arguments")
}
Type = args[0]
Name = args[1]

if Type == "user" {
Username := strings.ToLower(Name)
// TODO: this is a temporary workaround it will be handled in the backend
temporarayPassword := util.RandomString(50)
SourceFileType := "json"
Source := "{\"userName\":\"" + Username + "\",\"password\":\"" + temporarayPassword + "\"}"
restClient := client.NewRestClient(Config.Url, Config.Token, Debug, Config.Cert)
values := make(map[string]string)
values["project"] = Config.Project
values["cluster"] = Config.Cluster
values["virtual_cluster"] = Config.VirtualCluster
values["application"] = Application
isCreated, createError := restClient.Create(Type, Name, Source, SourceFileType, values)
if !isCreated {
return createError
}
fmt.Printf("User created.\n")
token, loginError := restClient.Login(Username, temporarayPassword)
if loginError != nil {
return loginError
}
fmt.Printf("User can login with:\n")
fmt.Printf("vamp login --url %v --user %v --initial --token %v --cert <<EOF \"%v\"\nEOF\n", Config.Url, Username, token, Config.Cert)
}
return nil
},
}

func init() {
rootCmd.AddCommand(addCmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// addCmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// addCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
26 changes: 20 additions & 6 deletions cmd/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ var Username string
var Password string
var Cert string

var initial bool

var WelcomeText = AddAppName(`
Welcome to $AppName
It is recommeded to update your password with
$AppName passwd
and re-login with your username and new password.
`)

// loginCmd represents the login command
var loginCmd = &cobra.Command{
Use: "login",
Expand Down Expand Up @@ -75,12 +84,12 @@ Example:
if err_cert != nil {
b, err := util.UseSourceUrl(Cert)
if err != nil {
// fmt.Print(err)
return err
fmt.Printf("Warning: %v\n", err)
b = Cert
}
err_cert_from_path := util.VerifyCertForHost(Config.Url, b)
if err_cert_from_path != nil {
return err_cert_from_path
certVerifyError := util.VerifyCertForHost(Config.Url, b)
if certVerifyError != nil {
return certVerifyError
}
CertString = string(b)
}
Expand Down Expand Up @@ -116,8 +125,12 @@ Example:
}
Config.Token = token
}
fmt.Println("Token will be written to config: " + Config.Token)
Config.Username = Username
fmt.Println("Login Successful.")
WriteConfigFile()
if initial {
fmt.Println(WelcomeText)
}
return nil
},
}
Expand All @@ -140,6 +153,7 @@ func init() {
loginCmd.Flags().StringVarP(&Password, "password", "", "", "Password required")
// loginCmd.MarkFlagRequired("password")
loginCmd.Flags().StringVarP(&Cert, "cert", "", "", "Cert from file, url or string")
loginCmd.Flags().BoolVarP(&initial, "initial", "", false, "Prints welcome string for new users.")

// loginCmd.PersistentFlags().StringVar(&Server, "server", "default", "server to connect")
// viper.BindPFlag("server", loginCmd.PersistentFlags().Lookup("server"))
Expand Down
78 changes: 78 additions & 0 deletions cmd/passwd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright © 2018 Developer [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
"fmt"

"github.com/magneticio/vampkubistcli/client"
"github.com/magneticio/vampkubistcli/util"
"github.com/spf13/cobra"
)

// passwdCmd represents the passwd command
var passwdCmd = &cobra.Command{
Use: "passwd",
Short: "Update password",
Long: AddAppName(`Update password
For the current user:
$AppName
For a different user
$AppName --user username`),
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
Type := "user"
passwd, passwdError := util.GetParameterFromTerminalAsSecret(
"Enter your password (password will not be visible):",
"Enter your password again (password will not be visible):",
"Passwords do not match.")
if passwdError != nil {
return passwdError
}
SourceFileType := "json"
if Username == "" {
Username = Config.Username
}
Source := "{\"userName\":\"" + Username + "\",\"password\":\"" + passwd + "\"}"
restClient := client.NewRestClient(Config.Url, Config.Token, Debug, Config.Cert)
values := make(map[string]string)
values["project"] = Config.Project
values["cluster"] = Config.Cluster
values["virtual_cluster"] = Config.VirtualCluster
values["application"] = Application
_, updateError := restClient.Update(Type, Username, Source, SourceFileType, values)
if updateError != nil {
return updateError
}
fmt.Printf("User password updated.\nLogin with the new password.\n")
return nil
},
}

func init() {
rootCmd.AddCommand(passwdCmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// passwdCmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// passwdCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
passwdCmd.Flags().StringVarP(&Username, "user", "", "", "Username of the user to change password")
}
1 change: 1 addition & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
type config struct {
Url string `yaml:"url,omitempty" json:"url,omitempty"`
Cert string `yaml:"cert,omitempty" json:"cert,omitempty"`
Username string `yaml:"username,omitempty" json:"username,omitempty"`
Token string `yaml:"token,omitempty" json:"token,omitempty"`
Project string `yaml:"project,omitempty" json:"project,omitempty"`
Cluster string `yaml:"cluster,omitempty" json:"cluster,omitempty"`
Expand Down
31 changes: 31 additions & 0 deletions util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ import (
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"strings"
"syscall"
"time"

"github.com/ghodss/yaml"
"github.com/yalp/jsonpath"
Expand Down Expand Up @@ -157,15 +159,44 @@ func GetParameterFromTerminalAsSecret(text1 string, text2 string, errorText stri
if errInput1 != nil {
return "", errInput1
}
fmt.Println()
input1 := string(byteInput1)
fmt.Println(text2)
byteInput2, errInput2 := terminal.ReadPassword(int(syscall.Stdin))
if errInput2 != nil {
return "", errInput2
}
fmt.Println()
input2 := string(byteInput2)
if input1 != input2 {
return "", errors.New(errorText)
}
return input1, nil
}

var src = rand.NewSource(time.Now().UnixNano())

const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)

func RandomString(n int) string {
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}

return string(b)
}

0 comments on commit a076fa3

Please sign in to comment.