go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/experiments/huectl/pkg/command/auth.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package command
     9  
    10  import (
    11  	"encoding/json"
    12  	"fmt"
    13  	"os"
    14  	"path/filepath"
    15  
    16  	"github.com/urfave/cli/v2"
    17  
    18  	"go.charczuk.com/experiments/huectl/pkg/hue"
    19  )
    20  
    21  // Auth returns the auth command.
    22  func Auth() *cli.Command {
    23  	return &cli.Command{
    24  		Name:    "auth",
    25  		Aliases: []string{"login"},
    26  		Usage:   "Authenticate with your local bridge, writing a config to save the credentials.",
    27  		Flags: []cli.Flag{
    28  			&cli.StringFlag{
    29  				Name:  flagAddr,
    30  				Usage: "The local bridge address",
    31  			},
    32  			&cli.StringFlag{
    33  				Name:  flagDeviceType,
    34  				Usage: "The devicetype argument",
    35  				Value: "my_hue_app#huectl",
    36  			},
    37  			&cli.StringFlag{
    38  				Name:    flagOutput,
    39  				Usage:   "The output config json file path",
    40  				Value:   os.ExpandEnv("${HOME}/.config/huectl/config.json"),
    41  				EnvVars: []string{"HUE_CONFIG"},
    42  			},
    43  		},
    44  		Action: func(c *cli.Context) error {
    45  			var b hue.Bridge
    46  			hueAddr := c.String(flagAddr)
    47  			if hueAddr == "" {
    48  				found, ok, err := hue.DiscoverFirst(c.Context)
    49  				if err != nil {
    50  					return err
    51  				}
    52  				if !ok {
    53  					return fmt.Errorf("no bridges discovered")
    54  				}
    55  				b.Addr = found.Addr
    56  			} else {
    57  				b.Addr = hueAddr
    58  			}
    59  
    60  			fmt.Println("Please make sure to go press the 'link' button on your bridge")
    61  			fmt.Println("Press the <Enter> key when ready")
    62  			fmt.Scanln()
    63  
    64  			username, err := b.CreateUser(c.Context, c.String(flagDeviceType))
    65  			if err != nil {
    66  				return err
    67  			}
    68  
    69  			configData, err := json.Marshal(config{
    70  				Addr:     b.Addr,
    71  				Username: username,
    72  			})
    73  			if err != nil {
    74  				return err
    75  			}
    76  
    77  			configPath := c.String("output")
    78  			if err = os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
    79  				return err
    80  			}
    81  			return os.WriteFile(c.String("config"), configData, 0644)
    82  		},
    83  	}
    84  }