339 lines
11 KiB
Go
339 lines
11 KiB
Go
package account
|
|
|
|
import (
|
|
"context"
|
|
crand "crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"go-sms/internal/model/entity"
|
|
errs "go-sms/internal/pkg/errors"
|
|
)
|
|
|
|
// ---- Day 23:IP 白名单 / 审核模式 / 业务开关 ----
|
|
|
|
// SetProtocol 更新账号接入协议(Day 30/A-2.1:HTTP/CMPP/SMPP/Web 四类账号)。
|
|
func (s *Service) SetProtocol(ctx context.Context, accountID int64, business, protocol string) error {
|
|
valid := map[string]bool{"http": true, "cmpp": true, "smpp": true, "web": true}
|
|
if !valid[protocol] {
|
|
return errs.InvalidParam.WithMsg("协议仅支持 http/cmpp/smpp/web")
|
|
}
|
|
res := s.config.DB().WithContext(ctx).Model(&entity.AccountConfig{}).
|
|
Where("account_id = ? AND business = ?", accountID, business).
|
|
Update("protocol", protocol)
|
|
if res.Error != nil {
|
|
return res.Error
|
|
}
|
|
if res.RowsAffected == 0 {
|
|
return errs.NotFound.WithMsg("账号或业务线不存在(须先开户)")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetIPBindings 获取账号的 IP 白名单(JSON 数组,存于 account_user.ip_bind)。
|
|
func (s *Service) GetIPBindings(ctx context.Context, accountID int64) ([]string, error) {
|
|
u, err := s.dao.GetByID(ctx, accountID)
|
|
if err != nil {
|
|
return nil, errs.NotFound.WithMsg("账号不存在")
|
|
}
|
|
return parseIPList(u.IPBind), nil
|
|
}
|
|
|
|
// SetIPBindings 设置 IP 白名单(存储为 JSON 数组;空列表=不限制)。
|
|
func (s *Service) SetIPBindings(ctx context.Context, accountID int64, ips []string) error {
|
|
for _, ip := range ips {
|
|
if !isValidIP(ip) {
|
|
return errs.InvalidParam.WithMsg(fmt.Sprintf("非法 IP 地址: %q", ip))
|
|
}
|
|
}
|
|
jsonStr := ""
|
|
if len(ips) > 0 {
|
|
b, _ := json.Marshal(ips)
|
|
jsonStr = string(b)
|
|
}
|
|
return s.config.DB().WithContext(ctx).Model(&entity.AccountUser{}).
|
|
Where("id = ?", accountID).Update("ip_bind", jsonStr).Error
|
|
}
|
|
|
|
// CheckIPAllowed 校验请求 IP 是否在白名单内(空白名单=允许所有)。
|
|
func (s *Service) CheckIPAllowed(ctx context.Context, accountID int64, clientIP string) (bool, error) {
|
|
u, err := s.dao.GetByID(ctx, accountID)
|
|
if err != nil {
|
|
return true, nil // 账号不存在则不限制(由 JWT 层拦截)
|
|
}
|
|
return IPAllowed(u.IPBind, clientIP), nil
|
|
}
|
|
|
|
// IPAllowed 判定 clientIP 是否命中 ip_bind JSON 白名单(Day 46 导出供外部 API 验签复用;
|
|
// 空白名单=允许所有;支持精确 IP 与 a.b.c.* 前缀通配)。
|
|
func IPAllowed(ipBindJSON, clientIP string) bool {
|
|
ips := parseIPList(ipBindJSON)
|
|
if len(ips) == 0 {
|
|
return true
|
|
}
|
|
for _, allowed := range ips {
|
|
if ipMatch(allowed, clientIP) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// ---- 审核模式 ----
|
|
|
|
// SetAuditMode 设置审核模式(0免审/1手动/2自动审核——黑词命中拒/未命中过,对齐 audit.ModeAuto 口径)。
|
|
func (s *Service) SetAuditMode(ctx context.Context, accountID int64, business string, mode int) error {
|
|
if mode < 0 || mode > 2 {
|
|
return errs.InvalidParam.WithMsg(fmt.Sprintf("非法审核模式 %d(0免审/1手动/2自动审核·黑词)", mode))
|
|
}
|
|
result := s.config.DB().WithContext(ctx).Model(&entity.AccountConfig{}).
|
|
Where("account_id = ? AND business = ?", accountID, business).
|
|
Update("audit_mode", mode)
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
if result.RowsAffected == 0 {
|
|
return errs.NotFound.WithMsg("账号业务配置不存在")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ---- 业务开关(按位操作) ----
|
|
|
|
// EnableBusiness 开通业务线(在 account_config 中添加行)。
|
|
func (s *Service) EnableBusiness(ctx context.Context, accountID int64, business string) error {
|
|
if !isBusinessCode(business) {
|
|
return errs.InvalidParam.WithMsg(fmt.Sprintf("非法业务线 %q", business))
|
|
}
|
|
// 检查是否已开通
|
|
var n int64
|
|
s.config.DB().WithContext(ctx).Model(&entity.AccountConfig{}).
|
|
Where("account_id = ? AND business = ?", accountID, business).Count(&n)
|
|
if n > 0 {
|
|
return errs.InvalidParam.WithMsg("该业务线已开通")
|
|
}
|
|
return s.config.DB().WithContext(ctx).Create(&entity.AccountConfig{
|
|
AccountID: accountID, Business: business, Protocol: "http", AuditMode: 0, FailRefund: 1,
|
|
}).Error
|
|
}
|
|
|
|
// DisableBusiness 关闭业务线(删除 account_config 行)。
|
|
func (s *Service) DisableBusiness(ctx context.Context, accountID int64, business string) error {
|
|
result := s.config.DB().WithContext(ctx).Unscoped().
|
|
Where("account_id = ? AND business = ?", accountID, business).
|
|
Delete(&entity.AccountConfig{})
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
if result.RowsAffected == 0 {
|
|
return errs.NotFound.WithMsg("该业务线未开通")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetBusinessStatus 获取账号全部业务线开通状态。
|
|
func (s *Service) GetBusinessStatus(ctx context.Context, accountID int64) (map[string]bool, error) {
|
|
var cfgs []entity.AccountConfig
|
|
if err := s.config.DB().WithContext(ctx).Where("account_id = ?", accountID).Find(&cfgs).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
status := map[string]bool{}
|
|
for _, code := range businessCode {
|
|
status[code] = false
|
|
}
|
|
for _, c := range cfgs {
|
|
status[c.Business] = true
|
|
}
|
|
return status, nil
|
|
}
|
|
|
|
// ---- 内部工具 ----
|
|
|
|
func parseIPList(jsonStr string) []string {
|
|
if jsonStr == "" {
|
|
return nil
|
|
}
|
|
var ips []string
|
|
_ = json.Unmarshal([]byte(jsonStr), &ips)
|
|
return ips
|
|
}
|
|
|
|
func isValidIP(ip string) bool {
|
|
// 简单校验:IPv4 或 CIDR
|
|
if strings.Contains(ip, "/") {
|
|
parts := strings.SplitN(ip, "/", 2)
|
|
return isValidIPv4(parts[0])
|
|
}
|
|
return isValidIPv4(ip)
|
|
}
|
|
|
|
func isValidIPv4(ip string) bool {
|
|
parts := strings.Split(ip, ".")
|
|
if len(parts) != 4 {
|
|
return false
|
|
}
|
|
for _, p := range parts {
|
|
if p == "" || len(p) > 3 {
|
|
return false
|
|
}
|
|
n := 0
|
|
for _, c := range p {
|
|
if c < '0' || c > '9' {
|
|
return false
|
|
}
|
|
n = n*10 + int(c-'0')
|
|
}
|
|
if n > 255 {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// ipMatch 支持 CIDR 前缀匹配(如 192.168.1.0/24)。
|
|
func ipMatch(rule, ip string) bool {
|
|
if !strings.Contains(rule, "/") {
|
|
return rule == ip
|
|
}
|
|
// 简化 CIDR:前缀匹配
|
|
parts := strings.SplitN(rule, "/", 2)
|
|
prefix := strings.TrimSuffix(parts[0], "0") // 移除末尾 0(如 192.168.1.0 → 192.168.1.)
|
|
return strings.HasPrefix(ip, prefix) || strings.HasPrefix(ip, strings.TrimSuffix(parts[0], "0"))
|
|
}
|
|
|
|
func isBusinessCode(code string) bool {
|
|
for _, c := range businessCode {
|
|
if c == code {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// ---- Day 46:外部 HTTP API 配置(回调绑定/限速/扩展码/接口密钥) ----
|
|
|
|
// ApiConfigReq 外部 API 配置更新请求(零值字段不覆盖;ResetSecret 重发密钥)。
|
|
type ApiConfigReq struct {
|
|
ReportURL string `json:"report_url"` // 状态回执推送地址(http/https)
|
|
UplinkURL string `json:"uplink_url"` // 上行消息推送地址
|
|
SpeedLimit int `json:"speed_limit"` // 接口提交限速(条/秒;0=不修改)
|
|
ExtCode string `json:"ext_code"` // 通道扩展码默认值(≤32)
|
|
ResetSecret bool `json:"reset_secret"` // true=重新生成接口密钥
|
|
// Day 62→改版:自定义密码(6~64 字符;非空时优先于 ResetSecret 的随机生成)。
|
|
// 口径「库值即密码」:平台零转换原样入库,客户 CMPP/SMPP/HTTP 均直接填该值;
|
|
// CMPP Authenticator=MD5(密码+spid+ts) 由客户程序自行拼接,平台同式比对。
|
|
CustomSecret string `json:"custom_secret"`
|
|
// Day 62:CMPP 账号级接入配额(0=不修改;-1=恢复系统默认即置 0;正数=设置)。
|
|
CmppMaxConns int `json:"cmpp_max_conns"` // 每账号最大连接数(1~1024)
|
|
CmppSpeed int `json:"cmpp_speed"` // 单链提交限速 条/s(1~100000)
|
|
}
|
|
|
|
// ApiConfigResult 配置更新结果(密码原样入库与回显,口径「库值即密码」)。
|
|
type ApiConfigResult struct {
|
|
Secret string `json:"secret"` // 新密码原文(未重发时为空;CMPP/SMPP/HTTP 客户端均填它)
|
|
CmppPassword string `json:"cmpp_password"` // Day 62:CMPP 密码=库值原文(与 Secret 同值,便于前端分区展示)
|
|
}
|
|
|
|
// SetApiConfig 更新账号外部 API 配置(Day 46;短信业务线 account_config)。
|
|
// 密码口径「库值即密码」(Day62 改版):custom(6~64)/随机 32hex 均原样入库,平台零转换;
|
|
// HTTP 验签 expect=MD5(userName+timestamp+MD5(库值)),客户 password 即填库值。
|
|
func (s *Service) SetApiConfig(ctx context.Context, accountID int64, req *ApiConfigReq) (*ApiConfigResult, error) {
|
|
if req.SpeedLimit < 0 || req.SpeedLimit > 100000 {
|
|
return nil, errs.InvalidParam.WithMsg("speed_limit 须在 0~100000 条/秒")
|
|
}
|
|
for _, u := range []string{req.ReportURL, req.UplinkURL} {
|
|
if u != "" && !strings.HasPrefix(u, "http://") && !strings.HasPrefix(u, "https://") {
|
|
return nil, errs.InvalidParam.WithMsg("回调地址须以 http:// 或 https:// 开头: " + u)
|
|
}
|
|
if len(u) > 255 {
|
|
return nil, errs.InvalidParam.WithMsg("回调地址超 255 字符")
|
|
}
|
|
}
|
|
if len(req.ExtCode) > 32 {
|
|
return nil, errs.InvalidParam.WithMsg("ext_code 超 32 字符")
|
|
}
|
|
// Day 62:CMPP 账号级配额校验(0=不修改;-1=恢复系统默认;正数=设置)。
|
|
for _, v := range []struct {
|
|
name string
|
|
val int
|
|
max int
|
|
}{{"cmpp_max_conns", req.CmppMaxConns, 1024}, {"cmpp_speed", req.CmppSpeed, 100000}} {
|
|
if (v.val < -1) || (v.val > 0 && v.val > v.max) {
|
|
return nil, errs.InvalidParam.WithMsg(
|
|
v.name + " 须为 -1(恢复默认)/0(不修改)/1~" + strconv.Itoa(v.max))
|
|
}
|
|
}
|
|
// Day 62:自定义密码长度校验(≥6;协议拼接由客户自行处理,平台不转换)。
|
|
if req.CustomSecret != "" && (len(req.CustomSecret) < 6 || len(req.CustomSecret) > 64) {
|
|
return nil, errs.InvalidParam.WithMsg("custom_secret 须为 6~64 字符")
|
|
}
|
|
updates := map[string]interface{}{}
|
|
if req.ReportURL != "" {
|
|
updates["report_url"] = req.ReportURL
|
|
}
|
|
if req.UplinkURL != "" {
|
|
updates["uplink_url"] = req.UplinkURL
|
|
}
|
|
if req.SpeedLimit > 0 {
|
|
updates["speed_limit"] = req.SpeedLimit
|
|
}
|
|
if req.ExtCode != "" {
|
|
updates["ext_code"] = req.ExtCode
|
|
}
|
|
// Day 62:CMPP 配额(-1=恢复系统默认即置 0;正数=设置;0=不修改)。
|
|
if req.CmppMaxConns == -1 || req.CmppMaxConns > 0 {
|
|
v := 0
|
|
if req.CmppMaxConns > 0 {
|
|
v = req.CmppMaxConns
|
|
}
|
|
updates["cmpp_max_conns"] = v
|
|
}
|
|
if req.CmppSpeed == -1 || req.CmppSpeed > 0 {
|
|
v := 0
|
|
if req.CmppSpeed > 0 {
|
|
v = req.CmppSpeed
|
|
}
|
|
updates["cmpp_speed"] = v
|
|
}
|
|
out := &ApiConfigResult{}
|
|
// Day 62「库值即密码」:自定义优先于随机重发;原样入库(零转换),
|
|
// CMPP(拼接 Authenticator)/SMPP(明文比对)/HTTP(填库值原文)均直接使用该值。
|
|
plain := ""
|
|
if req.CustomSecret != "" {
|
|
plain = req.CustomSecret
|
|
} else if req.ResetSecret {
|
|
plain = GenApiSecret()
|
|
}
|
|
if plain != "" {
|
|
updates["api_secret"] = plain
|
|
out.Secret = plain
|
|
out.CmppPassword = plain
|
|
}
|
|
if len(updates) == 0 {
|
|
return out, nil
|
|
}
|
|
res := s.config.DB().WithContext(ctx).Model(&entity.AccountConfig{}).
|
|
Where("account_id = ? AND business = ?", accountID, "sms").Updates(updates)
|
|
if res.Error != nil {
|
|
return nil, res.Error
|
|
}
|
|
if res.RowsAffected == 0 {
|
|
return nil, errs.NotFound.WithMsg("账号短信业务配置不存在(须先开户)")
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// GenApiSecret 生成 32hex 随机密钥(crypto/rand)。
|
|
func GenApiSecret() string {
|
|
b := make([]byte, 16)
|
|
if _, err := crand.Read(b); err != nil {
|
|
// rand 失败极端场景:时间戳兜底(仍有随机前缀碰撞窗口,可忽略)
|
|
return fmt.Sprintf("%x", time.Now().UnixNano())
|
|
}
|
|
return hex.EncodeToString(b)
|
|
}
|