/commands/mauth.go
Go | 96 lines | 61 code | 23 blank | 12 comment | 11 complexity | 7098d0081459191705a07ea89f9a95c1 MD5 | raw file
- package commands
- import (
- "os"
- "strings"
- "github.com/spf13/cobra"
- _ "github.com/mattn/go-sqlite3"
- "github.com/jmoiron/sqlx"
- "gitlab.com/mikattack/mauth/datasource"
- )
- const (
- sqlite_default_file string = "./mauth.db"
- sqlite_default_idle_connections int = 10
- sqlite_default_open_connections int = 10
- )
- var dbpath string
- /*
- * Root command. Every other command is attached as a child to it.
- */
- var MauthCmd = &cobra.Command {
- Use: "mauth",
- Short: "Simplistic authentication management",
- Long: `mauth (v1.0.0)
- Simplitic management tool for single-node authentication data.`,
- }
- // Executes selected subcommand, with common error handling
- func Execute() {
- MauthCmd.SilenceUsage = true
- addCommands(MauthCmd)
- // Execute given command or print useage upon error
- if c, err := MauthCmd.ExecuteC(); err != nil {
- if ue, ok := err.(CommandlineError); ok && ue.UserError() == true {
- c.Println("")
- c.Println(c.UsageString())
- }
- os.Exit(1)
- }
- }
- func init() {
- // NOTE: Persistent flags are not evaluated until the eventual command is
- // actually run. Until then, the value is the default.
- MauthCmd.PersistentFlags().StringVar(&dbpath, "db", sqlite_default_file, "Path to SQLite database file")
- }
- func addCommands(cmd *cobra.Command) {
- cmd.AddCommand(addCmd)
- cmd.AddCommand(delCmd)
- cmd.AddCommand(passwdCmd)
- cmd.AddCommand(serverCmd)
- cmd.AddCommand(showCmd)
- cmd.AddCommand(keyCmd)
- cmd.AddCommand(revokeKeyCmd)
- }
- // Convenience for establishing a SQLite database connection pool. Will open
- // a connection, load the default schema, and set some connection limits.
- func connectToDatabase(path string) (*sqlx.DB, error) {
- // Clean path
- path = strings.TrimSpace(path)
- if len(path) == 0 {
- path = sqlite_default_file
- }
- // Open database file
- pool, err := sqlx.Open("sqlite3", path)
- if err != nil {
- return nil, err
- }
- // Initialize schema
- if _, err := pool.Exec(datasource.DEFAULT_SCHEMA); err != nil {
- return nil, err
- }
- pool.SetMaxIdleConns(sqlite_default_idle_connections)
- pool.SetMaxOpenConns(sqlite_default_open_connections)
- return pool, nil
- }