show.go
1 package users 2 3 import ( 4 "context" 5 6 "github.com/google/uuid" 7 8 "github.com/gofiber/fiber/v2" 9 "github.com/mrusme/journalist/ent/user" 10 // "github.com/mrusme/journalist/ent" 11 ) 12 13 type UserShowResponse struct { 14 Success bool `json:"success"` 15 User *UserShowModel `json:"user"` 16 Message string `json:"message"` 17 } 18 19 // Show godoc 20 // @Summary Show a user 21 // @Description Get user by ID 22 // @Tags users 23 // @Accept json 24 // @Produce json 25 // @Param id path string true "User ID" 26 // @Success 200 {object} UserShowResponse 27 // @Failure 400 {object} UserShowResponse 28 // @Failure 404 {object} UserShowResponse 29 // @Failure 500 {object} UserShowResponse 30 // @Router /users/{id} [get] 31 // @security BasicAuth 32 func (h *handler) Show(ctx *fiber.Ctx) error { 33 var err error 34 35 param_id := ctx.Params("id") 36 id, err := uuid.Parse(param_id) 37 if err != nil { 38 return ctx. 39 Status(fiber.StatusBadRequest). 40 JSON(UserShowResponse{ 41 Success: false, 42 User: nil, 43 Message: err.Error(), 44 }) 45 } 46 47 user_id := ctx.Locals("user_id").(string) 48 role := ctx.Locals("role").(string) 49 50 if param_id != user_id && role != "admin" { 51 return ctx. 52 Status(fiber.StatusForbidden). 53 JSON(UserShowResponse{ 54 Success: false, 55 User: nil, 56 Message: "Only admins are allowed to see other users", 57 }) 58 } 59 60 dbUser, err := h.entClient.User. 61 Query(). 62 Where( 63 user.ID(id), 64 ). 65 Only(context.Background()) 66 if err != nil { 67 return ctx. 68 Status(fiber.StatusInternalServerError). 69 JSON(UserShowResponse{ 70 Success: false, 71 User: nil, 72 Message: err.Error(), 73 }) 74 } 75 76 showUser := UserShowModel{ 77 ID: dbUser.ID.String(), 78 Username: dbUser.Username, 79 Role: dbUser.Role, 80 } 81 82 return ctx. 83 Status(fiber.StatusOK). 84 JSON(UserShowResponse{ 85 Success: true, 86 User: &showUser, 87 Message: "", 88 }) 89 }