77 lines
2.9 KiB
Go
77 lines
2.9 KiB
Go
// openapi/auth.go Day 46:MD5 验签(协议 §鉴权:sign=MD5(userName+timestamp+MD5(password)))。
|
|
// 顺序:用户名→账号存在→状态→业务配置→IP 白名单→时间戳±5min→签名比对。
|
|
package openapi
|
|
|
|
import (
|
|
"context"
|
|
"crypto/md5"
|
|
"crypto/subtle"
|
|
"fmt"
|
|
"strconv"
|
|
"time"
|
|
|
|
"go-sms/internal/model/entity"
|
|
"go-sms/internal/service/account"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// AuthWindow 验签时间戳窗口(秒)。
|
|
const AuthWindow = 300
|
|
|
|
// AuthContext 验签通过后的账号上下文(注入 gin.Context 供限流/提交使用)。
|
|
type AuthContext struct {
|
|
AccountID int64
|
|
Username string
|
|
Config *entity.AccountConfig // speed_limit/ext_code/回调地址
|
|
Source int8 // Day 60:受理来源打标(0→API;CMPP/SMPP 由 access 传入 2/3)
|
|
}
|
|
|
|
// Authenticator 外部 API 鉴权器(db 只读)。
|
|
type Authenticator struct{ db *gorm.DB }
|
|
|
|
// NewAuthenticator 构造。
|
|
func NewAuthenticator(db *gorm.DB) *Authenticator { return &Authenticator{db: db} }
|
|
|
|
// Authenticate 验签:返回上下文或 (code!=0, message)。失败码:1/2/3/4/16。
|
|
func (a *Authenticator) Authenticate(ctx context.Context, userName, timestamp, sign, clientIP string) (*AuthContext, int, string) {
|
|
if userName == "" {
|
|
return nil, CodeNoUser, DocMsg(CodeNoUser)
|
|
}
|
|
var u entity.AccountUser
|
|
if err := a.db.WithContext(ctx).
|
|
Where("username = ?", userName). // Model 含软删,gorm 自动过滤
|
|
First(&u).Error; err != nil {
|
|
return nil, CodeAuthFail, DocMsg(CodeAuthFail) // 账号不存在统一鉴权失败(不泄露存在性)
|
|
}
|
|
if u.Status != 1 {
|
|
return nil, CodeDisabled, DocMsg(CodeDisabled)
|
|
}
|
|
var cfg entity.AccountConfig
|
|
if err := a.db.WithContext(ctx).
|
|
Where("account_id = ? AND business = ?", u.ID, "sms").
|
|
First(&cfg).Error; err != nil {
|
|
return nil, CodeNoBiz, DocMsg(CodeNoBiz)
|
|
}
|
|
// IP 白名单(空白名单=放行;复用 account.IPAllowed 同一实现,支持 a.b.c.* 通配)。
|
|
if !account.IPAllowed(u.IPBind, clientIP) {
|
|
return nil, CodeAuthFail, "鉴权失败:来源 IP 不在白名单"
|
|
}
|
|
// 时间戳窗口(秒级)。
|
|
ts, err := strconv.ParseInt(timestamp, 10, 64)
|
|
if err != nil || time.Now().Unix()-ts > AuthWindow || ts-time.Now().Unix() > AuthWindow {
|
|
return nil, CodeStaleTS, DocMsg(CodeStaleTS)
|
|
}
|
|
// 签名(Day62 统一式「库值即密码」):expect=MD5(userName+timestamp+MD5(库值)),
|
|
// 客户 password 直接填库值;存量 md5 态库值同式成立(客户改填库值即可,无需双算)。
|
|
if cfg.ApiSecret == "" {
|
|
return nil, CodeAuthFail, "鉴权失败:接口密钥未签发,请联系管理员开通"
|
|
}
|
|
expectInner := fmt.Sprintf("%x", md5.Sum([]byte(cfg.ApiSecret)))
|
|
expect := fmt.Sprintf("%x", md5.Sum([]byte(userName+timestamp+expectInner)))
|
|
if subtle.ConstantTimeCompare([]byte(expect), []byte(sign)) != 1 {
|
|
return nil, CodeAuthFail, DocMsg(CodeAuthFail)
|
|
}
|
|
return &AuthContext{AccountID: u.ID, Username: u.Username, Config: &cfg}, CodeOK, ""
|
|
}
|