2023-07-25 17:00:24 +08:00
|
|
|
package handler
|
|
|
|
|
|
|
|
import (
|
|
|
|
"chatplus/core"
|
|
|
|
"chatplus/core/types"
|
|
|
|
"chatplus/service"
|
|
|
|
"chatplus/utils"
|
|
|
|
"chatplus/utils/resp"
|
|
|
|
"github.com/gin-gonic/gin"
|
2023-11-22 10:57:24 +08:00
|
|
|
"github.com/go-redis/redis/v8"
|
2024-01-05 18:17:11 +08:00
|
|
|
"strings"
|
2023-07-25 17:00:24 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
const CodeStorePrefix = "/verify/codes/"
|
|
|
|
|
|
|
|
type SmsHandler struct {
|
|
|
|
BaseHandler
|
2023-11-22 10:57:24 +08:00
|
|
|
redis *redis.Client
|
2023-07-25 17:00:24 +08:00
|
|
|
sms *service.AliYunSmsService
|
2024-01-05 18:17:11 +08:00
|
|
|
smtp *service.SmtpService
|
2023-07-25 17:00:24 +08:00
|
|
|
captcha *service.CaptchaService
|
|
|
|
}
|
|
|
|
|
2024-01-05 18:17:11 +08:00
|
|
|
func NewSmsHandler(
|
|
|
|
app *core.AppServer,
|
|
|
|
client *redis.Client,
|
|
|
|
sms *service.AliYunSmsService,
|
|
|
|
smtp *service.SmtpService,
|
|
|
|
captcha *service.CaptchaService) *SmsHandler {
|
|
|
|
handler := &SmsHandler{redis: client, sms: sms, captcha: captcha, smtp: smtp}
|
2023-07-25 17:00:24 +08:00
|
|
|
handler.App = app
|
|
|
|
return handler
|
|
|
|
}
|
|
|
|
|
2024-01-05 18:17:11 +08:00
|
|
|
// SendCode 发送验证码
|
2023-07-27 10:53:14 +08:00
|
|
|
func (h *SmsHandler) SendCode(c *gin.Context) {
|
2023-07-25 17:00:24 +08:00
|
|
|
var data struct {
|
2024-01-05 18:17:11 +08:00
|
|
|
Receiver string `json:"receiver"` // 接收者
|
|
|
|
Key string `json:"key"`
|
|
|
|
Dots string `json:"dots"`
|
2023-07-25 17:00:24 +08:00
|
|
|
}
|
|
|
|
if err := c.ShouldBindJSON(&data); err != nil {
|
|
|
|
resp.ERROR(c, types.InvalidArgs)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if !h.captcha.Check(data) {
|
|
|
|
resp.ERROR(c, "验证码错误,请先完人机验证")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
code := utils.RandomNumber(6)
|
2024-01-05 18:17:11 +08:00
|
|
|
var err error
|
|
|
|
if strings.Contains(data.Receiver, "@") { // email
|
|
|
|
err = h.smtp.SendVerifyCode(data.Receiver, code)
|
|
|
|
} else {
|
|
|
|
err = h.sms.SendVerifyCode(data.Receiver, code)
|
|
|
|
}
|
2023-07-25 17:00:24 +08:00
|
|
|
if err != nil {
|
|
|
|
resp.ERROR(c, err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// 存储验证码,等待后面注册验证
|
2024-01-05 18:17:11 +08:00
|
|
|
_, err = h.redis.Set(c, CodeStorePrefix+data.Receiver, code, 0).Result()
|
2023-07-25 17:00:24 +08:00
|
|
|
if err != nil {
|
|
|
|
resp.ERROR(c, "验证码保存失败")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
resp.SUCCESS(c)
|
|
|
|
}
|