users.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. package handlers
  2. import (
  3. "fmt"
  4. "net/http"
  5. "git.linuxforward.com/byop/byop-engine/dbstore"
  6. "git.linuxforward.com/byop/byop-engine/models"
  7. "github.com/gin-gonic/gin"
  8. "github.com/go-playground/validator/v10"
  9. "golang.org/x/crypto/bcrypt"
  10. )
  11. // UserHandler handles user-related operations
  12. type UserHandler struct {
  13. Store *dbstore.SQLiteStore
  14. Validate *validator.Validate
  15. }
  16. // NewUserHandler creates a new UserHandler
  17. func NewUserHandler(store *dbstore.SQLiteStore) *UserHandler {
  18. return &UserHandler{
  19. Store: store,
  20. Validate: validator.New(),
  21. }
  22. }
  23. // RegisterUserRoutes registers routes for user operations
  24. func (h *UserHandler) RegisterUserRoutes(rg *gin.RouterGroup) {
  25. rg.POST("/", h.CreateUser)
  26. rg.GET("/:id", h.GetUser)
  27. rg.PUT("/:id", h.UpdateUser)
  28. rg.DELETE("/:id", h.DeleteUser)
  29. rg.GET("/", h.ListUsers)
  30. rg.GET("/:id/deployments", h.GetUserDeployments)
  31. }
  32. // CreateUserInput defines the input for creating a user
  33. type CreateUserInput struct {
  34. Email string `json:"email" validate:"required,email"`
  35. Password string `json:"password" validate:"required,min=8"`
  36. Name string `json:"name" validate:"required,min=2"`
  37. Role string `json:"role" validate:"omitempty,oneof=user admin editor"`
  38. Active *bool `json:"active"`
  39. }
  40. // CreateUser creates a new user
  41. func (h *UserHandler) CreateUser(c *gin.Context) {
  42. ctx := c.Request.Context()
  43. var input CreateUserInput
  44. if err := c.ShouldBindJSON(&input); err != nil {
  45. appErr := models.NewErrValidation("invalid_user_input_format", map[string]string{"body": "Invalid request body"}, err)
  46. models.RespondWithError(c, appErr)
  47. return
  48. }
  49. if err := h.Validate.StructCtx(ctx, input); err != nil {
  50. errors := models.ExtractValidationErrors(err)
  51. appErr := models.NewErrValidation("user_validation_failed", errors, err)
  52. models.RespondWithError(c, appErr)
  53. return
  54. }
  55. hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
  56. if err != nil {
  57. appErr := models.NewErrInternalServer("password_hash_failed", fmt.Errorf("Failed to hash password: %w", err))
  58. models.RespondWithError(c, appErr)
  59. return
  60. }
  61. userRole := models.RoleUser
  62. if input.Role != "" {
  63. userRole = input.Role
  64. }
  65. userActive := true
  66. if input.Active != nil {
  67. userActive = *input.Active
  68. }
  69. user := models.User{
  70. Email: input.Email,
  71. Password: string(hashedPassword),
  72. Name: input.Name,
  73. Role: userRole,
  74. Active: userActive,
  75. }
  76. err = h.Store.CreateUser(ctx, &user)
  77. if err != nil {
  78. if models.IsErrConflict(err) {
  79. models.RespondWithError(c, err)
  80. return
  81. }
  82. appErr := models.NewErrInternalServer("failed_to_create_user", fmt.Errorf("Failed to create user: %w", err))
  83. models.RespondWithError(c, appErr)
  84. return
  85. }
  86. // GORM automatically sets the ID after creation
  87. // Clear the password before sending the response
  88. createdUser := user
  89. createdUser.Password = ""
  90. c.JSON(http.StatusCreated, createdUser)
  91. }
  92. // GetUser retrieves a user by ID
  93. func (h *UserHandler) GetUser(c *gin.Context) {
  94. ctx := c.Request.Context()
  95. id, err := parseUintID(c, "id")
  96. if err != nil {
  97. models.RespondWithError(c, err)
  98. return
  99. }
  100. user, err := h.Store.GetUserByID(ctx, id)
  101. if err != nil {
  102. models.RespondWithError(c, err)
  103. return
  104. }
  105. user.Password = ""
  106. c.JSON(http.StatusOK, user)
  107. }
  108. // UpdateUserInput defines the input for updating a user
  109. type UpdateUserInput struct {
  110. Email *string `json:"email,omitempty" validate:"omitempty,email"`
  111. Password *string `json:"password,omitempty" validate:"omitempty,min=8"`
  112. Name *string `json:"name,omitempty" validate:"omitempty,min=2"`
  113. Role *string `json:"role,omitempty" validate:"omitempty,oneof=user admin editor"`
  114. Active *bool `json:"active,omitempty"`
  115. }
  116. // UpdateUser updates an existing user
  117. func (h *UserHandler) UpdateUser(c *gin.Context) {
  118. ctx := c.Request.Context()
  119. id, err := parseUintID(c, "id")
  120. if err != nil {
  121. models.RespondWithError(c, err)
  122. return
  123. }
  124. var input UpdateUserInput
  125. if err := c.ShouldBindJSON(&input); err != nil {
  126. appErr := models.NewErrValidation("invalid_update_user_input_format", map[string]string{"body": "Invalid request body"}, err)
  127. models.RespondWithError(c, appErr)
  128. return
  129. }
  130. if err := h.Validate.StructCtx(ctx, input); err != nil {
  131. errors := models.ExtractValidationErrors(err)
  132. appErr := models.NewErrValidation("update_user_validation_failed", errors, err)
  133. models.RespondWithError(c, appErr)
  134. return
  135. }
  136. user, err := h.Store.GetUserByID(ctx, id)
  137. if err != nil {
  138. models.RespondWithError(c, err)
  139. return
  140. }
  141. updated := false
  142. if input.Email != nil {
  143. user.Email = *input.Email
  144. updated = true
  145. }
  146. if input.Password != nil {
  147. hashedPassword, err := bcrypt.GenerateFromPassword([]byte(*input.Password), bcrypt.DefaultCost)
  148. if err != nil {
  149. appErr := models.NewErrInternalServer("update_password_hash_failed", fmt.Errorf("Failed to hash new password: %w", err))
  150. models.RespondWithError(c, appErr)
  151. return
  152. }
  153. user.Password = string(hashedPassword)
  154. updated = true
  155. }
  156. if input.Name != nil {
  157. user.Name = *input.Name
  158. updated = true
  159. }
  160. if input.Role != nil {
  161. user.Role = *input.Role
  162. updated = true
  163. }
  164. if input.Active != nil {
  165. user.Active = *input.Active
  166. updated = true
  167. }
  168. if !updated {
  169. user.Password = ""
  170. c.JSON(http.StatusOK, user)
  171. return
  172. }
  173. if err := h.Store.UpdateUser(ctx, user); err != nil {
  174. models.RespondWithError(c, err)
  175. return
  176. }
  177. user.Password = ""
  178. c.JSON(http.StatusOK, user)
  179. }
  180. // DeleteUser deletes a user by ID
  181. func (h *UserHandler) DeleteUser(c *gin.Context) {
  182. ctx := c.Request.Context()
  183. id, err := parseUintID(c, "id")
  184. if err != nil {
  185. models.RespondWithError(c, err)
  186. return
  187. }
  188. if err := h.Store.DeleteUser(ctx, id); err != nil {
  189. models.RespondWithError(c, err)
  190. return
  191. }
  192. c.Status(http.StatusNoContent)
  193. }
  194. // ListUsers retrieves all users
  195. func (h *UserHandler) ListUsers(c *gin.Context) {
  196. ctx := c.Request.Context()
  197. users, err := h.Store.GetUsers(ctx)
  198. if err != nil {
  199. appErr := models.NewErrInternalServer("failed_to_list_users", fmt.Errorf("Failed to list users: %w", err))
  200. models.RespondWithError(c, appErr)
  201. return
  202. }
  203. for i := range users {
  204. users[i].Password = ""
  205. }
  206. c.JSON(http.StatusOK, users)
  207. }
  208. // GetUserDeployments returns all deployments for a specific user
  209. func (h *UserHandler) GetUserDeployments(c *gin.Context) {
  210. ctx := c.Request.Context()
  211. userID, err := parseUintID(c, "id")
  212. if err != nil {
  213. models.RespondWithError(c, err)
  214. return
  215. }
  216. _, err = h.Store.GetUserByID(ctx, userID)
  217. if err != nil {
  218. models.RespondWithError(c, err)
  219. return
  220. }
  221. deployments, err := h.Store.GetDeploymentsByUserID(ctx, userID)
  222. if err != nil {
  223. appErr := models.NewErrInternalServer("failed_to_get_user_deployments", fmt.Errorf("Failed to get deployments for user %d: %w", userID, err))
  224. models.RespondWithError(c, appErr)
  225. return
  226. }
  227. if deployments == nil {
  228. deployments = []*models.Deployment{}
  229. }
  230. c.JSON(http.StatusOK, deployments)
  231. }