forked from mtusi2026/mtusi2026lab5
chore(migrate) moved codebase from lab4
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
// 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
|
||||
jsonBodyLimit int64
|
||||
}
|
||||
|
||||
func NewHandler(st *store.Store, jsonBodyLimit int64) *Handler {
|
||||
return &Handler{store: st, jsonBodyLimit: jsonBodyLimit}
|
||||
}
|
||||
|
||||
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, h.jsonBodyLimit); 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)
|
||||
}
|
||||
Reference in New Issue
Block a user