- 每个连接记录一条日志:协议、端口、来源 IP、用户名、成功/失败、 失败原因(密码错误/IP封禁/中继被拒/发件人伪造/未认证发信等)、 操作摘要、消息数与会话时长 - 管理后台新增「协议日志」页:按协议/状态/IP/用户名/时间筛选, 今日与历史成功/失败统计卡片,分页查看,可手动清理 - 后台每 6 小时自动清理超出 protocol_log_keep_days(默认30天) 的日志;新增 [web] protocol_log_keep_days 配置项 - 修复 POP3 认证既有 bug:handleUSER 丢弃邮箱域名导致 PASS 永远失败 - 新增 store 单测、SMTP/POP3 端到端测试与模板渲染测试
55 lines
1.5 KiB
Go
55 lines
1.5 KiB
Go
package db
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"mail_go/config"
|
|
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
)
|
|
|
|
// InitDB initializes the database connection and performs auto-migration.
|
|
// It selects the appropriate driver based on cfg.Driver and resolves
|
|
// the DSN path for SQLite relative to the storage base directory.
|
|
func InitDB(cfg config.DatabaseConfig, storageCfg config.StorageConfig) (*gorm.DB, error) {
|
|
var dialector gorm.Dialector
|
|
|
|
switch cfg.Driver {
|
|
case "sqlite":
|
|
dsn := cfg.DSN
|
|
// If the DSN is the default relative path, prepend the storage base directory
|
|
if dsn == config.DefaultDSNWin || dsn == config.DefaultDSNLinux {
|
|
dsn = filepath.Join(storageCfg.BaseDir, "mail.db")
|
|
}
|
|
// Ensure the parent directory exists for SQLite
|
|
dir := filepath.Dir(dsn)
|
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
|
return nil, fmt.Errorf("创建数据库目录失败 %s: %w", dir, err)
|
|
}
|
|
dialector = sqlite.Open(dsn)
|
|
case "mysql":
|
|
dialector = mysql.Open(cfg.DSN)
|
|
default:
|
|
return nil, fmt.Errorf("不支持的数据库驱动: %s", cfg.Driver)
|
|
}
|
|
|
|
db, err := gorm.Open(dialector, &gorm.Config{
|
|
Logger: logger.Default.LogMode(logger.Warn),
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("连接数据库失败: %w", err)
|
|
}
|
|
|
|
// Auto-migrate all models
|
|
if err := db.AutoMigrate(&User{}, &Domain{}, &Message{}, &Attachment{}, &BanEntry{}, &OutboundMessage{}, &ProtocolLog{}); err != nil {
|
|
return nil, fmt.Errorf("数据库迁移失败: %w", err)
|
|
}
|
|
|
|
return db, nil
|
|
}
|