feat: add send phone code

This commit is contained in:
2025-12-20 13:37:20 +08:00
parent 12aa7a404a
commit 3f716b669c
5 changed files with 164 additions and 22 deletions

View File

@@ -6,7 +6,6 @@ import (
"github.com/gofiber/fiber/v3"
"github.com/pkg/errors"
"gorm.io/gorm"
)
// @provider
@@ -18,49 +17,43 @@ type auth struct {
//
// @Summary 手机验证
// @Tags Auth
// @Accept json
// @Produce json
// @Param form body PhoneValidationForm true "手机号"
// @Success 200 {object} any "成功"
// @Router /v1/auth/phone [post]
// @Bind form body
func (ctl *auth) Phone(ctx fiber.Ctx, form *PhoneValidationForm) error {
_, err := services.Users.FindByPhone(ctx, form.Phone)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return errors.New("手机号未注册,请联系管理员开通")
}
return err
}
// TODO: send sms
return nil
return services.Users.SendPhoneCode(ctx, form.Phone)
}
type PhoneValidationForm struct {
Phone string `json:"phone,omitempty"`
Code *string `json:"code,omitempty"`
Phone string `json:"phone,omitempty"` // 手机号(必须为已注册用户)
Code *string `json:"code,omitempty"` // 短信验证码(/v1/auth/validate 使用)
}
type TokenResponse struct {
Token string `json:"token,omitempty"`
Token string `json:"token,omitempty"` // 登录 token用于 Authorization: Bearer <token>
}
// Validate
//
// @Summary 手机验证
// @Tags Auth
// @Accept json
// @Produce json
// @Param body body PhoneValidationForm true "请求体"
// @Success 200 {object} any "成功"
// @Success 200 {object} TokenResponse "成功"
// @Router /v1/auth/validate [post]
// @Bind body body
func (ctl *auth) Validate(ctx fiber.Ctx, body *PhoneValidationForm) (*TokenResponse, error) {
user, err := services.Users.FindByPhone(ctx, body.Phone)
if err != nil {
return nil, errors.New("手机号未注册,请联系管理员开通")
if body.Code == nil {
return nil, errors.New("验证码不能为空")
}
if body.Code == nil || *body.Code != "1234" {
return nil, errors.New("验证码错误")
user, err := services.Users.ValidatePhoneCode(ctx, body.Phone, *body.Code)
if err != nil {
return nil, err
}
// generate token for user