forked from mtusi2026/mtusi2026lab2
65 lines
1.8 KiB
Go
65 lines
1.8 KiB
Go
package users
|
|
|
|
import (
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/auth"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type Handler struct {
|
|
store *store.Store
|
|
}
|
|
|
|
func NewHandler(st *store.Store) *Handler {
|
|
return &Handler{store: st}
|
|
}
|
|
|
|
type CreateUserRequest struct {
|
|
Username string `json:"username" validate:"required"`
|
|
DisplayName string `json:"display_name" validate:"required"`
|
|
Password string `json:"password" validate:"required"`
|
|
}
|
|
|
|
func (h *Handler) CreateUser(c fiber.Ctx) error {
|
|
var req CreateUserRequest
|
|
if err := common.BindJSON(c, &req); err != nil {
|
|
return common.SendAppError(c, err)
|
|
}
|
|
|
|
if msg := common.ValidateCreateUser(req.Username, req.DisplayName); msg != "" {
|
|
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
|
}
|
|
if msg := common.ValidatePassword(req.Password); msg != "" {
|
|
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
|
|
}
|
|
|
|
hash, err := auth.HashPassword(req.Password)
|
|
if err != nil {
|
|
return common.SendError(c, fiber.StatusInternalServerError,
|
|
common.ErrorCodeInternal, "Internal server error")
|
|
}
|
|
|
|
user, err := h.store.CreateUser(c.Context(), req.Username, req.DisplayName, hash)
|
|
if err != nil {
|
|
return common.SendAppError(c, err)
|
|
}
|
|
|
|
return c.Status(fiber.StatusCreated).JSON(user)
|
|
}
|
|
|
|
func (h *Handler) GetCurrentUser(c fiber.Ctx) error {
|
|
userID, ok := c.Locals("userID").(uuid.UUID)
|
|
if !ok {
|
|
return common.SendChallenge(c, `Bearer realm="messenger"`, "authentication required")
|
|
}
|
|
|
|
user, err := h.store.GetUserByID(c.Context(), userID)
|
|
if err != nil {
|
|
return common.SendAppError(c, err)
|
|
}
|
|
|
|
return c.JSON(user)
|
|
}
|