yosai-server.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package main
  2. import (
  3. "database/sql"
  4. "flag"
  5. "fmt"
  6. "log"
  7. "os"
  8. "strconv"
  9. "git.aetherial.dev/aeth/yosai/pkg/config"
  10. configserver "git.aetherial.dev/aeth/yosai/pkg/config-server"
  11. "github.com/joho/godotenv"
  12. _ "github.com/lib/pq"
  13. )
  14. func main() {
  15. envFile := flag.String("env", "", "pass this to read an env file")
  16. username := flag.String("username", "", "The username to seed the db with, only has affect when calling with the --seed flag")
  17. dbSeed := flag.String("seed", "", "Pass this to seed the database with a configuration file")
  18. flag.Parse()
  19. if *envFile == "" {
  20. fmt.Println("No env file passed, attempting to run with raw environment")
  21. } else {
  22. err := godotenv.Load(*envFile)
  23. if err != nil {
  24. log.Fatal("Couldnt load the env file: ", err.Error())
  25. }
  26. }
  27. dbhost := os.Getenv("DB_HOST")
  28. dbport := os.Getenv("DB_PORT")
  29. dbuser := os.Getenv("DB_USER")
  30. dbpassword := os.Getenv("DB_PASS")
  31. dbname := "postgres"
  32. var portInt int
  33. portInt, err := strconv.Atoi(dbport)
  34. if err != nil {
  35. fmt.Println("An unuseable port was passed: '", dbport, "', defaulting to postgres default of 5432")
  36. portInt = 5432
  37. }
  38. if portInt < 0 || portInt > 65535 {
  39. fmt.Println("An unuseable port was passed: '", dbport, "', defaulting to postgres default of 5432")
  40. portInt = 5432
  41. }
  42. connectionString := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=disable", dbuser, dbpassword, dbhost, portInt, dbname)
  43. fmt.Print(connectionString)
  44. db, err := sql.Open("postgres", connectionString)
  45. if err != nil {
  46. log.Fatal(err)
  47. }
  48. defer db.Close()
  49. err = db.Ping()
  50. if err != nil {
  51. panic(err)
  52. }
  53. fmt.Println("Successfully connected!")
  54. configServerDb := configserver.NewSQLiteRepo(db, os.Stdout)
  55. configServerDb.Migrate()
  56. if *dbSeed != "" {
  57. if *username == "" {
  58. log.Fatal("Blank username not accepted. Use the --username flag to pass in a username to seed the database with")
  59. }
  60. conf := config.NewConfiguration(os.Stdout, config.ValidateUsername(*username))
  61. config.NewConfigHostImpl("./.config.json").Propogate(conf)
  62. user, err := configServerDb.AddUser(config.ValidateUsername(*username))
  63. if err != nil {
  64. log.Fatal(err.Error(), "failed to add user")
  65. }
  66. configServerDb.SeedUser(user, *conf)
  67. fmt.Println("Database created and seeded.")
  68. }
  69. configserver.RunHttpServer(8080, configServerDb, os.Stdout)
  70. }