code.oscarkilo.com/okg/auth.go

.gitignore
README.md
auth.go
client.go
config.go
go.mod
main.go
okg_test.go
pr.go
repo.go
package main

import "bufio"
import "fmt"
import "os"
import "strings"

func runAuth(args []string) error {
  if len(args) == 0 {
    return fmt.Errorf("usage: okg auth login")
  }
  switch args[0] {
  case "login":
    return runAuthLogin(args[1:])
  default:
    return fmt.Errorf("unknown auth command: %s", args[0])
  }
}

func runAuthLogin(args []string) error {
  host := ""
  user := ""
  for i := 0; i < len(args); i++ {
    switch args[i] {
    case "--host":
      i++
      if i >= len(args) {
        return fmt.Errorf("--host requires a value")
      }
      host = args[i]
    case "--user":
      i++
      if i >= len(args) {
        return fmt.Errorf("--user requires a value")
      }
      user = args[i]
    default:
      return fmt.Errorf("unknown flag: %s", args[i])
    }
  }

  reader := bufio.NewReader(os.Stdin)

  if host == "" {
    fmt.Print("Host (default http://localhost:42069): ")
    line, _ := reader.ReadString('\n')
    host = strings.TrimSpace(line)
    if host == "" {
      host = "http://localhost:42069"
    }
  }

  fmt.Print("API key: ")
  api_key, _ := reader.ReadString('\n')
  api_key = strings.TrimSpace(api_key)
  if api_key == "" {
    return fmt.Errorf("API key is required")
  }

  cfg := &Config{Host: host, ApiKey: api_key}
  if err := saveConfig(cfg); err != nil {
    return fmt.Errorf("saving config: %v", err)
  }
  fmt.Printf("Saved config to %s\n", configPath())

  // If --user given, call profile edit to map the
  // API key to this username in mock who.
  if user != "" {
    cl := newClient(cfg)
    payload := map[string]string{
      "username": user,
      "name":     user,
    }
    var result map[string]string
    err := cl.postJSON(
      "/login/profile/edit", payload, &result)
    if err != nil {
      return fmt.Errorf("setting username: %v", err)
    }
    fmt.Printf("Authenticated as %s\n", user)
  }

  return nil
}