PageRenderTime 1381ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/commands/mauth.go

https://gitlab.com/mikattack/mauth
Go | 96 lines | 61 code | 23 blank | 12 comment | 11 complexity | 7098d0081459191705a07ea89f9a95c1 MD5 | raw file
  1. package commands
  2. import (
  3. "os"
  4. "strings"
  5. "github.com/spf13/cobra"
  6. _ "github.com/mattn/go-sqlite3"
  7. "github.com/jmoiron/sqlx"
  8. "gitlab.com/mikattack/mauth/datasource"
  9. )
  10. const (
  11. sqlite_default_file string = "./mauth.db"
  12. sqlite_default_idle_connections int = 10
  13. sqlite_default_open_connections int = 10
  14. )
  15. var dbpath string
  16. /*
  17. * Root command. Every other command is attached as a child to it.
  18. */
  19. var MauthCmd = &cobra.Command {
  20. Use: "mauth",
  21. Short: "Simplistic authentication management",
  22. Long: `mauth (v1.0.0)
  23. Simplitic management tool for single-node authentication data.`,
  24. }
  25. // Executes selected subcommand, with common error handling
  26. func Execute() {
  27. MauthCmd.SilenceUsage = true
  28. addCommands(MauthCmd)
  29. // Execute given command or print useage upon error
  30. if c, err := MauthCmd.ExecuteC(); err != nil {
  31. if ue, ok := err.(CommandlineError); ok && ue.UserError() == true {
  32. c.Println("")
  33. c.Println(c.UsageString())
  34. }
  35. os.Exit(1)
  36. }
  37. }
  38. func init() {
  39. // NOTE: Persistent flags are not evaluated until the eventual command is
  40. // actually run. Until then, the value is the default.
  41. MauthCmd.PersistentFlags().StringVar(&dbpath, "db", sqlite_default_file, "Path to SQLite database file")
  42. }
  43. func addCommands(cmd *cobra.Command) {
  44. cmd.AddCommand(addCmd)
  45. cmd.AddCommand(delCmd)
  46. cmd.AddCommand(passwdCmd)
  47. cmd.AddCommand(serverCmd)
  48. cmd.AddCommand(showCmd)
  49. cmd.AddCommand(keyCmd)
  50. cmd.AddCommand(revokeKeyCmd)
  51. }
  52. // Convenience for establishing a SQLite database connection pool. Will open
  53. // a connection, load the default schema, and set some connection limits.
  54. func connectToDatabase(path string) (*sqlx.DB, error) {
  55. // Clean path
  56. path = strings.TrimSpace(path)
  57. if len(path) == 0 {
  58. path = sqlite_default_file
  59. }
  60. // Open database file
  61. pool, err := sqlx.Open("sqlite3", path)
  62. if err != nil {
  63. return nil, err
  64. }
  65. // Initialize schema
  66. if _, err := pool.Exec(datasource.DEFAULT_SCHEMA); err != nil {
  67. return nil, err
  68. }
  69. pool.SetMaxIdleConns(sqlite_default_idle_connections)
  70. pool.SetMaxOpenConns(sqlite_default_open_connections)
  71. return pool, nil
  72. }