Build and Publish Server / build (push) Successful in 4m11s
handler 失败分支不再丢弃 service 错误:记录含服务商名称与上游状态码的 err 供生产排障关联,对外响应保持通用 503 不变。
54 lines
1.8 KiB
Go
54 lines
1.8 KiB
Go
package handler
|
|
|
|
import (
|
|
"errors"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/gouki/lunar-server/internal/service"
|
|
)
|
|
|
|
func RequestEmailLoginCode(c *gin.Context) {
|
|
var request struct {
|
|
Email string `json:"email" binding:"required"`
|
|
}
|
|
if err := c.ShouldBindJSON(&request); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "邮箱格式错误"})
|
|
return
|
|
}
|
|
err := service.NewEmailAuthService().RequestCode(request.Email)
|
|
if errors.Is(err, service.ErrInvalidEmail) {
|
|
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "邮箱格式错误"})
|
|
return
|
|
}
|
|
if errors.Is(err, service.ErrLoginCodeRateLimited) {
|
|
c.JSON(http.StatusTooManyRequests, gin.H{"code": 429, "msg": "请稍后再获取验证码"})
|
|
return
|
|
}
|
|
if err != nil {
|
|
// 保留 service 返回的 provider 错误(含服务商名称与上游状态码),便于生产排障关联
|
|
log.Printf("[EMAIL-AUTH] 验证码发送失败: email=%s err=%v", request.Email, err)
|
|
c.JSON(http.StatusServiceUnavailable, gin.H{"code": 503, "msg": "验证码暂时无法发送"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "验证码已发送"})
|
|
}
|
|
|
|
func VerifyEmailLoginCode(c *gin.Context) {
|
|
var request struct {
|
|
Email string `json:"email" binding:"required"`
|
|
Code string `json:"code" binding:"required"`
|
|
}
|
|
if err := c.ShouldBindJSON(&request); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
|
|
return
|
|
}
|
|
user, token, err := service.NewEmailAuthService().VerifyCode(request.Email, request.Code)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "验证码无效或已过期"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "success", "data": gin.H{"token": token, "user": user}})
|
|
}
|