74 lines
1.7 KiB
Go
74 lines
1.7 KiB
Go
package http
|
|
|
|
import (
|
|
"quyun/v2/app/services"
|
|
"quyun/v2/providers/jwt"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/pkg/errors"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// @provider
|
|
type auth struct {
|
|
jwt *jwt.JWT
|
|
}
|
|
|
|
// Phone
|
|
//
|
|
// @Summary 手机验证
|
|
// @Tags Auth
|
|
// @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
|
|
}
|
|
|
|
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
|
|
// @Param body body PhoneValidationForm true "请求体"
|
|
// @Success 200 {object} any "成功"
|
|
// @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 || *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
|
|
}
|