aboutsummaryrefslogtreecommitdiff
path: root/cmd/tokentool/main.go
blob: f137fb48a0fd30f58c35950ac7c7c5f62710982a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main

import (
	"encoding/csv"
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"git.ofmax.li/go-git-server/internal/authz"
)

func main() {
	var (
		tokenFile string
		generate  bool
		list      bool
		name      string
	)

	flag.StringVar(&tokenFile, "tokens", "tokens.csv", "Path to tokens CSV file")
	flag.BoolVar(&generate, "generate", false, "Generate a new token")
	flag.BoolVar(&list, "list", false, "List existing tokens")
	flag.StringVar(&name, "name", "", "Friendly name for new token")
	flag.Parse()

	if generate {
		if name == "" {
			fmt.Fprintln(os.Stderr, "Error: -name required when generating token")
			os.Exit(1)
		}

		// Generate new access ID and token
		accessID, err := authz.GenerateAccessID()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error generating access ID: %v\n", err)
			os.Exit(1)
		}

		token, hash, err := authz.GenerateNewToken()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error generating token: %v\n", err)
			os.Exit(1)
		}

		// Ensure directory exists
		if err := os.MkdirAll(filepath.Dir(tokenFile), 0755); err != nil {
			fmt.Fprintf(os.Stderr, "Error creating directory: %v\n", err)
			os.Exit(1)
		}

		// Open file in append mode
		f, err := os.OpenFile(tokenFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error opening token file: %v\n", err)
			os.Exit(1)
		}
		defer f.Close()

		// Write new entry
		w := csv.NewWriter(f)
		if err := w.Write([]string{string(accessID), name, hash}); err != nil {
			fmt.Fprintf(os.Stderr, "Error writing to CSV: %v\n", err)
			os.Exit(1)
		}
		w.Flush()

		fmt.Printf("Generated new token:\n")
		fmt.Printf("Access ID: %s\n", accessID)
		fmt.Printf("Name: %s\n", name)
		fmt.Printf("Token: %s\n", token)
		fmt.Printf("Added to %s\n", tokenFile)
		return
	}

	if list {
		// Load and display existing tokens
		_, identities, err := authz.LoadTokensFromFile(tokenFile)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error reading tokens: %v\n", err)
			os.Exit(1)
		}

		fmt.Printf("Existing tokens in %s:\n", tokenFile)
		fmt.Printf("%-40s %-30s\n", "ACCESS ID", "NAME")
		fmt.Printf("%s %s\n", strings.Repeat("-", 40), strings.Repeat("-", 30))

		for id, name := range identities.IDToName {
			fmt.Printf("%-40s %-30s\n", id, name)
		}
		return
	}

	flag.Usage()
}