users.go 7.4 KB

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