支持多用户
支持SSL证书支持DNS验证
增加mysql测试用例
修复DNS设置时的展示歧义
This commit is contained in:
Jinnrry authored and GitHub committed 2024-07-02 21:02:00 +08:00
1 parent 76bc24d2bd
commit 01cbdc9875
73 files changed
+4722 -538

No files matched your search

+7 -16
View File
@@ -17,26 +17,17 @@ import (
// HasAuth 检查当前用户是否有某个邮件的auth
func HasAuth(ctx *context.Context, email *models.Email) bool {
// 获取当前用户的auth
var auth []models.UserAuth
err := db.Instance.Where("user_id = ?", ctx.UserID).Find(&auth)
if ctx.IsAdmin {
return true
}
var ue *models.UserEmail
err := db.Instance.Where("email_id = ?", email.Id).Find(&ue)
if err != nil {
log.WithContext(ctx).Errorf("SQL error:%+v", err)
log.Errorf("Error while checking user: %v", err)
return false
}
var hasAuth bool
for _, userAuth := range auth {
if userAuth.EmailAccount == "*" {
hasAuth = true
break
} else if strings.Contains(email.Bcc, ctx.UserAccount) || strings.Contains(email.Cc, ctx.UserAccount) || strings.Contains(email.To, ctx.UserAccount) {
hasAuth = true
break
}
}
return hasAuth
return ue != nil
}
func DkimGen() string {
+33 -18
View File
@@ -1,35 +1,50 @@
package del_email
import (
log "github.com/sirupsen/logrus"
"pmail/consts"
"pmail/db"
"pmail/models"
"pmail/services/auth"
"pmail/utils/context"
"pmail/utils/errors"
"xorm.io/builder"
)
import . "xorm.io/builder"
func DelEmail(ctx *context.Context, ids []int) error {
var emails []*models.Email
err := db.Instance.Table("email").Where(builder.In("id", ids)).Find(&emails)
if err != nil {
return errors.Wrap(err)
}
for _, email := range emails {
// 检查是否有权限
hasAuth := auth.HasAuth(ctx, email)
if !hasAuth {
return errors.New("No Auth!")
}
email.Status = 3
if len(ids) == 0 {
return nil
}
_, err = db.Instance.Table("email").Where(builder.In("id", ids)).Cols("status").Update(map[string]interface{}{"status": 3})
where, params, err := ToSQL(Eq{"user_id": ctx.UserID}.And(Eq{"email_id": ids}))
if err != nil {
return errors.Wrap(err)
log.Errorf("del email err: %v", err)
return err
}
return nil
_, err = db.Instance.Table(&models.UserEmail{}).Where(where, params...).Update(map[string]interface{}{"status": consts.EmailStatusDel})
if err != nil {
log.Errorf("del email err: %v", err)
}
return err
}
func DelEmailI64(ctx *context.Context, ids []int64) error {
if len(ids) == 0 {
return nil
}
where, params, err := ToSQL(Eq{"user_id": ctx.UserID}.And(Eq{"email_id": ids}))
if err != nil {
log.Errorf("del email err: %v", err)
return err
}
_, err = db.Instance.Table(&models.UserEmail{}).Where(where, params...).Update(map[string]interface{}{"status": consts.EmailStatusDel})
if err != nil {
log.Errorf("del email err: %v", err)
}
return err
}
+21 -6
View File
@@ -7,22 +7,37 @@ import (
log "github.com/sirupsen/logrus"
"pmail/db"
"pmail/dto/parsemail"
"pmail/dto/response"
"pmail/models"
"pmail/utils/context"
"pmail/utils/errors"
"strings"
)
func GetEmailDetail(ctx *context.Context, id int, markRead bool) (*models.Email, error) {
// 获取邮件内容
var email models.Email
_, err := db.Instance.ID(id).Get(&email)
func GetEmailDetail(ctx *context.Context, id int, markRead bool) (*response.EmailResponseData, error) {
// 先查是否是本人的邮件
var ue models.UserEmail
_, err := db.Instance.Where("email_id = ?", id).Get(&ue)
if err != nil {
log.Error(err)
}
if ue.ID == 0 && !ctx.IsAdmin {
return nil, errors.New("Not authorized")
}
//获取邮件内容
var email response.EmailResponseData
_, err = db.Instance.ID(id).Get(&email)
if err != nil {
log.WithContext(ctx).Errorf("SQL error:%+v", err)
return nil, err
}
if markRead && email.IsRead == 0 {
_, err = db.Instance.Exec(db.WithContext(ctx, "update email set is_read =1 where id =?"), email.Id)
email.IsRead = ue.IsRead
if markRead && ue.IsRead == 0 {
ue.IsRead = 1
_, err = db.Instance.Update(&ue)
if err != nil {
log.WithContext(ctx).Errorf("SQL error:%+v", err)
}
+65 -25
View File
@@ -1,49 +1,62 @@
package list
import (
"encoding/json"
"fmt"
log "github.com/sirupsen/logrus"
"pmail/db"
"pmail/dto"
"pmail/models"
"pmail/dto/response"
"pmail/utils/context"
)
func GetEmailList(ctx *context.Context, tag string, keyword string, offset, limit int) (emailList []*models.Email, total int64) {
querySQL, queryParams := genSQL(ctx, tag, keyword)
total, err := db.Instance.Table("email").Where(querySQL, queryParams...).Desc("id").Limit(limit, offset).FindAndCount(&emailList)
if err != nil {
log.Errorf("SQL ERROR: %s ,Error:%s", querySQL, err)
}
return
func GetEmailList(ctx *context.Context, tagInfo dto.SearchTag, keyword string, pop3List bool, offset, limit int) (emailList []*response.EmailResponseData, total int64) {
return getList(ctx, tagInfo, keyword, pop3List, offset, limit)
}
func genSQL(ctx *context.Context, tag, keyword string) (string, []any) {
func getList(ctx *context.Context, tagInfo dto.SearchTag, keyword string, pop3List bool, offset, limit int) (emailList []*response.EmailResponseData, total int64) {
querySQL, queryParams := genSQL(ctx, false, tagInfo, keyword, pop3List, offset, limit)
sql := "1=1 "
err := db.Instance.SQL(querySQL, queryParams...).Find(&emailList)
if err != nil {
log.WithContext(ctx).Errorf("SQL ERROR: %s ,Error:%s", querySQL, err)
}
sqlParams := []any{}
totalSQL, totalParams := genSQL(ctx, true, tagInfo, keyword, pop3List, offset, limit)
var tagInfo dto.SearchTag
_ = json.Unmarshal([]byte(tag), &tagInfo)
_, err = db.Instance.SQL(totalSQL, totalParams...).Get(&total)
if err != nil {
log.WithContext(ctx).Errorf("SQL ERROR: %s ,Error:%s", querySQL, err)
}
return emailList, total
}
func genSQL(ctx *context.Context, count bool, tagInfo dto.SearchTag, keyword string, pop3List bool, offset, limit int) (string, []any) {
sqlParams := []any{ctx.UserID}
sql := "select "
if count {
sql += `count(1) from email e left join user_email ue on e.id=ue.email_id where ue.user_id = ? `
} else if pop3List {
sql += `e.id,e.size from email e left join user_email ue on e.id=ue.email_id where ue.user_id = ? `
} else {
sql += `e.*,ue.is_read from email e left join user_email ue on e.id=ue.email_id where ue.user_id = ? `
}
if tagInfo.Status != -1 {
sql += " and ue.status =? "
sqlParams = append(sqlParams, tagInfo.Status)
} else {
sql += " and ue.status != 3"
}
if tagInfo.Type != -1 {
sql += " and type =? "
sqlParams = append(sqlParams, tagInfo.Type)
}
if tagInfo.Status != -1 {
sql += " and status =? "
sqlParams = append(sqlParams, tagInfo.Status)
} else {
sql += " and status != 3"
}
if tagInfo.GroupId != -1 {
sql += " and group_id=? "
sql += " and ue.group_id=? "
sqlParams = append(sqlParams, tagInfo.GroupId)
}
@@ -52,5 +65,32 @@ func genSQL(ctx *context.Context, tag, keyword string) (string, []any) {
sqlParams = append(sqlParams, "%"+keyword+"%", "%"+keyword+"%")
}
if limit == 0 {
limit = 10
}
sql += " order by e.id desc"
if limit < 10000 {
sql += fmt.Sprintf(" limit %d,%d ", offset, limit)
}
return sql, sqlParams
}
type statRes struct {
Total int64
Size int64
}
// Stat 查询邮件总数和大小
func Stat(ctx *context.Context) (int64, int64) {
sql := `select count(1) as total,sum(size) as size from email e left join user_email ue on e.id=ue.email_id where ue.user_id = ? and e.type = 0 and ue.status != 3`
var ret statRes
_, err := db.Instance.SQL(sql, ctx.UserID).Get(&ret)
if err != nil {
log.WithContext(ctx).Errorf("SQL ERROR: %s ,Error:%s", sql, err)
}
return ret.Total, ret.Size
}
+54
View File
@@ -0,0 +1,54 @@
package list
import (
"pmail/dto"
"pmail/utils/context"
"reflect"
"testing"
)
func Test_genSQL(t *testing.T) {
type args struct {
ctx *context.Context
count bool
tagInfo dto.SearchTag
keyword string
pop3List bool
offset int
limit int
}
tests := []struct {
name string
args args
want string
want1 []any
}{
{
name: "Group搜索",
args: args{
ctx: &context.Context{
UserID: 1,
},
count: false,
tagInfo: dto.SearchTag{-1, -1, 2},
keyword: "",
pop3List: false,
offset: 0,
limit: 0,
},
want: "select e.*,ue.is_read from email e left join user_email ue on e.id=ue.email_id where ue.user_id = ? and ue.status != 3 and ue.group_id=? order by e.id desc limit 0,10 ",
want1: []any{1, 2},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, got1 := genSQL(tt.args.ctx, tt.args.count, tt.args.tagInfo, tt.args.keyword, tt.args.pop3List, tt.args.offset, tt.args.limit)
if got != tt.want {
t.Errorf("genSQL() got = \n%v, want \n%v", got, tt.want)
}
if !reflect.DeepEqual(got1, tt.want1) {
t.Errorf("genSQL() got1 = \n%v, want \n%v", got1, tt.want1)
}
})
}
}
+15 -12
View File
@@ -4,6 +4,7 @@ import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cast"
"pmail/config"
"pmail/consts"
"pmail/db"
"pmail/dto"
"pmail/dto/parsemail"
@@ -14,13 +15,13 @@ import (
"strings"
)
func GetAllRules(ctx *context.Context) []*dto.Rule {
func GetAllRules(ctx *context.Context, userId int) []*dto.Rule {
var res []*models.Rule
var err error
if ctx == nil || ctx.UserID == 0 {
err = db.Instance.Decr("sort").Find(&res)
if userId == 0 {
return nil
} else {
err = db.Instance.Where("user_id=?", ctx.UserID).Decr("sort").Find(&res)
err = db.Instance.Where("user_id=?", userId).Decr("sort").Find(&res)
}
if err != nil {
@@ -64,14 +65,16 @@ func DoRule(ctx *context.Context, rule *dto.Rule, email *parsemail.Email) {
switch rule.Action {
case dto.READ:
email.IsRead = 1
if email.MessageId > 0 {
db.Instance.Exec(db.WithContext(ctx, "update email set is_read=1 where id =?"), email.MessageId)
_, err := db.Instance.Table(&models.UserEmail{}).Where("email_id=? and user_id=?", email.MessageId, rule.UserId).Cols("is_read").Update(map[string]interface{}{"is_read": 1})
if err != nil {
log.WithContext(ctx).Errorf("sqlERror :%v", err)
}
}
case dto.DELETE:
email.Status = 3
if email.MessageId > 0 {
db.Instance.Exec(db.WithContext(ctx, "update email set status=3 where id =?"), email.MessageId)
_, err := db.Instance.Table(&models.UserEmail{}).Where("email_id=? and user_id=?", email.MessageId, rule.UserId).Cols("status").Update(map[string]interface{}{"status": consts.EmailStatusDel})
if err != nil {
log.WithContext(ctx).Errorf("sqlERror :%v", err)
}
case dto.FORWARD:
if strings.Contains(rule.Params, config.Instance.Domain) {
@@ -83,9 +86,9 @@ func DoRule(ctx *context.Context, rule *dto.Rule, email *parsemail.Email) {
log.WithContext(ctx).Errorf("Forward Error:%v", err)
}
case dto.MOVE:
email.GroupId = cast.ToInt(rule.Params)
if email.MessageId > 0 {
db.Instance.Exec(db.WithContext(ctx, "update email set group_id=? where id =?"), email.GroupId, email.MessageId)
_, err := db.Instance.Table(&models.UserEmail{}).Where("email_id=? and user_id=?", email.MessageId, rule.UserId).Cols("group_id").Update(map[string]interface{}{"group_id": cast.ToInt(rule.Params)})
if err != nil {
log.WithContext(ctx).Errorf("sqlERror :%v", err)
}
}
+3 -10
View File
@@ -43,18 +43,11 @@ func GetAdminPassword(ctx *context.Context) (string, error) {
func SetAdminPassword(ctx *context.Context, account, pwd string) error {
encodePwd := password.Encode(pwd)
res, err := db.Instance.Exec(db.WithContext(ctx, "INSERT INTO user (account, name, password) VALUES (?, 'admin',?)"), account, encodePwd)
if err != nil {
return errors.Wrap(err)
}
id, err := res.LastInsertId()
if err != nil {
return errors.Wrap(err)
}
_, err = db.Instance.Exec(db.WithContext(ctx, "INSERT INTO user_auth (user_id, email_account) VALUES (?, '*')"), id)
_, err := db.Instance.Exec(db.WithContext(ctx, "INSERT INTO user (account, name, password,is_admin) VALUES (?, 'admin',?,1)"), account, encodePwd)
if err != nil {
return errors.Wrap(err)
}
return nil
}
@@ -81,7 +74,7 @@ func SetDatabaseSettings(ctx *context.Context, dbType, dbDSN string) error {
}
config.Init()
// 检查数据库是否能正确连接
err = db.Init()
err = db.Init("")
if err != nil {
return errors.Wrap(err)
}
+3 -3
View File
@@ -26,9 +26,9 @@ func GetDNSSettings(ctx *context.Context) ([]*DNSItem, error) {
ret := []*DNSItem{
{Type: "A", Host: "smtp", Value: ip.GetIp(), TTL: 3600, Tips: i18n.GetText(ctx.Lang, "ip_taps")},
{Type: "A", Host: "pop", Value: ip.GetIp(), TTL: 3600, Tips: i18n.GetText(ctx.Lang, "ip_taps")},
{Type: "A", Host: "-", Value: ip.GetIp(), TTL: 3600, Tips: i18n.GetText(ctx.Lang, "ip_taps")},
{Type: "MX", Host: "-", Value: fmt.Sprintf("smtp.%s", configData.Domain), TTL: 3600},
{Type: "TXT", Host: "-", Value: "v=spf1 a mx ~all", TTL: 3600},
{Type: "A", Host: "", Value: ip.GetIp(), TTL: 3600, Tips: i18n.GetText(ctx.Lang, "ip_taps")},
{Type: "MX", Host: "", Value: fmt.Sprintf("smtp.%s", configData.Domain), TTL: 3600},
{Type: "TXT", Host: "", Value: "v=spf1 a mx ~all", TTL: 3600},
{Type: "TXT", Host: "default._domainkey", Value: auth.DkimGen(), TTL: 3600},
}
return ret, nil
+1 -2
View File
@@ -2,12 +2,11 @@ package setup
import (
"pmail/signal"
"pmail/utils/context"
"pmail/utils/errors"
)
// Finish 标记初始化完成
func Finish(ctx *context.Context) error {
func Finish() error {
cfg, err := ReadConfig()
if err != nil {
return errors.Wrap(err)
+67
View File
@@ -0,0 +1,67 @@
package ssl
import (
"github.com/go-acme/lego/v4/providers/dns"
"os"
"pmail/utils/errors"
"regexp"
"strings"
)
func GetServerParamsList(serverName string) ([]string, error) {
var serverParams []string
infos, err := os.ReadDir("./")
if err != nil {
return nil, errors.Wrap(err)
}
upperServerName := strings.ToUpper(serverName)
for _, info := range infos {
if strings.HasPrefix(info.Name(), upperServerName) {
serverParams = append(serverParams, info.Name())
}
}
if len(serverParams) != 0 {
return serverParams, nil
}
_, err = dns.NewDNSChallengeProviderByName(serverName)
if err == nil {
return nil, errors.New(serverName + " Not Support")
}
if strings.Contains(err.Error(), "unrecognized DNS provider") {
return nil, err
}
re := regexp.MustCompile(`missing: (.+)`)
// namesilo: some credentials information are missing: NAMESILO_API_KEY
estr := err.Error()
name := re.FindStringSubmatch(estr)
if len(name) == 2 {
names := strings.Split(name[1], ",")
for _, s := range names {
serverParams = append(serverParams, s)
SetDomainServerParams(s, "empty")
}
}
_, err = dns.NewDNSChallengeProviderByName(serverName)
return serverParams, err
}
func SetDomainServerParams(name, value string) {
key := name
err := os.WriteFile(key, []byte(value), 0644)
if err != nil {
panic(err)
}
err = os.Setenv(name+"_FILE", key)
if err != nil {
panic(err)
}
}
@@ -0,0 +1,36 @@
package ssl
import (
"reflect"
"testing"
)
func TestGetServerParamsList(t *testing.T) {
type args struct {
serverName string
}
tests := []struct {
name string
args args
want []string
wantErr bool
}{
{name: "namesilo", args: args{serverName: "namesilo"}, want: []string{"NAMESILO_API_KEY"}, wantErr: false},
{name: "namesiloAgain", args: args{serverName: "namesilo"}, want: []string{"NAMESILO_API_KEY"}, wantErr: false},
{name: "auroradns", args: args{serverName: "auroradns"}, want: []string{"AURORA_API_KEY", "AURORA_SECRET"}, wantErr: false},
{name: "alidns", args: args{serverName: "alidns"}, want: []string{"ALICLOUD_ACCESS_KEY", "ALICLOUD_SECRET_KEY"}, wantErr: false},
{name: "null", args: args{serverName: "null"}, want: nil, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := GetServerParamsList(tt.args.serverName)
if (err != nil) != tt.wantErr {
t.Errorf("GetServerParamsList() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("GetServerParamsList() got = %v, want %v", got, tt.want)
}
})
}
}
+55 -26
View File
@@ -8,13 +8,17 @@ import (
"crypto/tls"
"crypto/x509"
"github.com/go-acme/lego/v4/certificate"
"github.com/go-acme/lego/v4/challenge/dns01"
"github.com/go-acme/lego/v4/providers/dns"
log "github.com/sirupsen/logrus"
"github.com/spf13/cast"
"os"
"pmail/config"
"pmail/services/setup"
"pmail/signal"
"pmail/utils/async"
"pmail/utils/errors"
"strings"
"time"
"github.com/go-acme/lego/v4/certcrypto"
@@ -44,19 +48,20 @@ func GetSSL() string {
panic(err)
}
if cfg.SSLType == "" {
return config.SSLTypeAuto
return config.SSLTypeAutoHTTP
}
return cfg.SSLType
}
func SetSSL(sslType, priKey, crtKey string) error {
func SetSSL(sslType, priKey, crtKey, serviceName string) error {
cfg, err := setup.ReadConfig()
if err != nil {
panic(err)
}
if sslType == config.SSLTypeAuto || sslType == config.SSLTypeUser {
if sslType == config.SSLTypeAutoHTTP || sslType == config.SSLTypeUser || sslType == config.SSLTypeAutoDNS {
cfg.SSLType = sslType
cfg.DomainServiceName = serviceName
} else {
return errors.New("SSL Type Error!")
}
@@ -101,19 +106,34 @@ func GenSSL(update bool) error {
key: privateKey,
}
config := lego.NewConfig(&myUser)
config.Certificate.KeyType = certcrypto.RSA2048
conf := lego.NewConfig(&myUser)
conf.UserAgent = "PMail"
conf.Certificate.KeyType = certcrypto.RSA2048
// A client facilitates communication with the CA server.
client, err := lego.NewClient(config)
client, err := lego.NewClient(conf)
if err != nil {
return errors.Wrap(err)
}
err = client.Challenge.SetHTTP01Provider(GetHttpChallengeInstance())
if err != nil {
return errors.Wrap(err)
if cfg.SSLType == "0" {
err = client.Challenge.SetHTTP01Provider(GetHttpChallengeInstance())
if err != nil {
return errors.Wrap(err)
}
} else if cfg.SSLType == "2" {
err = os.Setenv(strings.ToUpper(cfg.DomainServiceName)+"_PROPAGATION_TIMEOUT", "900")
if err != nil {
log.Errorf("Set ENV Variable Error: %s", err.Error())
}
dnspodProvider, err := dns.NewDNSChallengeProviderByName(cfg.DomainServiceName)
if err != nil {
return errors.Wrap(err)
}
err = client.Challenge.SetDNS01Provider(dnspodProvider, dns01.AddDNSTimeout(15*time.Minute))
if err != nil {
return errors.Wrap(err)
}
}
reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
@@ -126,25 +146,34 @@ func GenSSL(update bool) error {
Domains: []string{"smtp." + cfg.Domain, cfg.WebDomain, "pop." + cfg.Domain},
Bundle: true,
}
certificates, err := client.Certificate.Obtain(request)
if err != nil {
return errors.Wrap(err)
}
err = os.WriteFile("./config/ssl/private.key", certificates.PrivateKey, 0666)
if err != nil {
return errors.Wrap(err)
}
as := async.New(nil)
err = os.WriteFile("./config/ssl/public.crt", certificates.Certificate, 0666)
if err != nil {
return errors.Wrap(err)
}
as.Process(func(params any) {
log.Infof("wait ssl")
certificates, err := client.Certificate.Obtain(request)
if err != nil {
panic(err)
}
err = os.WriteFile("./config/ssl/issuerCert.crt", certificates.IssuerCertificate, 0666)
if err != nil {
return errors.Wrap(err)
}
err = os.WriteFile("./config/ssl/private.key", certificates.PrivateKey, 0666)
if err != nil {
panic(err)
}
err = os.WriteFile("./config/ssl/public.crt", certificates.Certificate, 0666)
if err != nil {
panic(err)
}
err = os.WriteFile("./config/ssl/issuerCert.crt", certificates.IssuerCertificate, 0666)
if err != nil {
panic(err)
}
setup.Finish()
}, nil)
return nil
}