github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/scripts/generate-password/main.go (about)

     1  // Copyright 2018 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package main
     5  
     6  import (
     7  	"fmt"
     8  	"log"
     9  	"os"
    10  	"strings"
    11  
    12  	"github.com/juju/gnuflag"
    13  	"github.com/juju/utils"
    14  )
    15  
    16  func main() {
    17  	gnuflag.Usage = func() {
    18  		fmt.Fprintf(os.Stderr, "Usage: %s [modeluuid agent|--user <username>]\n", os.Args[0])
    19  		gnuflag.PrintDefaults()
    20  	}
    21  	user := gnuflag.String("user", "", "supply a username to generate a password instead of modeluuid and agent")
    22  	gnuflag.Parse(true)
    23  	args := gnuflag.Args()
    24  	var modelUUID string
    25  	var agent string
    26  	if *user == "" {
    27  		if len(args) < 2 {
    28  			gnuflag.Usage()
    29  			os.Exit(1)
    30  		}
    31  		modelUUID = args[0]
    32  		agent = args[1]
    33  	}
    34  	passwd, err := utils.RandomPassword()
    35  	if err != nil {
    36  		log.Fatal(err)
    37  	}
    38  	if *user != "" {
    39  		salt, err := utils.RandomSalt()
    40  		if err != nil {
    41  			log.Fatal(err)
    42  		}
    43  		hash := utils.UserPasswordHash(passwd, salt)
    44  		fmt.Printf("Password line for ~/.local/share/juju/accounts.yaml\n")
    45  		fmt.Printf("  password: %s\n", passwd)
    46  		fmt.Printf(`db.users.update({"_id": "%s"}, {"$set": {"passwordsalt": "%s", "passwordhash": "%s"}})`+"\n",
    47  			*user, salt, hash)
    48  	} else {
    49  		hash := utils.AgentPasswordHash(passwd)
    50  		fmt.Printf("oldpassword: %s\n", passwd)
    51  		collection := "UNKNOWN"
    52  		if strings.Index(agent, "/") < 0 {
    53  			// must be a machine
    54  			collection = "machines"
    55  		} else {
    56  			collection = "units"
    57  		}
    58  		fmt.Printf(`db.%s.update({"_id": "%s:%s"}, {$set: {"passwordhash": "%s"}})`+"\n",
    59  			collection, modelUUID, agent, hash)
    60  	}
    61  }