refactor: reorganize modules and add Linux build tooling
This commit is contained in:
152
module/base/sender/internal/logic/mail/send.go
Normal file
152
module/base/sender/internal/logic/mail/send.go
Normal file
@@ -0,0 +1,152 @@
|
||||
package mail
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/mail"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
|
||||
"bsm/full/module/base/sender/internal/config"
|
||||
"bsm/full/module/base/sender/internal/excode"
|
||||
"bsm/full/module/base/sender/internal/impl"
|
||||
"bsm/full/module/base/sender/internal/models"
|
||||
pb "bsm/full/module/base/sender/pb"
|
||||
"git.apinb.com/bsm-sdk/core/errcode"
|
||||
"git.apinb.com/bsm-sdk/core/vars"
|
||||
)
|
||||
|
||||
func Send(ctx context.Context, in *pb.SendMailRequest) (reply *pb.SendMailReply, err error) {
|
||||
provider := strings.ToLower(in.GetProvider())
|
||||
|
||||
// 校验参数
|
||||
if in.GetTemplateKey() == "" || provider == "" || in.GetTo() == "" {
|
||||
return nil, errcode.ErrInvalidArgument
|
||||
}
|
||||
|
||||
// 校验配置
|
||||
cfg, ok := config.Spec.SMTP[provider]
|
||||
if !ok || cfg == nil {
|
||||
return nil, excode.ErrProviderIsNil
|
||||
}
|
||||
|
||||
// 检验邮箱格式
|
||||
if !ValidateEmail(in.GetTo()) {
|
||||
return nil, excode.ErrEmail
|
||||
}
|
||||
|
||||
// 获取模板
|
||||
var tplRecord models.SenderTemplate
|
||||
err = impl.DBService.Where("key=?", in.GetTemplateKey()).First(&tplRecord).Error
|
||||
if err != nil {
|
||||
return nil, errcode.ErrNotFound(1404, "template")
|
||||
}
|
||||
|
||||
// 解析模板
|
||||
tmpl, err := template.New("page").Parse(tplRecord.Body)
|
||||
if err != nil {
|
||||
return nil, excode.ErrTemplate
|
||||
}
|
||||
|
||||
// 发送邮件
|
||||
switch provider {
|
||||
case "qq":
|
||||
err = QQ(cfg, tmpl, in.GetTo(), tplRecord.Subjet, in.GetParamters())
|
||||
default:
|
||||
return nil, excode.ErrNotProvider
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pb.SendMailReply{
|
||||
Data: vars.OK,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func ValidateEmail(s string) bool {
|
||||
_, err := mail.ParseAddress(s)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func QQ(cfg *config.SmtpConf, tmpl *template.Template, to string, subject string, args map[string]string) error {
|
||||
// 建立TLS加密连接
|
||||
conn, err := tls.Dial("tcp", fmt.Sprintf("%s:%d", cfg.Endpoint, cfg.Port), &tls.Config{
|
||||
ServerName: cfg.Endpoint,
|
||||
MinVersion: tls.VersionTLS12, // 强制TLS1.2+
|
||||
InsecureSkipVerify: false,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Println("TLS连接失败: ", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// 创建SMTP客户端(带超时控制)
|
||||
client, err := smtp.NewClient(conn, cfg.Endpoint)
|
||||
if err != nil {
|
||||
client.Close()
|
||||
fmt.Println("SMTP客户端初始化失败: ", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// 设置认证
|
||||
auth := smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Endpoint)
|
||||
if err := client.Auth(auth); err != nil {
|
||||
client.Close()
|
||||
fmt.Println("认证失败: ", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// 设置发件人和收件人
|
||||
err = client.Mail(cfg.FromAddress)
|
||||
if err != nil {
|
||||
client.Close()
|
||||
fmt.Println("发件人设置失败: ", err)
|
||||
return err
|
||||
}
|
||||
err = client.Rcpt(to)
|
||||
if err != nil {
|
||||
fmt.Println("发件人设置失败: ", err)
|
||||
client.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
// 创建一个写入SMTP服务器的标准写入器
|
||||
writer, err := client.Data()
|
||||
if err != nil {
|
||||
client.Close()
|
||||
return err
|
||||
}
|
||||
defer writer.Close()
|
||||
|
||||
// 构建邮件正文
|
||||
mailBody := "From: " + cfg.FromName + "<" + cfg.FromAddress + ">\n"
|
||||
mailBody += "To: " + to + "\n"
|
||||
mailBody += "Subject: " + subject + "\n\n"
|
||||
|
||||
// 执行模板,将结果写入邮件正文
|
||||
var buf bytes.Buffer
|
||||
err = tmpl.Execute(&buf, args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mailBody += buf.String()
|
||||
|
||||
// 将邮件正文发送到SMTP服务器
|
||||
if _, err := writer.Write([]byte(mailBody)); err != nil {
|
||||
client.Close()
|
||||
fmt.Printf("写入邮件内容失败: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := writer.Close(); err != nil {
|
||||
client.Close()
|
||||
fmt.Printf("关闭数据流失败: %v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
8
module/base/sender/internal/logic/sms/const.go
Normal file
8
module/base/sender/internal/logic/sms/const.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package sms
|
||||
|
||||
const (
|
||||
FormatDay = "2006-01-02"
|
||||
KeyPrefix = "/SMS/Code/"
|
||||
BlackListCacheKey = "/SMS/BlackList/"
|
||||
LimitCacheKey = "/SMS/LimitCacheKey/"
|
||||
)
|
||||
176
module/base/sender/internal/logic/sms/send.go
Normal file
176
module/base/sender/internal/logic/sms/send.go
Normal file
@@ -0,0 +1,176 @@
|
||||
package sms
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"bsm/full/module/base/sender/internal/config"
|
||||
"bsm/full/module/base/sender/internal/excode"
|
||||
"bsm/full/module/base/sender/internal/impl"
|
||||
pb "bsm/full/module/base/sender/pb"
|
||||
"git.apinb.com/bsm-sdk/core/cache/redis"
|
||||
"git.apinb.com/bsm-sdk/core/errcode"
|
||||
AliYunClient "github.com/alibabacloud-go/darabonba-openapi/v2/client"
|
||||
AliYunUtil "github.com/alibabacloud-go/darabonba-openapi/v2/utils"
|
||||
"github.com/alibabacloud-go/tea/dara"
|
||||
"github.com/alibabacloud-go/tea/tea"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
func Send(ctx context.Context, in *pb.SmsSendRequest) (reply *pb.SmsReply, err error) {
|
||||
var smsCode string
|
||||
|
||||
if in.GetPhone() == "" || !VerifyPhone(in.GetPhone()) {
|
||||
return nil, excode.ErrPhone
|
||||
}
|
||||
if in.GetTemplateCode() == "" {
|
||||
return nil, excode.ErrTemplate
|
||||
}
|
||||
|
||||
// 是否验证黑名单
|
||||
if impl.RedisService.Client.SIsMember(impl.RedisService.Ctx, BlackListCacheKey, in.GetPhone()).Val() {
|
||||
return nil, excode.ErrInBlackList
|
||||
}
|
||||
|
||||
// 每天限制
|
||||
limitKey := LimitCacheKey + time.Now().Format(FormatDay) + in.GetPhone()
|
||||
|
||||
// check limit
|
||||
twice, err := impl.RedisService.Client.Get(impl.RedisService.Ctx, limitKey).Int()
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
return nil, errcode.ErrRedis
|
||||
}
|
||||
if twice > config.Spec.Code.MaxSentLimit {
|
||||
return nil, excode.ErrSentLimit
|
||||
}
|
||||
|
||||
// 从redis获取验证码,如果没有重新生成
|
||||
key := KeyPrefix + in.GetPhone()
|
||||
if in.GetIsGenCode() {
|
||||
//验证码最少4位,最大10位。
|
||||
if config.Spec.Code.Length < 4 || config.Spec.Code.Length > 10 {
|
||||
config.Spec.Code.Length = 6
|
||||
}
|
||||
|
||||
// 新生成验证码
|
||||
smsCode = GenValidateCode(config.Spec.Code.Length)
|
||||
//sms code write to redis
|
||||
expire := time.Second * time.Duration(config.Spec.Code.Expire)
|
||||
impl.RedisService.Client.SetNX(impl.RedisService.Ctx, key, smsCode, expire)
|
||||
} else {
|
||||
// 获取验证码
|
||||
if code, ok := in.Paramters["code"]; ok {
|
||||
smsCode = code
|
||||
} else {
|
||||
return nil, excode.ErrCode
|
||||
}
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
switch strings.ToLower(in.GetProvider()) {
|
||||
case "aliyun":
|
||||
if impl.Provider.Aliyun == nil {
|
||||
return nil, excode.ErrProviderIsNil
|
||||
}
|
||||
result, err = AliyunSender(in, smsCode)
|
||||
case "tencent":
|
||||
if impl.Provider.Tencent == nil {
|
||||
return nil, excode.ErrProviderIsNil
|
||||
}
|
||||
result, err = TencentSender(in)
|
||||
default:
|
||||
return nil, excode.ErrNotProvider
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
jsonBytes, _ := json.Marshal(result)
|
||||
fmt.Println("短信发送结果:", string(jsonBytes))
|
||||
return &pb.SmsReply{
|
||||
Reply: string(jsonBytes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func AliyunSender(args *pb.SmsSendRequest, code string) (map[string]any, error) {
|
||||
// 构建发送参数
|
||||
var templateParam = map[string]any{
|
||||
"code": code,
|
||||
}
|
||||
for key, val := range args.Paramters {
|
||||
templateParam[key] = val
|
||||
}
|
||||
jsonBytes, _ := json.Marshal(templateParam)
|
||||
|
||||
params := map[string]any{
|
||||
// 必填,接收短信的手机号码
|
||||
"PhoneNumbers": tea.String(cast.ToString(args.Phone)),
|
||||
// 必填,短信签名名称
|
||||
"SignName": tea.String(cast.ToString(args.SignName)),
|
||||
// 必填,短信模板ID
|
||||
"TemplateCode": tea.String(cast.ToString(args.TemplateCode)),
|
||||
// 可选,模板参数
|
||||
"TemplateParam": string(jsonBytes),
|
||||
}
|
||||
|
||||
runtime := &dara.RuntimeOptions{}
|
||||
request := &AliYunClient.OpenApiRequest{
|
||||
Query: AliYunUtil.Query(params),
|
||||
}
|
||||
|
||||
clientParams := &AliYunClient.Params{
|
||||
// 接口名称
|
||||
Action: tea.String("SendSms"),
|
||||
// 接口版本
|
||||
Version: tea.String("2017-05-25"),
|
||||
// 接口协议
|
||||
Protocol: tea.String("HTTPS"),
|
||||
// 接口 HTTP 方法
|
||||
Method: tea.String("POST"),
|
||||
AuthType: tea.String("AK"),
|
||||
Style: tea.String("RPC"),
|
||||
// 接口 PATH
|
||||
Pathname: tea.String("/"),
|
||||
// 接口请求体内容格式
|
||||
ReqBodyType: tea.String("json"),
|
||||
// 接口响应体内容格式
|
||||
BodyType: tea.String("json"),
|
||||
}
|
||||
fmt.Println("请求参数params为:", params)
|
||||
fmt.Println("请求参数clientParams为:", clientParams)
|
||||
return impl.Provider.Aliyun.CallApi(clientParams, request, runtime)
|
||||
}
|
||||
|
||||
func TencentSender(args *pb.SmsSendRequest) (map[string]any, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func VerifyPhone(phone string) bool {
|
||||
result, _ := regexp.MatchString(`^(1[3|4|5|6|7|8|9][0-9]\d{4,8})$`, phone)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// GenValidateCode .
|
||||
func GenValidateCode(width int64) string {
|
||||
if width == 0 {
|
||||
width = 4
|
||||
}
|
||||
l := 10
|
||||
numeric := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
|
||||
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
var sb strings.Builder
|
||||
for i := int64(0); i < width; i++ {
|
||||
fmt.Fprintf(&sb, "%d", numeric[rand.Intn(l)])
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
40
module/base/sender/internal/logic/sms/verify.go
Normal file
40
module/base/sender/internal/logic/sms/verify.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package sms
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"bsm/full/module/base/sender/internal/excode"
|
||||
"bsm/full/module/base/sender/internal/impl"
|
||||
pb "bsm/full/module/base/sender/pb"
|
||||
"git.apinb.com/bsm-sdk/core/errcode"
|
||||
)
|
||||
|
||||
func Verify(ctx context.Context, in *pb.SmsVerifyRequest) (reply *pb.SmsReply, err error) {
|
||||
if in.GetCode() == "" {
|
||||
return nil, excode.ErrCode
|
||||
}
|
||||
|
||||
if in.GetPhone() == "" {
|
||||
return nil, excode.ErrPhone
|
||||
}
|
||||
|
||||
//check redis
|
||||
key := KeyPrefix + in.GetPhone()
|
||||
code, err := impl.RedisService.Client.Get(impl.RedisService.Ctx, key).Result()
|
||||
if err != nil {
|
||||
return nil, errcode.NewError(1311, err.Error())
|
||||
}
|
||||
//check code
|
||||
if code == in.Code {
|
||||
return &pb.SmsReply{
|
||||
Reply: "true",
|
||||
}, nil
|
||||
}
|
||||
|
||||
//verify pass ; delete the requestId
|
||||
impl.RedisService.Client.Del(impl.RedisService.Ctx, key)
|
||||
|
||||
return &pb.SmsReply{
|
||||
Reply: "false",
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user