Files
mygo/internal/handler/account.go
T
ld 1dfccf513a Add structured logging and centralized error handling
- Initialize slog in the serve command with terminal/file support
- Introduce `AppError` with HTTP status for unified service-layer errors
- Replace ad-hoc `api.Error` calls with `api.RespondError`
- Wrap internal errors with `model.NewInternalError` and add reference
  IDs
- Add `RequestID` middleware and switch router from `gin.Default` to
  `gin.New`
2026-07-04 16:24:22 +08:00

89 lines
2.2 KiB
Go

package handler
import (
"log/slog"
"net/http"
"github.com/gin-gonic/gin"
"github.com/dhao2001/mygo/internal/api"
"github.com/dhao2001/mygo/internal/middleware"
"github.com/dhao2001/mygo/internal/model"
"github.com/dhao2001/mygo/internal/service"
)
// AccountHandler handles authenticated account endpoints.
type AccountHandler struct {
authService *service.AuthService
}
// NewAccountHandler creates an AccountHandler.
func NewAccountHandler(authService *service.AuthService) *AccountHandler {
return &AccountHandler{authService: authService}
}
type createPasskeyRequest struct {
Label string `json:"label" binding:"required"`
}
// GetAccount handles GET /api/v1/account.
func (h *AccountHandler) GetAccount(c *gin.Context) {
userID := middleware.MustGetUserID(c)
c.JSON(http.StatusOK, gin.H{"user_id": userID})
}
// ListPasskeys handles GET /api/v1/account/passkeys.
func (h *AccountHandler) ListPasskeys(c *gin.Context) {
userID := middleware.MustGetUserID(c)
creds, err := h.authService.ListPasskeys(c.Request.Context(), userID)
if err != nil {
api.RespondError(c, err)
return
}
if creds == nil {
creds = []model.Credential{}
}
c.JSON(http.StatusOK, creds)
}
// CreatePasskey handles POST /api/v1/account/passkeys.
func (h *AccountHandler) CreatePasskey(c *gin.Context) {
userID := middleware.MustGetUserID(c)
var req createPasskeyRequest
if err := c.ShouldBindJSON(&req); err != nil {
slog.DebugContext(c.Request.Context(), "create passkey bind failed", "error", err)
api.Error(c, http.StatusBadRequest, "invalid request body")
return
}
pk, err := h.authService.CreatePasskey(c.Request.Context(), userID, req.Label)
if err != nil {
api.RespondError(c, err)
return
}
c.JSON(http.StatusCreated, pk)
}
// RevokePasskey handles DELETE /api/v1/account/passkeys/:id.
func (h *AccountHandler) RevokePasskey(c *gin.Context) {
userID := middleware.MustGetUserID(c)
passkeyID := c.Param("id")
if passkeyID == "" {
api.Error(c, http.StatusBadRequest, "missing passkey id")
return
}
if err := h.authService.RevokePasskey(c.Request.Context(), userID, passkeyID); err != nil {
api.RespondError(c, err)
return
}
c.Status(http.StatusOK)
}