71 lines
1.5 KiB
Go
71 lines
1.5 KiB
Go
package user
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
|
|
"messenger/internal/auth"
|
|
"messenger/internal/platform/httpx"
|
|
)
|
|
|
|
type Handler struct {
|
|
users *Service
|
|
}
|
|
|
|
func NewHandler(users *Service) *Handler {
|
|
return &Handler{users: users}
|
|
}
|
|
|
|
// Register mounts registration on the public router and the current-user
|
|
// endpoint on the router guarded by RequireUser.
|
|
func (h *Handler) Register(public, protected gin.IRouter) {
|
|
public.POST("/users", h.register)
|
|
protected.GET("/users/me", auth.WithUser(h.me))
|
|
}
|
|
|
|
type createRequest struct {
|
|
Username string `json:"username"`
|
|
DisplayName string `json:"display_name"`
|
|
}
|
|
|
|
type Response struct {
|
|
ID string `json:"id"`
|
|
Username string `json:"username"`
|
|
DisplayName string `json:"display_name"`
|
|
CreatedAt string `json:"created_at"`
|
|
}
|
|
|
|
func ToResponse(u User) Response {
|
|
return Response{
|
|
ID: u.ID.String(),
|
|
Username: u.Username,
|
|
DisplayName: u.DisplayName,
|
|
CreatedAt: httpx.Timestamp(u.CreatedAt),
|
|
}
|
|
}
|
|
|
|
func (h *Handler) register(c *gin.Context) {
|
|
var req createRequest
|
|
if err := httpx.DecodeJSON(c, &req); err != nil {
|
|
httpx.Error(c, err)
|
|
return
|
|
}
|
|
u, err := h.users.Register(c.Request.Context(), req.Username, req.DisplayName)
|
|
if err != nil {
|
|
httpx.Error(c, err)
|
|
return
|
|
}
|
|
httpx.JSON(c, http.StatusCreated, ToResponse(u))
|
|
}
|
|
|
|
func (h *Handler) me(c *gin.Context, actor uuid.UUID) {
|
|
u, err := h.users.GetByID(c.Request.Context(), actor)
|
|
if err != nil {
|
|
httpx.Error(c, err)
|
|
return
|
|
}
|
|
httpx.JSON(c, http.StatusOK, ToResponse(u))
|
|
}
|