Files
mtusi2026lab3/app/internal/users/handler.go
T

62 lines
1.4 KiB
Go

// Package users implements registration and the current-user endpoint.
package users
import (
"log/slog"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
)
type Handler struct {
store *store.Store
}
func NewHandler(st *store.Store) *Handler {
return &Handler{store: st}
}
type CreateUserRequest struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
func (h *Handler) CreateUser(c fiber.Ctx) error {
var req CreateUserRequest
if err := common.BindJSON(c, &req); err != nil {
return err
}
if err := common.ValidateCreateUser(req.Username, req.DisplayName); err != nil {
return err
}
if err := common.ValidatePassword(req.Password); err != nil {
return err
}
hash, err := auth.HashPassword(req.Password)
if err != nil {
slog.Error("hash password", "err", err)
return common.Internal()
}
user, err := h.store.CreateUser(c.Context(), req.Username, req.DisplayName, hash)
if err != nil {
return err
}
return c.Status(fiber.StatusCreated).JSON(user)
}
func (h *Handler) GetCurrentUser(c fiber.Ctx) error {
user, err := h.store.GetUserByID(c.Context(), common.MustUserID(c))
if err != nil {
return err
}
return c.JSON(user)
}