feat: phone validate
This commit is contained in:
@@ -1,27 +1,29 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"errors"
|
||||
|
||||
"quyun/v2/app/services"
|
||||
"quyun/v2/providers/jwt"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// @provider
|
||||
type auth struct{}
|
||||
type auth struct {
|
||||
jwt *jwt.JWT
|
||||
}
|
||||
|
||||
// Phone
|
||||
//
|
||||
// @Summary 手机验证
|
||||
// @Tags Auth
|
||||
// @Produce json
|
||||
// @Success 200 {object} any "成功"
|
||||
// @Param form body PhoneValidationForm true "手机号"
|
||||
// @Success 200 {object} any "成功"
|
||||
// @Router /v1/auth/phone [post]
|
||||
// @Bind phone body
|
||||
func (ctl *posts) Phone(ctx fiber.Ctx, form *PhoneValidation) error {
|
||||
// @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) {
|
||||
@@ -33,20 +35,39 @@ func (ctl *posts) Phone(ctx fiber.Ctx, form *PhoneValidation) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type PhoneValidation struct {
|
||||
type PhoneValidationForm struct {
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Code *string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
type TokenResponse struct {
|
||||
Token string `json:"token,omitempty"`
|
||||
}
|
||||
|
||||
// Validate
|
||||
//
|
||||
// @Summary 手机验证
|
||||
// @Tags Auth
|
||||
// @Produce json
|
||||
// @Success 200 {object} any "成功"
|
||||
// @Param body body PhoneValidationForm true "请求体"
|
||||
// @Success 200 {object} any "成功"
|
||||
// @Router /v1/auth/validate [post]
|
||||
// @Bind phone body
|
||||
func (ctl *posts) Validate(ctx fiber.Ctx, form *PhoneValidation) error {
|
||||
// TODO: send sms
|
||||
return nil
|
||||
// @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 || *body.Code != "1234" {
|
||||
return nil, errors.New("验证码错误")
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user