|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "database/sql" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + "github.com/coder/coder/cli/clibase" |
| 8 | + "github.com/coder/coder/coderd/database" |
| 9 | + "github.com/coder/coder/coderd/database/migrations" |
| 10 | + "golang.org/x/xerrors" |
| 11 | +) |
| 12 | + |
| 13 | +func (*RootCmd) appSecurityKey() *clibase.Cmd { |
| 14 | + var postgresURL string |
| 15 | + |
| 16 | + root := &clibase.Cmd{ |
| 17 | + Use: "app-security-key", |
| 18 | + Short: "Directly connect to the database to print the app security key", |
| 19 | + // We can unhide this if we decide to keep it this way. |
| 20 | + Hidden: true, |
| 21 | + Middleware: clibase.RequireNArgs(0), |
| 22 | + Handler: func(inv *clibase.Invocation) error { |
| 23 | + sqlDB, err := sql.Open("postgres", postgresURL) |
| 24 | + if err != nil { |
| 25 | + return xerrors.Errorf("dial postgres: %w", err) |
| 26 | + } |
| 27 | + defer sqlDB.Close() |
| 28 | + err = sqlDB.Ping() |
| 29 | + if err != nil { |
| 30 | + return xerrors.Errorf("ping postgres: %w", err) |
| 31 | + } |
| 32 | + |
| 33 | + err = migrations.EnsureClean(sqlDB) |
| 34 | + if err != nil { |
| 35 | + return xerrors.Errorf("database needs migration: %w", err) |
| 36 | + } |
| 37 | + db := database.New(sqlDB) |
| 38 | + |
| 39 | + key, err := db.GetAppSecurityKey(inv.Context()) |
| 40 | + if err != nil { |
| 41 | + return xerrors.Errorf("retrieving key: %w", err) |
| 42 | + } |
| 43 | + |
| 44 | + _, _ = fmt.Fprintln(inv.Stdout, key) |
| 45 | + return nil |
| 46 | + }, |
| 47 | + } |
| 48 | + |
| 49 | + root.Options = clibase.OptionSet{ |
| 50 | + { |
| 51 | + Flag: "postgres-url", |
| 52 | + Description: "URL of a PostgreSQL database to connect to.", |
| 53 | + Env: "CODER_PG_CONNECTION_URL", |
| 54 | + Value: clibase.StringOf(&postgresURL), |
| 55 | + }, |
| 56 | + } |
| 57 | + |
| 58 | + return root |
| 59 | +} |
0 commit comments