This commit is contained in:
1 parent
b65fb4ec6c
commit
492f2f6322
17 files changed
+615
-25
No files matched your search
@@ -0,0 +1,158 @@
|
||||
package email
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/db"
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/utils/context"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
type deleteContactRequest struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
type trustSenderRequest struct {
|
||||
Email string `json:"email"`
|
||||
Trusted bool `json:"trusted"`
|
||||
}
|
||||
|
||||
// ContactsList 查询当前用户的历史写信收件人列表(多租户严格隔离)
|
||||
func ContactsList(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
var contacts []models.UserContact
|
||||
err := db.Instance.Table(&models.UserContact{}).
|
||||
Where("user_id = ?", ctx.UserID).
|
||||
OrderBy("last_used_at DESC").
|
||||
Limit(100).
|
||||
Find(&contacts)
|
||||
if err != nil {
|
||||
log.WithContext(ctx).WithError(err).Error("query user contacts failed")
|
||||
response.NewErrorResponse(response.ServerError, "获取联系人失败", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
|
||||
response.NewSuccessResponse(contacts).FPrint(w)
|
||||
}
|
||||
|
||||
// DeleteContact 删除当前用户的某项历史联系人记录
|
||||
func DeleteContact(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
var reqData deleteContactRequest
|
||||
if err := json.NewDecoder(req.Body).Decode(&reqData); err != nil {
|
||||
response.NewErrorResponse(response.ParamsError, "参数错误", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
email := strings.ToLower(strings.TrimSpace(reqData.Email))
|
||||
if email == "" {
|
||||
response.NewErrorResponse(response.ParamsError, "联系人邮箱不能为空", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
|
||||
_, err := db.Instance.Table(&models.UserContact{}).
|
||||
Where("user_id = ? AND LOWER(email) = ?", ctx.UserID, email).
|
||||
Delete(&models.UserContact{})
|
||||
if err != nil {
|
||||
log.WithContext(ctx).WithError(err).Error("delete user contact failed")
|
||||
response.NewErrorResponse(response.ServerError, "删除联系人失败", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
|
||||
response.NewSuccessResponse("ok").FPrint(w)
|
||||
}
|
||||
|
||||
// TrustSender 将发件人添加至信任白名单,或从中移除
|
||||
func TrustSender(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
var reqData trustSenderRequest
|
||||
if err := json.NewDecoder(req.Body).Decode(&reqData); err != nil {
|
||||
response.NewErrorResponse(response.ParamsError, "参数错误", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
email := strings.ToLower(strings.TrimSpace(reqData.Email))
|
||||
if email == "" {
|
||||
response.NewErrorResponse(response.ParamsError, "发件人邮箱不能为空", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
|
||||
if reqData.Trusted {
|
||||
var exists bool
|
||||
has, err := db.Instance.Table(&models.UserTrustedSender{}).
|
||||
Where("user_id = ? AND LOWER(email) = ?", ctx.UserID, email).
|
||||
Exist(&models.UserTrustedSender{})
|
||||
if err != nil {
|
||||
log.WithContext(ctx).WithError(err).Error("check trusted sender failed")
|
||||
response.NewErrorResponse(response.ServerError, "操作失败", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
exists = has
|
||||
if !exists {
|
||||
item := models.UserTrustedSender{
|
||||
UserID: ctx.UserID,
|
||||
Email: email,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
if _, err := db.Instance.Insert(&item); err != nil {
|
||||
log.WithContext(ctx).WithError(err).Error("insert trusted sender failed")
|
||||
response.NewErrorResponse(response.ServerError, "添加信任发件人失败", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if _, err := db.Instance.Table(&models.UserTrustedSender{}).
|
||||
Where("user_id = ? AND LOWER(email) = ?", ctx.UserID, email).
|
||||
Delete(&models.UserTrustedSender{}); err != nil {
|
||||
log.WithContext(ctx).WithError(err).Error("remove trusted sender failed")
|
||||
response.NewErrorResponse(response.ServerError, "取消信任发件人失败", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
response.NewSuccessResponse("ok").FPrint(w)
|
||||
}
|
||||
|
||||
// RecordUserContacts 异步批量记录发件成功后的收件人地址
|
||||
func RecordUserContacts(userID int, recipients []models.UserContact) {
|
||||
if userID <= 0 || len(recipients) == 0 {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
_ = db.Transaction(db.Instance, func(session *xorm.Session) error {
|
||||
for _, r := range recipients {
|
||||
email := strings.ToLower(strings.TrimSpace(r.Email))
|
||||
if email == "" {
|
||||
continue
|
||||
}
|
||||
var existing models.UserContact
|
||||
has, err := session.Table(&models.UserContact{}).
|
||||
Where("user_id = ? AND LOWER(email) = ?", userID, email).
|
||||
Get(&existing)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if has {
|
||||
existing.LastUsedAt = now
|
||||
if r.Name != "" {
|
||||
existing.Name = r.Name
|
||||
}
|
||||
if _, err := session.ID(existing.ID).Cols("name", "last_used_at").Update(&existing); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
item := models.UserContact{
|
||||
UserID: userID,
|
||||
Email: email,
|
||||
Name: r.Name,
|
||||
LastUsedAt: now,
|
||||
}
|
||||
if _, err := session.Insert(&item); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package email
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/db"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/utils/context"
|
||||
_ "modernc.org/sqlite"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
func setupContactsTestDB(t *testing.T) {
|
||||
engine, err := xorm.NewEngine("sqlite", ":memory:")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := engine.Sync2(&models.UserContact{}, &models.UserTrustedSender{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.Instance = engine
|
||||
}
|
||||
|
||||
func TestContactsListAndTenantIsolation(t *testing.T) {
|
||||
setupContactsTestDB(t)
|
||||
|
||||
// User 1 联系人
|
||||
_, _ = db.Instance.Insert(&models.UserContact{
|
||||
UserID: 1,
|
||||
Email: "user1_friend@example.com",
|
||||
Name: "Friend One",
|
||||
LastUsedAt: time.Now(),
|
||||
})
|
||||
// User 2 联系人(隔离测试)
|
||||
_, _ = db.Instance.Insert(&models.UserContact{
|
||||
UserID: 2,
|
||||
Email: "user2_secret@example.com",
|
||||
Name: "Friend Two",
|
||||
LastUsedAt: time.Now(),
|
||||
})
|
||||
|
||||
// 测试 User 1 查询联系人,只能看到自己的
|
||||
ctxUser1 := &context.Context{UserID: 1}
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/email/contacts", nil)
|
||||
w := httptest.NewRecorder()
|
||||
ContactsList(ctxUser1, w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
var resp struct {
|
||||
Code int `json:"code"`
|
||||
Data []models.UserContact `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(resp.Data) != 1 {
|
||||
t.Fatalf("expected 1 contact for user 1, got %d", len(resp.Data))
|
||||
}
|
||||
if resp.Data[0].Email != "user1_friend@example.com" {
|
||||
t.Fatalf("expected user1_friend@example.com, got %s", resp.Data[0].Email)
|
||||
}
|
||||
|
||||
// 测试删除联系人
|
||||
delReqBody, _ := json.Marshal(deleteContactRequest{Email: "user1_friend@example.com"})
|
||||
delReq := httptest.NewRequest(http.MethodPost, "/api/v1/email/contacts/delete", bytes.NewReader(delReqBody))
|
||||
delW := httptest.NewRecorder()
|
||||
DeleteContact(ctxUser1, delW, delReq)
|
||||
|
||||
if delW.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", delW.Code)
|
||||
}
|
||||
|
||||
// 再次查询应该为空
|
||||
w2 := httptest.NewRecorder()
|
||||
ContactsList(ctxUser1, w2, req)
|
||||
var resp2 struct {
|
||||
Code int `json:"code"`
|
||||
Data []models.UserContact `json:"data"`
|
||||
}
|
||||
_ = json.Unmarshal(w2.Body.Bytes(), &resp2)
|
||||
if len(resp2.Data) != 0 {
|
||||
t.Fatalf("expected 0 contacts after delete, got %d", len(resp2.Data))
|
||||
}
|
||||
|
||||
// 确认 User 2 的联系人未受影响
|
||||
var u2Count int
|
||||
has, err := db.Instance.Table(&models.UserContact{}).Where("user_id = 2").Count(&models.UserContact{})
|
||||
if err != nil || has != 1 {
|
||||
t.Fatalf("user 2 contact was corrupted: count=%d, err=%v", u2Count, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrustSenderToggle(t *testing.T) {
|
||||
setupContactsTestDB(t)
|
||||
ctx := &context.Context{UserID: 1}
|
||||
|
||||
// 添加信任
|
||||
body, _ := json.Marshal(trustSenderRequest{Email: "trusted@example.com", Trusted: true})
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/email/trust-sender", bytes.NewReader(body))
|
||||
w := httptest.NewRecorder()
|
||||
TrustSender(ctx, w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
has, err := db.Instance.Table(&models.UserTrustedSender{}).Where("user_id = ? AND email = ?", 1, "trusted@example.com").Exist(&models.UserTrustedSender{})
|
||||
if err != nil || !has {
|
||||
t.Fatalf("expected trusted sender to exist")
|
||||
}
|
||||
|
||||
// 取消信任
|
||||
body2, _ := json.Marshal(trustSenderRequest{Email: "trusted@example.com", Trusted: false})
|
||||
req2 := httptest.NewRequest(http.MethodPost, "/api/v1/email/trust-sender", bytes.NewReader(body2))
|
||||
w2 := httptest.NewRecorder()
|
||||
TrustSender(ctx, w2, req2)
|
||||
|
||||
if w2.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w2.Code)
|
||||
}
|
||||
|
||||
hasAfter, _ := db.Instance.Table(&models.UserTrustedSender{}).Where("user_id = ? AND email = ?", 1, "trusted@example.com").Exist(&models.UserTrustedSender{})
|
||||
if hasAfter {
|
||||
t.Fatalf("expected trusted sender to be removed")
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/dto"
|
||||
"git.pcux.cn/xuans/Smail/dto/parsemail"
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/db"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/list"
|
||||
"git.pcux.cn/xuans/Smail/utils/context"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -79,6 +81,14 @@ func EmailList(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
response.NewErrorResponse(response.ServerError, "读取邮件列表失败", "").FPrint(w)
|
||||
return
|
||||
}
|
||||
trustedMap := make(map[string]bool)
|
||||
var trustedSenders []models.UserTrustedSender
|
||||
if err := db.Instance.Table(&models.UserTrustedSender{}).Where("user_id = ?", ctx.UserID).Find(&trustedSenders); err == nil {
|
||||
for _, item := range trustedSenders {
|
||||
trustedMap[strings.ToLower(strings.TrimSpace(item.Email))] = true
|
||||
}
|
||||
}
|
||||
|
||||
items := make([]*emilItem, 0, len(emailList))
|
||||
for _, email := range emailList {
|
||||
var sender User
|
||||
@@ -99,6 +109,10 @@ func EmailList(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
return
|
||||
}
|
||||
authentication := parsemail.NewEmailAuthentication(email.SPFCheck == 1, email.DKIMCheck == 1)
|
||||
dangerous := authentication.Dangerous
|
||||
if trustedMap[strings.ToLower(strings.TrimSpace(sender.EmailAddress))] {
|
||||
dangerous = false
|
||||
}
|
||||
items = append(items, &emilItem{
|
||||
ID: email.Id,
|
||||
Title: email.Subject,
|
||||
@@ -107,7 +121,7 @@ func EmailList(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
IsRead: email.IsRead == 1,
|
||||
Sender: sender,
|
||||
To: recipients,
|
||||
Dangerous: authentication.Dangerous,
|
||||
Dangerous: dangerous,
|
||||
Error: email.Error.String,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -282,6 +282,18 @@ func Send(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// ??????????????????
|
||||
var contactList []models.UserContact
|
||||
for _, recipient := range append(append(e.To, e.Cc...), e.Bcc...) {
|
||||
if recipient != nil && recipient.EmailAddress != "" {
|
||||
contactList = append(contactList, models.UserContact{
|
||||
Email: recipient.EmailAddress,
|
||||
Name: recipient.Name,
|
||||
})
|
||||
}
|
||||
}
|
||||
RecordUserContacts(ctx.UserID, contactList)
|
||||
|
||||
e.MessageId = cast.ToInt64(modelEmail.Id)
|
||||
e.MsgID = modelEmail.MsgID
|
||||
|
||||
|
||||
Reference in new issue
Block a user