users.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package handlers
  2. import (
  3. "fmt"
  4. "git.linuxforward.com/byom/byom-gateway/store"
  5. "github.com/gin-gonic/gin"
  6. "github.com/sirupsen/logrus"
  7. )
  8. type UserHandler struct {
  9. entry *logrus.Entry
  10. db *store.DataStore
  11. pricingPage string
  12. }
  13. // this handlers is gonna be used in order to check
  14. // if a specified user using its email has an hostname associated
  15. func NewUserHandler(db *store.DataStore, pricingPage string) *UserHandler {
  16. return &UserHandler{
  17. entry: logrus.WithField("handler", "user-host"),
  18. db: db,
  19. pricingPage: pricingPage,
  20. }
  21. }
  22. func (u *UserHandler) GetUserHost(c *gin.Context) {
  23. email := c.Query("email")
  24. if email == "" {
  25. c.JSON(400, gin.H{"error": "email is required"})
  26. return
  27. }
  28. host, err := u.db.GetUserHost(email)
  29. fmt.Printf("Host from DB: %v, err: %v\n", host, err) // Add this log
  30. if err != nil || host == "" {
  31. c.JSON(200, gin.H{"redirect": u.pricingPage})
  32. return
  33. }
  34. c.JSON(200, gin.H{"redirect": "https://" + host + "/login"})
  35. }
  36. func (u *UserHandler) AddUserHost(c *gin.Context) {
  37. var req struct {
  38. Email string `json:"email"`
  39. Host string `json:"host"`
  40. }
  41. if err := c.BindJSON(&req); err != nil {
  42. c.JSON(400, gin.H{"error": err.Error()})
  43. return
  44. }
  45. if req.Email == "" || req.Host == "" {
  46. c.JSON(400, gin.H{"error": "email is required"})
  47. return
  48. }
  49. if err := u.db.AddUserHost(req.Email, req.Host); err != nil {
  50. c.JSON(500, gin.H{"error": err.Error()})
  51. return
  52. }
  53. c.JSON(200, gin.H{"status": "ok"})
  54. }
  55. func (u *UserHandler) DeleteUserHost(c *gin.Context) {
  56. email := c.Query("email")
  57. if email == "" {
  58. c.JSON(400, gin.H{"error": "email is required"})
  59. return
  60. }
  61. if err := u.db.DeleteUserHost(email); err != nil {
  62. c.JSON(500, gin.H{"error": err.Error()})
  63. return
  64. }
  65. c.JSON(200, gin.H{"status": "ok"})
  66. }
  67. func (u *UserHandler) UpdateUserHost(c *gin.Context) {
  68. var req struct {
  69. Email string `json:"email"`
  70. Host string `json:"host"`
  71. }
  72. if err := c.BindJSON(&req); err != nil {
  73. c.JSON(400, gin.H{"error": err.Error()})
  74. return
  75. }
  76. if req.Email == "" || req.Host == "" {
  77. c.JSON(400, gin.H{"error": "email is required"})
  78. return
  79. }
  80. if err := u.db.UpdateUserHost(req.Email, req.Host); err != nil {
  81. c.JSON(500, gin.H{"error": err.Error()})
  82. return
  83. }
  84. c.JSON(200, gin.H{"status": "ok"})
  85. }