This commit is contained in:
jinnrry committed 2023-08-06 09:33:51 +08:00
1 parent 8f7fbd4fee
commit c0f12558b5
54 files changed
+1273 -132

No files matched your search

+3 -3
View File
@@ -3,10 +3,10 @@ package attachments
import (
"encoding/json"
log "github.com/sirupsen/logrus"
"pmail/db"
"pmail/dto"
"pmail/dto/parsemail"
"pmail/models"
"pmail/mysql"
"pmail/services/auth"
)
@@ -14,7 +14,7 @@ func GetAttachments(ctx *dto.Context, emailId int, cid string) (string, []byte)
// 获取邮件内容
var email models.Email
err := mysql.Instance.Get(&email, mysql.WithContext(ctx, "select * from email where id = ?"), emailId)
err := db.Instance.Get(&email, db.WithContext(ctx, "select * from email where id = ?"), emailId)
if err != nil {
log.WithContext(ctx).Errorf("SQL error:%+v", err)
return "", nil
@@ -39,7 +39,7 @@ func GetAttachmentsByIndex(ctx *dto.Context, emailId int, index int) (string, []
// 获取邮件内容
var email models.Email
err := mysql.Instance.Get(&email, mysql.WithContext(ctx, "select * from email where id = ?"), emailId)
err := db.Instance.Get(&email, db.WithContext(ctx, "select * from email where id = ?"), emailId)
if err != nil {
log.WithContext(ctx).Errorf("SQL error:%+v", err)
return "", nil
+80 -2
View File
@@ -1,10 +1,17 @@
package auth
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
log "github.com/sirupsen/logrus"
"os"
"pmail/db"
"pmail/dto"
"pmail/models"
"pmail/mysql"
"strings"
)
@@ -12,7 +19,7 @@ import (
func HasAuth(ctx *dto.Context, email *models.Email) bool {
// 获取当前用户的auth
var auth []models.UserAuth
err := mysql.Instance.Select(&auth, mysql.WithContext(ctx, "select * from user_auth where user_id = ?"), ctx.UserInfo.ID)
err := db.Instance.Select(&auth, db.WithContext(ctx, "select * from user_auth where user_id = ?"), ctx.UserInfo.ID)
if err != nil {
log.WithContext(ctx).Errorf("SQL error:%+v", err)
return false
@@ -31,3 +38,74 @@ func HasAuth(ctx *dto.Context, email *models.Email) bool {
return hasAuth
}
func DkimGen() string {
privKeyStr, _ := os.ReadFile("./config/dkim/dkim.priv")
publicKeyStr, _ := os.ReadFile("./config/dkim/dkim.public")
if len(privKeyStr) > 0 && len(publicKeyStr) > 0 {
return string(publicKeyStr)
}
var (
privKey crypto.Signer
err error
)
privKey, err = rsa.GenerateKey(rand.Reader, 3072)
if err != nil {
log.Fatalf("Failed to generate key: %v", err)
}
privBytes, err := x509.MarshalPKCS8PrivateKey(privKey)
if err != nil {
log.Fatalf("Failed to marshal private key: %v", err)
}
f, err := os.OpenFile("./config/dkim/dkim.priv", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Failed to create key file: %v", err)
}
defer f.Close()
privBlock := pem.Block{
Type: "PRIVATE KEY",
Bytes: privBytes,
}
if err := pem.Encode(f, &privBlock); err != nil {
log.Fatalf("Failed to write key PEM block: %v", err)
}
if err := f.Close(); err != nil {
log.Fatalf("Failed to close key file: %v", err)
}
var pubBytes []byte
switch pubKey := privKey.Public().(type) {
case *rsa.PublicKey:
// RFC 6376 is inconsistent about whether RSA public keys should
// be formatted as RSAPublicKey or SubjectPublicKeyInfo.
// Erratum 3017 (https://www.rfc-editor.org/errata/eid3017)
// proposes allowing both. We use SubjectPublicKeyInfo for
// consistency with other implementations including opendkim,
// Gmail, and Fastmail.
pubBytes, err = x509.MarshalPKIXPublicKey(pubKey)
if err != nil {
log.Fatalf("Failed to marshal public key: %v", err)
}
default:
panic("unreachable")
}
params := []string{
"v=DKIM1",
"k=rsa",
"p=" + base64.StdEncoding.EncodeToString(pubBytes),
}
publicKey := strings.Join(params, "; ")
os.WriteFile("./config/dkim/dkim.public", []byte(publicKey), 0666)
return publicKey
}
+3 -3
View File
@@ -5,24 +5,24 @@ import (
"encoding/json"
"fmt"
log "github.com/sirupsen/logrus"
"pmail/db"
"pmail/dto"
"pmail/dto/parsemail"
"pmail/models"
"pmail/mysql"
"strings"
)
func GetEmailDetail(ctx *dto.Context, id int, markRead bool) (*models.Email, error) {
// 获取邮件内容
var email models.Email
err := mysql.Instance.Get(&email, mysql.WithContext(ctx, "select * from email where id = ?"), id)
err := db.Instance.Get(&email, db.WithContext(ctx, "select * from email where id = ?"), id)
if err != nil {
log.WithContext(ctx).Errorf("SQL error:%+v", err)
return nil, err
}
if markRead && email.IsRead == 0 {
_, err = mysql.Instance.Exec(mysql.WithContext(ctx, "update email set is_read =1 where id =?"), email.Id)
_, err = db.Instance.Exec(db.WithContext(ctx, "update email set is_read =1 where id =?"), email.Id)
if err != nil {
log.WithContext(ctx).Errorf("SQL error:%+v", err)
}
+3 -3
View File
@@ -3,9 +3,9 @@ package list
import (
"encoding/json"
log "github.com/sirupsen/logrus"
"pmail/db"
"pmail/dto"
"pmail/models"
"pmail/mysql"
)
func GetEmailList(ctx *dto.Context, tag string, keyword string, offset, limit int) (emailList []*models.Email, total int) {
@@ -13,12 +13,12 @@ func GetEmailList(ctx *dto.Context, tag string, keyword string, offset, limit in
querySQL, queryParams := genSQL(ctx, false, tag, keyword, offset, limit)
counterSQL, counterParams := genSQL(ctx, true, tag, keyword, offset, limit)
err := mysql.Instance.Select(&emailList, querySQL, queryParams...)
err := db.Instance.Select(&emailList, querySQL, queryParams...)
if err != nil {
log.Errorf("SQL ERROR: %s ,Error:%s", querySQL, err)
}
err = mysql.Instance.Get(&total, counterSQL, counterParams...)
err = db.Instance.Get(&total, counterSQL, counterParams...)
if err != nil {
log.Errorf("SQL ERROR: %s ,Error:%s", querySQL, err)
}
+76
View File
@@ -0,0 +1,76 @@
package setup
import (
"encoding/json"
"os"
"pmail/config"
"pmail/utils/array"
"pmail/utils/errors"
"pmail/utils/file"
)
func GetDatabaseSettings() (string, string, error) {
configData, err := readConfig()
if err != nil {
return "", "", errors.Wrap(err)
}
return configData.DbType, configData.DbDSN, nil
}
func SetDatabaseSettings(dbType, dbDSN string) error {
configData, err := readConfig()
if err != nil {
return errors.Wrap(err)
}
if !array.InArray(dbType, config.DBTypes) {
return errors.New("dbtype error")
}
configData.DbType = dbType
configData.DbDSN = dbDSN
// 检查数据库是否能正确连接 todo
err = writeConfig(configData)
if err != nil {
return errors.Wrap(err)
}
return nil
}
func writeConfig(cfg *config.Config) error {
bytes, _ := json.Marshal(cfg)
err := os.WriteFile("./config/config.json", bytes, 0666)
if err != nil {
return errors.Wrap(err)
}
return nil
}
func readConfig() (*config.Config, error) {
configData := config.Config{
DkimPrivateKeyPath: "config/dkim/dkim.priv",
SSLPrivateKeyPath: "config/ssl/private.key",
SSLPublicKeyPath: "config/ssl/public.crt",
}
if !file.PathExist("./config/config.json") {
bytes, _ := json.Marshal(configData)
err := os.WriteFile("./config/config.json", bytes, 0666)
if err != nil {
return nil, errors.Wrap(err)
}
} else {
cfgData, err := os.ReadFile("./config/config.json")
if err != nil {
return nil, errors.Wrap(err)
}
err = json.Unmarshal(cfgData, &configData)
if err != nil {
return nil, errors.Wrap(err)
}
}
return &configData, nil
}
+54
View File
@@ -0,0 +1,54 @@
package setup
import (
"encoding/json"
"fmt"
"io"
"net/http"
"pmail/dto"
"pmail/i18n"
"pmail/services/auth"
"pmail/utils/errors"
)
type DNSItem struct {
Type string `json:"type"`
Host string `json:"host"`
Value string `json:"value"`
TTL int `json:"ttl"`
Tips string `json:"tips"`
}
func GetDNSSettings(ctx *dto.Context) ([]*DNSItem, error) {
configData, err := readConfig()
if err != nil {
return nil, errors.Wrap(err)
}
ret := []*DNSItem{
{Type: "A", Host: "smtp", Value: 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
}
func getIp() string {
resp, err := http.Get("http://ip-api.com/json/?lang=zh-CN ")
if err != nil {
return "Your Server IP"
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
body, err := io.ReadAll(resp.Body)
if err == nil {
var queryRes map[string]string
_ = json.Unmarshal(body, &queryRes)
return queryRes["query"]
}
}
return "Your Server IP"
}
+7
View File
@@ -0,0 +1,7 @@
package setup
import "testing"
func TestGetIp(t *testing.T) {
GetIp()
}
+32
View File
@@ -0,0 +1,32 @@
package setup
import (
"pmail/utils/errors"
)
func GetDomainSettings() (string, string, error) {
configData, err := readConfig()
if err != nil {
return "", "", errors.Wrap(err)
}
return configData.Domain, configData.WebDomain, nil
}
func SetDomainSettings(smtpDomain, webDomain string) error {
configData, err := readConfig()
if err != nil {
return errors.Wrap(err)
}
configData.Domain = smtpDomain
configData.WebDomain = webDomain
// 检查域名是否指向本机 todo
err = writeConfig(configData)
if err != nil {
return errors.Wrap(err)
}
return nil
}
+103
View File
@@ -0,0 +1,103 @@
package setup
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
log "github.com/sirupsen/logrus"
"pmail/utils/errors"
"github.com/go-acme/lego/v4/certcrypto"
"github.com/go-acme/lego/v4/certificate"
"github.com/go-acme/lego/v4/challenge/http01"
"github.com/go-acme/lego/v4/challenge/tlsalpn01"
"github.com/go-acme/lego/v4/lego"
"github.com/go-acme/lego/v4/registration"
)
type MyUser struct {
Email string
Registration *registration.Resource
key crypto.PrivateKey
}
func (u *MyUser) GetEmail() string {
return u.Email
}
func (u MyUser) GetRegistration() *registration.Resource {
return u.Registration
}
func (u *MyUser) GetPrivateKey() crypto.PrivateKey {
return u.key
}
func GenSSL() error {
configData, err := readConfig()
if err != nil {
return errors.Wrap(err)
}
// Create a user. New accounts need an email and private key to start.
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
log.Fatal(err)
}
myUser := MyUser{
Email: "i@" + configData.Domain,
key: privateKey,
}
config := lego.NewConfig(&myUser)
config.Certificate.KeyType = certcrypto.RSA2048
// A client facilitates communication with the CA server.
client, err := lego.NewClient(config)
if err != nil {
log.Fatal(err)
}
// We specify an HTTP port of 5002 and an TLS port of 5001 on all interfaces
// because we aren't running as root and can't bind a listener to port 80 and 443
// (used later when we attempt to pass challenges). Keep in mind that you still
// need to proxy challenge traffic to port 5002 and 5001.
err = client.Challenge.SetHTTP01Provider(http01.NewProviderServer("", "5001"))
if err != nil {
log.Fatal(err)
}
err = client.Challenge.SetTLSALPN01Provider(tlsalpn01.NewProviderServer("", "443"))
if err != nil {
log.Fatal(err)
}
// New users will need to register
reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
if err != nil {
log.Fatal(err)
}
myUser.Registration = reg
request := certificate.ObtainRequest{
Domains: []string{
fmt.Sprintf("smtp.%s", configData.Domain),
configData.WebDomain,
},
Bundle: true,
}
certificates, err := client.Certificate.Obtain(request)
if err != nil {
log.Fatal(err)
}
// Each certificate comes back with the cert bytes, the bytes of the client's
// private key, and a certificate URL. SAVE THESE TO DISK.
fmt.Printf("%#v\n", certificates)
// ... all done.
return nil
}