Files
quyun/backend_v1/app/http/auth.go
2025-12-20 13:37:20 +08:00

67 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package http
import (
"quyun/v2/app/services"
"quyun/v2/providers/jwt"
"github.com/gofiber/fiber/v3"
"github.com/pkg/errors"
)
// @provider
type auth struct {
jwt *jwt.JWT
}
// Phone
//
// @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 {
return services.Users.SendPhoneCode(ctx, form.Phone)
}
type PhoneValidationForm struct {
Phone string `json:"phone,omitempty"` // 手机号(必须为已注册用户)
Code *string `json:"code,omitempty"` // 短信验证码(/v1/auth/validate 使用)
}
type TokenResponse struct {
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} TokenResponse "成功"
// @Router /v1/auth/validate [post]
// @Bind body body
func (ctl *auth) Validate(ctx fiber.Ctx, body *PhoneValidationForm) (*TokenResponse, error) {
if body.Code == nil {
return nil, errors.New("验证码不能为空")
}
user, err := services.Users.ValidatePhoneCode(ctx, body.Phone, *body.Code)
if err != nil {
return nil, err
}
// generate token for user
jwtToken, err := ctl.jwt.CreateToken(ctl.jwt.CreateClaims(jwt.BaseClaims{UserID: user.ID}))
if err != nil {
return nil, errors.Wrap(err, "failed to create token")
}
return &TokenResponse{Token: jwtToken}, nil
}