67 lines
1.6 KiB
Go
67 lines
1.6 KiB
Go
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
|
||
}
|