86 lines
2.1 KiB
Go
86 lines
2.1 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"hepa-calc-admin-api/extend/aliyun"
|
|
"hepa-calc-admin-api/global"
|
|
"math/rand"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
type PublicService struct {
|
|
}
|
|
|
|
// GetPhoneCode 获取手机验证码
|
|
func (r *PublicService) GetPhoneCode(scene int, phone string) (bool, error) {
|
|
var sendCodeCount int // // 获取验证码最大次数
|
|
var code string // 验证码
|
|
var templateCode string // 短信模版
|
|
|
|
// 登录获取验证码
|
|
if scene == 1 {
|
|
// 验证发送次数
|
|
res, _ := global.Redis.Get(context.Background(), "login_code_count_"+phone).Result()
|
|
if res != "" {
|
|
sendCodeCount, err := strconv.Atoi(res)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
if sendCodeCount > 3 {
|
|
// 超出规定时间内最大获取次数
|
|
return false, errors.New("手机号超出规定时间内最大获取次数,请您稍后再试")
|
|
}
|
|
}
|
|
|
|
// 生成随机数
|
|
rand.New(rand.NewSource(time.Now().UnixNano()))
|
|
code = strconv.Itoa(rand.Intn(9000) + 1000)
|
|
|
|
// 模版
|
|
templateCode = "SMS_243055263"
|
|
|
|
sendCodeCount = sendCodeCount + 1
|
|
}
|
|
|
|
if code == "" || templateCode == "" {
|
|
return false, errors.New("验证码发送失败,请您稍后再试")
|
|
}
|
|
|
|
// 发送验证码
|
|
templateParam := make(map[string]interface{})
|
|
templateParam["code"] = code
|
|
err := aliyun.SendSms(phone, templateCode, "获取验证码", templateParam)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
// 记录发送次数
|
|
if sendCodeCount != 0 {
|
|
_, err = global.Redis.Set(context.Background(), "login_code_count_"+phone, time.Now().Unix(), 60*5*time.Second).Result()
|
|
if err != nil {
|
|
return false, errors.New("验证码发送失败,请您稍后再试")
|
|
}
|
|
}
|
|
|
|
// 设置验证码有效期
|
|
_, err = global.Redis.Set(context.Background(), "login_code_"+phone, code, 60*5*time.Second).Result()
|
|
if err != nil {
|
|
return false, errors.New("验证码发送失败,请您稍后再试")
|
|
}
|
|
|
|
return true, nil
|
|
}
|
|
|
|
// GetUserIP 获取用户ip
|
|
func (r *PublicService) GetUserIP(h *http.Request) string {
|
|
forwarded := h.Header.Get("X-FORWARDED-FOR")
|
|
if forwarded != "" {
|
|
return forwarded
|
|
}
|
|
return h.RemoteAddr
|
|
}
|