1// Copyright 2023 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
3
4package cmd
5
6import (
7 "errors"
8 "fmt"
9 "os"
10 "text/tabwriter"
11
12 auth_model "forgejo.org/models/auth"
13 "forgejo.org/models/db"
14 auth_service "forgejo.org/services/auth"
15
16 "github.com/urfave/cli/v2"
17)
18
19var (
20 microcmdAuthDelete = &cli.Command{
21 Name: "delete",
22 Usage: "Delete specific auth source",
23 Flags: []cli.Flag{idFlag},
24 Action: runDeleteAuth,
25 }
26 microcmdAuthList = &cli.Command{
27 Name: "list",
28 Usage: "List auth sources",
29 Action: runListAuth,
30 Flags: []cli.Flag{
31 &cli.IntFlag{
32 Name: "min-width",
33 Usage: "Minimal cell width including any padding for the formatted table",
34 Value: 0,
35 },
36 &cli.IntFlag{
37 Name: "tab-width",
38 Usage: "width of tab characters in formatted table (equivalent number of spaces)",
39 Value: 8,
40 },
41 &cli.IntFlag{
42 Name: "padding",
43 Usage: "padding added to a cell before computing its width",
44 Value: 1,
45 },
46 &cli.StringFlag{
47 Name: "pad-char",
48 Usage: `ASCII char used for padding if padchar == '\\t', the Writer will assume that the width of a '\\t' in the formatted output is tabwidth, and cells are left-aligned independent of align_left (for correct-looking results, tabwidth must correspond to the tab width in the viewer displaying the result)`,
49 Value: "\t",
50 },
51 &cli.BoolFlag{
52 Name: "vertical-bars",
53 Usage: "Set to true to print vertical bars between columns",
54 },
55 },
56 }
57)
58
59func runListAuth(c *cli.Context) error {
60 ctx, cancel := installSignals()
61 defer cancel()
62
63 if err := initDB(ctx); err != nil {
64 return err
65 }
66
67 authSources, err := db.Find[auth_model.Source](ctx, auth_model.FindSourcesOptions{})
68 if err != nil {
69 return err
70 }
71
72 flags := tabwriter.AlignRight
73 if c.Bool("vertical-bars") {
74 flags |= tabwriter.Debug
75 }
76
77 padChar := byte('\t')
78 if len(c.String("pad-char")) > 0 {
79 padChar = c.String("pad-char")[0]
80 }
81
82 // loop through each source and print
83 w := tabwriter.NewWriter(os.Stdout, c.Int("min-width"), c.Int("tab-width"), c.Int("padding"), padChar, flags)
84 fmt.Fprintf(w, "ID\tName\tType\tEnabled\n")
85 for _, source := range authSources {
86 fmt.Fprintf(w, "%d\t%s\t%s\t%t\n", source.ID, source.Name, source.Type.String(), source.IsActive)
87 }
88 w.Flush()
89
90 return nil
91}
92
93func runDeleteAuth(c *cli.Context) error {
94 if !c.IsSet("id") {
95 return errors.New("--id flag is missing")
96 }
97
98 ctx, cancel := installSignals()
99 defer cancel()
100
101 if err := initDB(ctx); err != nil {
102 return err
103 }
104
105 source, err := auth_model.GetSourceByID(ctx, c.Int64("id"))
106 if err != nil {
107 return err
108 }
109
110 return auth_service.DeleteSource(ctx, source)
111}