chore: make codes the repository root

This commit is contained in:
Eric 1549169735@qq.com
2026-08-06 21:52:03 +08:00
parent de5345607a
commit 23c9f52869
89 changed files with 21 additions and 513 deletions

80
internal/auth/handler.go Normal file
View File

@@ -0,0 +1,80 @@
package auth
import (
"errors"
"net/http"
"git.iwork-ai.com/xdc/iqudo-top1/internal/response"
"github.com/gin-gonic/gin"
)
type Handler struct {
service *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}
type loginRequest struct {
Username string `json:"username" binding:"required,min=2,max=64"`
Password string `json:"password" binding:"required,min=6,max=128"`
}
func (h *Handler) Login(c *gin.Context) {
var input loginRequest
if err := c.ShouldBindJSON(&input); err != nil {
response.Error(c, http.StatusBadRequest, "INVALID_ARGUMENT", "请输入有效的用户名和密码")
return
}
tokens, err := h.service.Login(input.Username, input.Password)
if errors.Is(err, ErrInvalidCredentials) {
response.Error(c, http.StatusUnauthorized, "INVALID_CREDENTIALS", "用户名或密码错误")
return
}
if err != nil {
response.Error(c, http.StatusInternalServerError, "LOGIN_FAILED", "登录失败")
return
}
response.OK(c, tokens)
}
func (h *Handler) Refresh(c *gin.Context) {
var input struct {
RefreshToken string `json:"refresh_token" binding:"required"`
}
if err := c.ShouldBindJSON(&input); err != nil {
response.Error(c, http.StatusBadRequest, "INVALID_ARGUMENT", "refresh_token 不能为空")
return
}
tokens, err := h.service.Refresh(input.RefreshToken)
if err != nil {
response.Error(c, http.StatusUnauthorized, "INVALID_REFRESH_TOKEN", "登录状态已失效")
return
}
response.OK(c, tokens)
}
func (h *Handler) Me(c *gin.Context) {
principal, exists := PrincipalFromContext(c)
if !exists {
response.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "请先登录")
return
}
response.OK(c, principal)
}
const principalContextKey = "principal"
func SetPrincipal(c *gin.Context, principal Principal) {
c.Set(principalContextKey, principal)
}
func PrincipalFromContext(c *gin.Context) (Principal, bool) {
value, exists := c.Get(principalContextKey)
if !exists {
return Principal{}, false
}
principal, ok := value.(Principal)
return principal, ok
}