Compare commits
11
Commits
v2.14.0
...
09fa1d3133
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
09fa1d3133 | ||
|
|
343d038ee3 | ||
|
|
875b83fa2a | ||
|
|
dabed6e4f5 | ||
|
|
492f2f6322 | ||
|
|
b65fb4ec6c | ||
|
|
def5b40d13 | ||
|
|
5672614430 | ||
|
|
12475f5565 | ||
|
|
aec0d23ac0 | ||
|
|
3ea935d3c4 |
No files matched your search
@@ -84,6 +84,7 @@ type legacyMigrationConfig struct {
|
||||
LoginPolicy string `json:"loginPolicy"`
|
||||
VerificationLoginPolicy string `json:"verificationLoginPolicy"`
|
||||
PluginAllowList []string `json:"pluginAllowList"`
|
||||
SSL SSLConfig `json:"ssl"`
|
||||
}
|
||||
|
||||
var legacyMigrationKnownFields = map[string]struct{}{
|
||||
@@ -94,7 +95,7 @@ var legacyMigrationKnownFields = map[string]struct{}{
|
||||
"tgBotToken": {}, "tgChatId": {}, "isInit": {}, "setupState": {}, "webPushUrl": {}, "webPushToken": {},
|
||||
"smtpHost": {}, "smtpPort": {}, "smtpUsername": {}, "smtpPassword": {}, "smtpSecurity": {}, "smtpFrom": {},
|
||||
"smtpFromDomain": {}, "verificationEnabled": {}, "externalRecoveryEnabled": {}, "loginPolicy": {},
|
||||
"verificationLoginPolicy": {}, "pluginAllowList": {},
|
||||
"verificationLoginPolicy": {}, "pluginAllowList": {}, "ssl": {},
|
||||
}
|
||||
|
||||
var legacyPluginExecutableMap = map[string]string{
|
||||
@@ -140,7 +141,7 @@ func PlanLegacyMigration(root string, _ RuntimeValidationOptions) (LegacyMigrati
|
||||
if err := json.Unmarshal(data, &legacy); err != nil {
|
||||
return LegacyMigrationPlan{}, err
|
||||
}
|
||||
plan.ManualFields = legacyManualFields(legacy)
|
||||
plan.ManualFields = legacyManualFields(root, legacy)
|
||||
if len(plan.ManualFields) > 0 {
|
||||
return plan, ErrMigrationUnsafeValue
|
||||
}
|
||||
@@ -371,9 +372,9 @@ func equivalentStoredSecret(expected, existing StoredSecret, vault *credential.V
|
||||
return expectedErr == nil && existingErr == nil && expectedPlaintext == existingPlaintext
|
||||
}
|
||||
|
||||
func legacyManualFields(legacy legacyMigrationConfig) []string {
|
||||
func legacyManualFields(root string, legacy legacyMigrationConfig) []string {
|
||||
fields := make([]string, 0)
|
||||
_, _, databaseManualFields := legacyDatabasePlan(legacy)
|
||||
_, _, databaseManualFields := legacyDatabasePlan(root, legacy)
|
||||
fields = append(fields, databaseManualFields...)
|
||||
if _, ok := legacyControlledReference(legacy.SSLPublicKeyPath); legacy.SSLPublicKeyPath != "" && !ok {
|
||||
fields = append(fields, "SSLPublicKeyPath")
|
||||
@@ -381,6 +382,12 @@ func legacyManualFields(legacy legacyMigrationConfig) []string {
|
||||
if _, ok := legacyControlledReference(legacy.SSLPrivateKeyPath); legacy.SSLPrivateKeyPath != "" && !ok {
|
||||
fields = append(fields, "SSLPrivateKeyPath")
|
||||
}
|
||||
if _, ok := legacyControlledReference(legacy.SSL.CertificateRef); legacy.SSL.CertificateRef != "" && !ok {
|
||||
fields = append(fields, "ssl.certificateRef")
|
||||
}
|
||||
if _, ok := legacyControlledReference(legacy.SSL.PrivateKeyRef); legacy.SSL.PrivateKeyRef != "" && !ok {
|
||||
fields = append(fields, "ssl.privateKeyRef")
|
||||
}
|
||||
if legacy.SMTPUsername == "" && legacy.SMTPPassword != "" {
|
||||
fields = append(fields, "smtpPassword")
|
||||
}
|
||||
@@ -568,7 +575,7 @@ func prepareLegacyRuntime(runtime RuntimeConfig) (RuntimeConfig, error) {
|
||||
}
|
||||
|
||||
func legacyDatabaseConfig(root string, vault *credential.Vault, legacy legacyMigrationConfig) (DatabaseConfig, []string, error) {
|
||||
database, password, manualFields := legacyDatabasePlan(legacy)
|
||||
database, password, manualFields := legacyDatabasePlan(root, legacy)
|
||||
if len(manualFields) > 0 {
|
||||
return DatabaseConfig{}, manualFields, nil
|
||||
}
|
||||
@@ -583,10 +590,10 @@ func legacyDatabaseConfig(root string, vault *credential.Vault, legacy legacyMig
|
||||
return database, nil, nil
|
||||
}
|
||||
|
||||
func legacyDatabasePlan(legacy legacyMigrationConfig) (DatabaseConfig, string, []string) {
|
||||
func legacyDatabasePlan(root string, legacy legacyMigrationConfig) (DatabaseConfig, string, []string) {
|
||||
switch legacy.DbType {
|
||||
case "", DBTypeSQLite:
|
||||
name, ok := legacySQLiteLocalRef(legacy.DbDSN)
|
||||
name, ok := legacySQLiteLocalRef(root, legacy.DbDSN)
|
||||
if !ok {
|
||||
return DatabaseConfig{}, "", []string{"dbDSN"}
|
||||
}
|
||||
@@ -608,15 +615,28 @@ func legacyDatabasePlan(legacy legacyMigrationConfig) (DatabaseConfig, string, [
|
||||
}
|
||||
}
|
||||
|
||||
func legacySQLiteLocalRef(value string) (string, bool) {
|
||||
func legacySQLiteLocalRef(root, value string) (string, bool) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
value = "smail.db"
|
||||
}
|
||||
value = filepath.ToSlash(value)
|
||||
if root != "" {
|
||||
rootSlash := strings.TrimRight(filepath.ToSlash(root), "/")
|
||||
if strings.HasPrefix(value, rootSlash+"/") {
|
||||
value = strings.TrimPrefix(value, rootSlash+"/")
|
||||
} else if filepath.IsAbs(value) || isWindowsAbsolute(value) {
|
||||
if rel, err := filepath.Rel(root, value); err == nil {
|
||||
rel = filepath.ToSlash(rel)
|
||||
if !strings.HasPrefix(rel, "../") && rel != ".." {
|
||||
value = rel
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if filepath.IsAbs(value) || isWindowsAbsolute(value) {
|
||||
return "", false
|
||||
}
|
||||
value = filepath.ToSlash(value)
|
||||
value = strings.TrimPrefix(value, "./")
|
||||
value = strings.TrimPrefix(value, "config/")
|
||||
value = strings.TrimPrefix(value, "data/")
|
||||
@@ -740,6 +760,28 @@ func legacySMTPConfig(root string, vault *credential.Vault, legacy legacyMigrati
|
||||
}
|
||||
|
||||
func legacySSLConfig(legacy legacyMigrationConfig) (SSLConfig, []string) {
|
||||
if legacy.SSL.CertificateRef != "" || legacy.SSL.PrivateKeyRef != "" || legacy.SSL.Mode != "" || legacy.SSL.Management != "" {
|
||||
ssl := legacy.SSL
|
||||
if ssl.DefaultDirectory == "" {
|
||||
ssl.DefaultDirectory = "ssl"
|
||||
}
|
||||
var manual []string
|
||||
if ssl.CertificateRef != "" {
|
||||
if ref, ok := legacyControlledReference(ssl.CertificateRef); ok {
|
||||
ssl.CertificateRef = ref
|
||||
} else {
|
||||
manual = append(manual, "ssl.certificateRef")
|
||||
}
|
||||
}
|
||||
if ssl.PrivateKeyRef != "" {
|
||||
if ref, ok := legacyControlledReference(ssl.PrivateKeyRef); ok {
|
||||
ssl.PrivateKeyRef = ref
|
||||
} else {
|
||||
manual = append(manual, "ssl.privateKeyRef")
|
||||
}
|
||||
}
|
||||
return ssl, manual
|
||||
}
|
||||
certificateRef, certificateOK := legacyControlledReference(legacy.SSLPublicKeyPath)
|
||||
privateKeyRef, privateKeyOK := legacyControlledReference(legacy.SSLPrivateKeyPath)
|
||||
certificateRef = runtimepath.LegacyReference(certificateRef)
|
||||
|
||||
@@ -724,3 +724,58 @@ func TestMigrateLegacyConfigDerivesSetupStateFromFullPreflight(t *testing.T) {
|
||||
t.Fatalf("setup state = %q / %q", runtime.SetupState, runtime.Root.SetupState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateLegacyConfigAcceptsStructuredSSLObject(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
legacy := map[string]any{
|
||||
"domain": "mail.example.com",
|
||||
"domains": []string{"mail.example.com"},
|
||||
"webDomain": "mail.example.com",
|
||||
"dbDSN": "./config/smail.db",
|
||||
"dbType": "sqlite",
|
||||
"isInit": true,
|
||||
"ssl": map[string]any{
|
||||
"management": "project",
|
||||
"mode": "managed_default",
|
||||
"defaultDirectory": "ssl",
|
||||
"challenge": "dns",
|
||||
"certificateRef": "ssl/custom.crt",
|
||||
"privateKeyRef": "ssl/custom.key",
|
||||
},
|
||||
}
|
||||
writeLegacyMigrationFixture(t, root, legacy)
|
||||
|
||||
result, err := MigrateLegacyConfig(root, RuntimeValidationOptions{HasSuperAdmin: true, Production: true})
|
||||
if err != nil {
|
||||
t.Fatalf("MigrateLegacyConfig failed: %v", err)
|
||||
}
|
||||
if result.Generation != 1 {
|
||||
t.Fatalf("unexpected generation: %d", result.Generation)
|
||||
}
|
||||
|
||||
runtime, err := NewConfigLoader(root, ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}}).Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load failed: %v", err)
|
||||
}
|
||||
if runtime.SSL.TLS.CertificateRef != "ssl/custom.crt" || runtime.SSL.TLS.PrivateKeyRef != "ssl/custom.key" {
|
||||
t.Fatalf("unexpected SSL refs: %+v", runtime.SSL.TLS)
|
||||
}
|
||||
if runtime.SSL.TLS.Mode != "managed_default" || runtime.SSL.TLS.Management != "project" {
|
||||
t.Fatalf("unexpected SSL mode/mgmt: %+v", runtime.SSL.TLS)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateLegacyConfigAcceptsDeploymentAbsoluteSQLiteDSN(t *testing.T) {
|
||||
root := "/opt/smail"
|
||||
ref, ok := legacySQLiteLocalRef(root, "/opt/smail/data/smail.db")
|
||||
if !ok || ref != "smail.db" {
|
||||
t.Fatalf("unexpected sqlite local ref: %q, ok: %v", ref, ok)
|
||||
}
|
||||
dbCfg, _, manual := legacyDatabasePlan(root, legacyMigrationConfig{
|
||||
DbType: "sqlite",
|
||||
DbDSN: "/opt/smail/data/smail.db",
|
||||
})
|
||||
if len(manual) > 0 || dbCfg.LocalRef != "smail.db" {
|
||||
t.Fatalf("unexpected db plan: %+v, manual: %v", dbCfg, manual)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -8,6 +9,50 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var knownActionMap = map[string]string{
|
||||
"imap_server.(*serverSession).Login": "IMAP 客户端登录",
|
||||
"imap_server.(*serverSession).Close": "IMAP 断开连接",
|
||||
"imap_server.(*serverSession).Select": "IMAP 选择邮箱",
|
||||
"imap_server.(*serverSession).Fetch": "IMAP 获取邮件",
|
||||
"imap_server.(*serverSession).Append": "IMAP 追加邮件",
|
||||
"imap_server.(*serverSession).Delete": "IMAP 删除邮箱",
|
||||
"pop3_server.action.Pass": "POP3 客户端登录",
|
||||
"pop3_server.action.Retr": "POP3 获取邮件",
|
||||
"smtp_server.(*Session).AuthPlain": "SMTP 客户端认证",
|
||||
"send.doSend": "SMTP 邮件投递",
|
||||
"send.doSend.func2": "SMTP 邮件投递",
|
||||
"send.Send": "发送邮件",
|
||||
}
|
||||
|
||||
var cleanFuncRe = regexp.MustCompile(`^([a-zA-Z0-9_]+)\.(?:\(\*?[a-zA-Z0-9_]+\)\.)?([a-zA-Z0-9_]+)(?:\.func\d+)?$`)
|
||||
|
||||
func friendlyActionFromCaller(function string) string {
|
||||
if action, ok := knownActionMap[function]; ok {
|
||||
return action
|
||||
}
|
||||
m := cleanFuncRe.FindStringSubmatch(function)
|
||||
if len(m) == 3 {
|
||||
pkg := m[1]
|
||||
fn := m[2]
|
||||
pkgLabel := map[string]string{
|
||||
"imap_server": "IMAP 服务",
|
||||
"pop3_server": "POP3 服务",
|
||||
"smtp_server": "SMTP 服务",
|
||||
"send": "邮件投递",
|
||||
"controllers": "接口处理",
|
||||
"services": "系统服务",
|
||||
"res_init": "系统初始化",
|
||||
"hooks": "插件钩子",
|
||||
"adminreset": "超级管理",
|
||||
}[pkg]
|
||||
if pkgLabel == "" {
|
||||
pkgLabel = pkg
|
||||
}
|
||||
return pkgLabel + " · " + fn
|
||||
}
|
||||
return "运行事件 · " + function
|
||||
}
|
||||
|
||||
// runtimeEventFields 为文件日志提供稳定的事件边界;没有完成信号时只记为状态记录。
|
||||
// 不从任意消息中的“成功”或日志级别猜测业务结果,也不改变调用方的字段。
|
||||
func runtimeEventFields(entry *log.Entry) map[string]any {
|
||||
@@ -30,7 +75,7 @@ func runtimeEventFields(entry *log.Entry) map[string]any {
|
||||
if index := strings.LastIndex(function, "/"); index >= 0 {
|
||||
function = function[index+1:]
|
||||
}
|
||||
action += " · " + function
|
||||
action = friendlyActionFromCaller(function)
|
||||
}
|
||||
fields["action"] = action
|
||||
}
|
||||
@@ -38,4 +83,4 @@ func runtimeEventFields(entry *log.Entry) map[string]any {
|
||||
fields["result"] = "recorded"
|
||||
}
|
||||
return fields
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -146,6 +146,8 @@ func syncTables() error {
|
||||
&models.WebAuthnCredential{},
|
||||
&models.ProtocolCredential{},
|
||||
&models.Version{},
|
||||
&models.UserContact{},
|
||||
&models.UserTrustedSender{},
|
||||
}
|
||||
for _, table := range tables {
|
||||
if err := Instance.Sync2(table); err != nil {
|
||||
|
||||
@@ -28,6 +28,7 @@ func DefaultMigrations() []Migration {
|
||||
DefineCustom(16, "expand_user_security_preferences", "expand_user_security_preferences_v1", applyUserSecurityPreferencesSchema),
|
||||
DefineForDialects(17, "create_managed_logs", logStatements()),
|
||||
DefineCustom(18, "expand_operation_log_actor_role", "expand_operation_log_actor_role_v1", applyOperationLogActorRoleSchema),
|
||||
DefineForDialects(19, "create_user_contacts_and_trusted_senders", userContactStatements()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ func TestDefaultMigrationsCreateCompleteSQLiteSchema(t *testing.T) {
|
||||
t.Fatalf("report = %+v", report)
|
||||
}
|
||||
|
||||
for _, table := range []string{"user", "email", "group", "rule", "sessions", "user_email", "version", "external_email", "verification_event", "security_question", "recovery_code", "verification_rate_limit", "verification_cleanup_state", "webauthn_credential", "totp_authenticator", "plugin_secret", "plugin_user_setting", "schema_migration"} {
|
||||
for _, table := range []string{"user", "email", "group", "rule", "sessions", "user_email", "version", "external_email", "verification_event", "security_question", "recovery_code", "verification_rate_limit", "verification_cleanup_state", "webauthn_credential", "totp_authenticator", "plugin_secret", "plugin_user_setting", "schema_migration", "user_contact", "user_trusted_sender"} {
|
||||
if !sqliteTableExists(t, db, table) {
|
||||
t.Fatalf("table %s was not created", table)
|
||||
}
|
||||
@@ -283,6 +283,7 @@ func TestDefaultMigrationChecksumsAreImmutable(t *testing.T) {
|
||||
16: "00cc275529e522d93b41e608692fb6e2271f1aa9300ebe020fcaed4d68d0ff76",
|
||||
17: "1dad66acb5e7fecf6c39f4a78526b994748d90045220f446a2e80c1b5fd881e7",
|
||||
18: "17622df3406657f199d78a3a1aa1f3a8693baf85aa7707910cc6d6cb44c13ee4",
|
||||
19: "f24b94ca9e4c25b7973f6c15fcaddccc7f02bcf7886c0a4995d2f7b79f4a3a16",
|
||||
}
|
||||
migrations := DefaultMigrations()
|
||||
if len(migrations) != len(expected) {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package migration
|
||||
|
||||
func userContactStatements() map[Dialect][]string {
|
||||
return map[Dialect][]string{
|
||||
DialectSQLite: {
|
||||
`CREATE TABLE IF NOT EXISTS "user_contact" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "user_id" INTEGER NOT NULL, "email" TEXT NOT NULL, "name" TEXT NOT NULL DEFAULT '', "last_used_at" DATETIME NOT NULL, UNIQUE("user_id", "email"))`,
|
||||
`CREATE INDEX IF NOT EXISTS "idx_user_contact_user_last_used" ON "user_contact"("user_id", "last_used_at")`,
|
||||
`CREATE TABLE IF NOT EXISTS "user_trusted_sender" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "user_id" INTEGER NOT NULL, "email" TEXT NOT NULL, "created_at" DATETIME NOT NULL, UNIQUE("user_id", "email"))`,
|
||||
`CREATE INDEX IF NOT EXISTS "idx_user_trusted_sender_user" ON "user_trusted_sender"("user_id", "email")`,
|
||||
},
|
||||
DialectMySQL: {
|
||||
"CREATE TABLE IF NOT EXISTS `user_contact` (`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `user_id` BIGINT NOT NULL, `email` VARCHAR(255) NOT NULL, `name` VARCHAR(100) NOT NULL DEFAULT '', `last_used_at` DATETIME(6) NOT NULL, UNIQUE KEY `uq_user_contact_user_email` (`user_id`, `email`), KEY `idx_user_contact_user_last_used` (`user_id`, `last_used_at`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",
|
||||
"CREATE TABLE IF NOT EXISTS `user_trusted_sender` (`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `user_id` BIGINT NOT NULL, `email` VARCHAR(255) NOT NULL, `created_at` DATETIME(6) NOT NULL, UNIQUE KEY `uq_user_trusted_sender_user_email` (`user_id`, `email`), KEY `idx_user_trusted_sender_user` (`user_id`, `email`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",
|
||||
},
|
||||
DialectPostgres: {
|
||||
`CREATE TABLE IF NOT EXISTS "user_contact" ("id" BIGSERIAL PRIMARY KEY, "user_id" BIGINT NOT NULL, "email" VARCHAR(255) NOT NULL, "name" VARCHAR(100) NOT NULL DEFAULT '', "last_used_at" TIMESTAMPTZ NOT NULL, UNIQUE("user_id", "email"))`,
|
||||
`CREATE INDEX IF NOT EXISTS "idx_user_contact_user_last_used" ON "user_contact"("user_id", "last_used_at")`,
|
||||
`CREATE TABLE IF NOT EXISTS "user_trusted_sender" ("id" BIGSERIAL PRIMARY KEY, "user_id" BIGINT NOT NULL, "email" VARCHAR(255) NOT NULL, "created_at" TIMESTAMPTZ NOT NULL, UNIQUE("user_id", "email"))`,
|
||||
`CREATE INDEX IF NOT EXISTS "idx_user_trusted_sender_user" ON "user_trusted_sender"("user_id", "email")`,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,9 @@ func registerV1Routes(mux *http.ServeMux) {
|
||||
registerV1MethodRoute(mux, "/api/v1/email/detail", "/api/email/detail", http.MethodPost, 256<<10, email.EmailDetail)
|
||||
registerV1MethodRoute(mux, "/api/v1/email/move", "/api/email/move", http.MethodPost, 256<<10, email.Move)
|
||||
registerV1MethodRoute(mux, "/api/v1/email/send", "/api/email/send", http.MethodPost, 40<<20, email.Send)
|
||||
registerV1MethodRoute(mux, "/api/v1/email/contacts", "/api/email/contacts", http.MethodGet, 0, email.ContactsList)
|
||||
registerV1MethodRoute(mux, "/api/v1/email/contacts/delete", "/api/email/contacts/delete", http.MethodPost, 16<<10, email.DeleteContact)
|
||||
registerV1MethodRoute(mux, "/api/v1/email/trust-sender", "/api/email/trust-sender", http.MethodPost, 16<<10, email.TrustSender)
|
||||
registerV1MethodRoute(mux, "/api/v1/settings/modify_password", "/api/settings/modify_password", http.MethodPost, 64<<10, controllers.ModifyPassword)
|
||||
registerV1MethodRoute(mux, "/api/v1/rule/get", "/api/rule/get", http.MethodPost, 4<<10, controllers.GetRule)
|
||||
registerV1MethodRoute(mux, "/api/v1/rule/add", "/api/rule/add", http.MethodPost, 64<<10, controllers.UpsertRule)
|
||||
|
||||
@@ -88,6 +88,9 @@ func router(mux *http.ServeMux) error {
|
||||
mux.HandleFunc("/api/email/detail", onlyMethod(http.MethodPost, limitBody(256<<10, contextIterceptor(email.EmailDetail))))
|
||||
mux.HandleFunc("/api/email/move", onlyMethod(http.MethodPost, limitBody(256<<10, contextIterceptor(email.Move))))
|
||||
mux.HandleFunc("/api/email/send", onlyMethod(http.MethodPost, limitBody(40<<20, contextIterceptor(email.Send))))
|
||||
mux.HandleFunc("/api/email/contacts", onlyMethod(http.MethodGet, contextIterceptor(email.ContactsList)))
|
||||
mux.HandleFunc("/api/email/contacts/delete", onlyMethod(http.MethodPost, limitBody(16<<10, contextIterceptor(email.DeleteContact))))
|
||||
mux.HandleFunc("/api/email/trust-sender", onlyMethod(http.MethodPost, limitBody(16<<10, contextIterceptor(email.TrustSender))))
|
||||
mux.HandleFunc("/api/settings/modify_password", onlyMethod(http.MethodPost, limitBody(64<<10, contextIterceptor(controllers.ModifyPassword))))
|
||||
mux.HandleFunc("/api/rule/get", onlyMethod(http.MethodPost, limitBody(4<<10, contextIterceptor(controllers.GetRule))))
|
||||
mux.HandleFunc("/api/rule/add", onlyMethod(http.MethodPost, limitBody(64<<10, contextIterceptor(controllers.UpsertRule))))
|
||||
|
||||
@@ -10,7 +10,11 @@ import (
|
||||
func (s *serverSession) Login(username, pwd string) error {
|
||||
user, err := auth.AuthenticateProtocol("imap", s.remoteAddress, username, pwd)
|
||||
if err != nil {
|
||||
log.WithContext(s.ctx).Info("IMAP authentication failed")
|
||||
log.WithContext(s.ctx).WithFields(log.Fields{
|
||||
"action": "IMAP 客户端登录",
|
||||
"result": "failure",
|
||||
"object": s.remoteAddress,
|
||||
}).Info("IMAP 客户端认证失败")
|
||||
return &imap.Error{
|
||||
Type: imap.StatusResponseTypeNo,
|
||||
Code: imap.ResponseCodeAuthenticationFailed,
|
||||
@@ -24,6 +28,10 @@ func (s *serverSession) Login(username, pwd string) error {
|
||||
s.ctx.UserAccount = user.Account
|
||||
s.ctx.Role = user.EffectiveRole()
|
||||
s.ctx.IsAdmin = s.ctx.Role == access.RoleSuperAdmin || s.ctx.Role == access.RoleAdmin
|
||||
log.WithContext(s.ctx).Debug("IMAP authentication succeeded")
|
||||
log.WithContext(s.ctx).WithFields(log.Fields{
|
||||
"action": "IMAP 客户端登录",
|
||||
"result": "success",
|
||||
"object": s.remoteAddress,
|
||||
}).Debug("IMAP 客户端认证成功")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -105,7 +105,11 @@ func (a action) Pass(session *gopop.Session, pwd string) error {
|
||||
}
|
||||
user, err := auth.AuthenticateProtocol("pop3", remoteAddress, session.User, pwd)
|
||||
if err != nil {
|
||||
log.WithContext(session.Ctx).Info("POP3 authentication failed")
|
||||
log.WithContext(session.Ctx).WithFields(log.Fields{
|
||||
"action": "POP3 客户端登录",
|
||||
"result": "failure",
|
||||
"object": remoteAddress,
|
||||
}).Info("POP3 客户端认证失败")
|
||||
return errors2.New("password error")
|
||||
}
|
||||
|
||||
|
||||
@@ -64,7 +64,11 @@ func (s *Session) Auth(mech string) (sasl.Server, error) {
|
||||
func (s *Session) AuthPlain(username, pwd string) error {
|
||||
user, err := auth.AuthenticateProtocol("smtp", s.RemoteAddress.String(), username, pwd)
|
||||
if err != nil {
|
||||
log.WithContext(s.Ctx).Info("SMTP authentication failed")
|
||||
log.WithContext(s.Ctx).WithFields(log.Fields{
|
||||
"action": "SMTP 客户端认证",
|
||||
"result": "failure",
|
||||
"object": s.RemoteAddress.String(),
|
||||
}).Info("SMTP 客户端认证失败")
|
||||
return errors.New("password error")
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// UserContact 保存单个用户的历史写信收件人,用于写信页自动补全与联系人管理
|
||||
type UserContact struct {
|
||||
ID int `xorm:"id bigint unsigned not null pk autoincr" json:"id"`
|
||||
UserID int `xorm:"user_id bigint not null" json:"-"`
|
||||
Email string `xorm:"email varchar(255) notnull" json:"email"`
|
||||
Name string `xorm:"name varchar(100) notnull default('')" json:"name"`
|
||||
LastUsedAt time.Time `xorm:"last_used_at datetime notnull" json:"last_used_at"`
|
||||
}
|
||||
|
||||
func (UserContact) TableName() string { return "user_contact" }
|
||||
|
||||
// UserTrustedSender 保存单个用户手动标记信任的发件人白名单,免除安全警告
|
||||
type UserTrustedSender struct {
|
||||
ID int `xorm:"id bigint unsigned not null pk autoincr" json:"id"`
|
||||
UserID int `xorm:"user_id bigint not null" json:"-"`
|
||||
Email string `xorm:"email varchar(255) notnull" json:"email"`
|
||||
CreatedAt time.Time `xorm:"created_at datetime created notnull" json:"created_at"`
|
||||
}
|
||||
|
||||
func (UserTrustedSender) TableName() string { return "user_trusted_sender" }
|
||||
@@ -72,24 +72,44 @@ func ResolveIdentifier(identifier string) (ResolvedIdentity, error) {
|
||||
Find(&bindings); err != nil {
|
||||
return ResolvedIdentity{}, fmt.Errorf("load login email binding: %w", err)
|
||||
}
|
||||
if len(bindings) != 1 || bindings[0].UserID <= 0 {
|
||||
return ResolvedIdentity{}, errors.New("invalid identifier")
|
||||
if len(bindings) == 1 && bindings[0].UserID > 0 {
|
||||
var user models.User
|
||||
has, err := db.Instance.ID(bindings[0].UserID).Get(&user)
|
||||
if err != nil {
|
||||
return ResolvedIdentity{}, fmt.Errorf("load login user: %w", err)
|
||||
}
|
||||
if has && user.ID > 0 && user.Account != "" && user.Disabled == 0 {
|
||||
return ResolvedIdentity{
|
||||
UserID: user.ID,
|
||||
Account: user.Account,
|
||||
LoginAddress: normalized,
|
||||
Kind: IdentifierEmail,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
var user models.User
|
||||
has, err := db.Instance.ID(bindings[0].UserID).Get(&user)
|
||||
if err != nil {
|
||||
return ResolvedIdentity{}, fmt.Errorf("load login user: %w", err)
|
||||
// 回退机制:若未绑定独立外部邮箱,但属于系统配置的域名,则按账号匹配有效系统用户
|
||||
parts := strings.SplitN(normalized, "@", 2)
|
||||
if len(parts) == 2 && isConfiguredLoginDomain(parts[1]) {
|
||||
account, err := validation.NormalizeAccount(parts[0])
|
||||
if err == nil {
|
||||
var user models.User
|
||||
has, err := db.Instance.Where("account = ? AND disabled = 0", account).Get(&user)
|
||||
if err != nil {
|
||||
return ResolvedIdentity{}, fmt.Errorf("load domain user: %w", err)
|
||||
}
|
||||
if has && user.ID > 0 && user.Account != "" {
|
||||
return ResolvedIdentity{
|
||||
UserID: user.ID,
|
||||
Account: user.Account,
|
||||
LoginAddress: normalized,
|
||||
Kind: IdentifierEmail,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
if !has || user.ID <= 0 || user.Account == "" {
|
||||
return ResolvedIdentity{}, errors.New("invalid identifier")
|
||||
}
|
||||
return ResolvedIdentity{
|
||||
UserID: user.ID,
|
||||
Account: user.Account,
|
||||
LoginAddress: normalized,
|
||||
Kind: IdentifierEmail,
|
||||
}, nil
|
||||
|
||||
return ResolvedIdentity{}, errors.New("invalid identifier")
|
||||
}
|
||||
|
||||
func parseLoginIdentifier(identifier string) (string, IdentifierKind, error) {
|
||||
|
||||
@@ -92,3 +92,53 @@ func TestNormalizeIdentifierKeepsLegacyAccountCompatibility(t *testing.T) {
|
||||
t.Fatalf("normalized email key = %q, err = %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func TestResolveIdentifierFallbackToConfiguredDomainUser(t *testing.T) {
|
||||
oldConfig := config.Instance
|
||||
oldDB := db.Instance
|
||||
config.Instance = &config.Config{
|
||||
DbType: config.DBTypeSQLite,
|
||||
DbDSN: filepath.Join(t.TempDir(), "domain_fallback.db"),
|
||||
Domain: "solit.cn",
|
||||
Domains: []string{"solit.cn"},
|
||||
}
|
||||
if err := db.Init(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if db.Instance != nil && db.Instance != oldDB {
|
||||
_ = db.Instance.Close()
|
||||
}
|
||||
db.Instance = oldDB
|
||||
config.Instance = oldConfig
|
||||
})
|
||||
|
||||
user := models.User{Account: "bob", Name: "Bob", Disabled: 0}
|
||||
if err := SetPassword(&user, "CorrectP12"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Instance.Insert(&user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
identity, err := ResolveIdentifier(" Bob@Solit.cn ")
|
||||
if err != nil {
|
||||
t.Fatalf("resolve configured domain user failed: %v", err)
|
||||
}
|
||||
if identity.Kind != IdentifierEmail || identity.UserID != user.ID || identity.Account != "bob" || identity.LoginAddress != "bob@solit.cn" {
|
||||
t.Fatalf("unexpected resolved identity: %+v", identity)
|
||||
}
|
||||
|
||||
disabledUser := models.User{Account: "charlie", Name: "Charlie", Disabled: 1}
|
||||
if _, err := db.Instance.Insert(&disabledUser); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ResolveIdentifier("charlie@solit.cn"); err == nil {
|
||||
t.Fatal("disabled domain user must not be resolved")
|
||||
}
|
||||
|
||||
if _, err := ResolveIdentifier("bob@other.com"); err == nil {
|
||||
t.Fatal("unconfigured domain must not be resolved")
|
||||
}
|
||||
}
|
||||
@@ -55,10 +55,10 @@ func (s *Service) SetSecurityQuestion(userID int, question, answer string) error
|
||||
}
|
||||
question = strings.TrimSpace(norm.NFKC.String(question))
|
||||
answer = normalizeAnswer(answer)
|
||||
if len([]byte(question)) < 2 || len([]byte(question)) > 255 {
|
||||
if len([]rune(question)) < 1 {
|
||||
return ErrInvalidQuestion
|
||||
}
|
||||
if len([]byte(answer)) < 8 || len([]byte(answer)) > 256 {
|
||||
if len([]rune(answer)) < 1 {
|
||||
return ErrInvalidAnswer
|
||||
}
|
||||
hash, err := password.Hash(answer)
|
||||
@@ -71,12 +71,8 @@ func (s *Service) SetSecurityQuestion(userID int, question, answer string) error
|
||||
return fmt.Errorf("load security question: %w", err)
|
||||
}
|
||||
if has {
|
||||
version := item.Version + 1
|
||||
if version <= 0 {
|
||||
version = 1
|
||||
}
|
||||
item.Question, item.AnswerHash, item.Version = question, hash, version
|
||||
if _, err := s.engine.ID(item.ID).Cols("question", "answer_hash", "version", "updated_at").Update(item); err != nil {
|
||||
item.Question, item.AnswerHash = question, hash
|
||||
if _, err := s.engine.ID(item.ID).Cols("question", "answer_hash", "updated_at").Update(item); err != nil {
|
||||
return fmt.Errorf("update security question: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -32,6 +32,36 @@ func newFixture(t *testing.T) *Service {
|
||||
return service
|
||||
}
|
||||
|
||||
func TestSecurityQuestionSupportsSingleCharacterAndUnlimited(t *testing.T) {
|
||||
service := newFixture(t)
|
||||
if err := service.SetSecurityQuestion(1, "Q", "A"); err != nil {
|
||||
t.Fatalf("setting 1 char question and answer failed: %v", err)
|
||||
}
|
||||
question, ok, err := service.GetSecurityQuestion(1)
|
||||
if err != nil || !ok || question != "Q" {
|
||||
t.Fatalf("question = %q, ok=%v, err=%v", question, ok, err)
|
||||
}
|
||||
if verified, err := service.VerifySecurityQuestion(1, "A"); err != nil || !verified {
|
||||
t.Fatalf("verification failed: %v, %v", verified, err)
|
||||
}
|
||||
if err := service.SetSecurityQuestion(1, " ", "A"); !errors.Is(err, ErrInvalidQuestion) {
|
||||
t.Fatalf("want ErrInvalidQuestion, got: %v", err)
|
||||
}
|
||||
if err := service.SetSecurityQuestion(1, "Q", " "); !errors.Is(err, ErrInvalidAnswer) {
|
||||
t.Fatalf("want ErrInvalidAnswer, got: %v", err)
|
||||
}
|
||||
if err := service.SetSecurityQuestion(1, "UpdatedQ", "UpdatedA"); err != nil {
|
||||
t.Fatalf("update security question failed: %v", err)
|
||||
}
|
||||
updatedQuestion, ok, err := service.GetSecurityQuestion(1)
|
||||
if err != nil || !ok || updatedQuestion != "UpdatedQ" {
|
||||
t.Fatalf("updated question = %q, ok=%v, err=%v", updatedQuestion, ok, err)
|
||||
}
|
||||
if verified, err := service.VerifySecurityQuestion(1, "UpdatedA"); err != nil || !verified {
|
||||
t.Fatalf("verification of updated answer failed: %v, %v", verified, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityQuestionIsCaseInsensitiveAndNeverReturnsHash(t *testing.T) {
|
||||
service := newFixture(t)
|
||||
if err := service.SetSecurityQuestion(1, "第一只宠物叫什么?", "BlueBird123"); err != nil {
|
||||
|
||||
@@ -22,8 +22,7 @@ const (
|
||||
saltLength = 16
|
||||
keyLength = 32
|
||||
maxHashSize = 255
|
||||
minSecretSize = 8
|
||||
maxSecretSize = 256
|
||||
minSecretSize = 1
|
||||
minPasswordSize = 8
|
||||
maxPasswordSize = 12
|
||||
)
|
||||
@@ -41,7 +40,7 @@ func ValidateUserPassword(plain string) error {
|
||||
// Hash 生成 Argon2id 密码哈希。
|
||||
func Hash(plain string) (string, error) {
|
||||
plainSize := len([]byte(plain))
|
||||
if plainSize < minSecretSize || plainSize > maxSecretSize {
|
||||
if plainSize < minSecretSize {
|
||||
return "", ErrInvalidLength
|
||||
}
|
||||
salt := make([]byte, saltLength)
|
||||
@@ -83,7 +82,7 @@ func HashUserPassword(plain string) (string, error) {
|
||||
|
||||
// Verify 校验 Argon2id 密码哈希,不接受旧算法格式。
|
||||
func Verify(encoded, plain string) bool {
|
||||
if len([]byte(plain)) > maxSecretSize {
|
||||
if len([]byte(plain)) < minSecretSize {
|
||||
return false
|
||||
}
|
||||
parts := strings.Split(encoded, "$")
|
||||
|
||||
@@ -16,14 +16,21 @@ func TestHashAndVerify(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashRejectsInvalidLengths(t *testing.T) {
|
||||
for _, plain := range []string{"short", strings.Repeat("a", maxSecretSize+1)} {
|
||||
if _, err := Hash(plain); err == nil {
|
||||
t.Fatalf("invalid secret length was accepted: %d", len([]byte(plain)))
|
||||
func TestHashSupportsSingleCharacterAndLongInputs(t *testing.T) {
|
||||
for _, plain := range []string{"a", "中", strings.Repeat("long-secret-key-123", 50)} {
|
||||
encoded, err := Hash(plain)
|
||||
if err != nil {
|
||||
t.Fatalf("valid secret %q failed: %v", plain, err)
|
||||
}
|
||||
if !Verify(encoded, plain) {
|
||||
t.Fatalf("verification failed for %q", plain)
|
||||
}
|
||||
}
|
||||
if Verify(mustHash(t, "StrongPass123"), strings.Repeat("a", maxSecretSize+1)) {
|
||||
t.Fatal("oversized verification input was accepted")
|
||||
if _, err := Hash(""); !errors.Is(err, ErrInvalidLength) {
|
||||
t.Fatalf("empty secret should be rejected, got: %v", err)
|
||||
}
|
||||
if Verify(mustHash(t, "StrongPass123"), "") {
|
||||
t.Fatal("empty verification input was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -277,7 +277,11 @@ func doSend(ctx *context.Context, fromDomain string, data []byte, to []*parsemai
|
||||
recordFailure(err)
|
||||
return
|
||||
}
|
||||
log.WithContext(ctx).Infof("SMTP STARTTLS on 25 Send Error. %s", err.Error())
|
||||
log.WithContext(ctx).WithFields(log.Fields{
|
||||
"action": "SMTP 邮件投递",
|
||||
"result": "failure",
|
||||
"object": domain.mxHost + ":25",
|
||||
}).Infof("SMTP 25 端口 STARTTLS 投递失败: %s", err.Error())
|
||||
|
||||
// 再试用587投递
|
||||
err = smtp.SendMailWithTls(strings.TrimSuffix(domain.mxHost, "."), domain.mxHost+":587", nil, from, fromDomain, buildAddress(tos), data)
|
||||
@@ -293,7 +297,11 @@ func doSend(ctx *context.Context, fromDomain string, data []byte, to []*parsemai
|
||||
recordFailure(err)
|
||||
return
|
||||
}
|
||||
log.WithContext(ctx).Infof("SMTPS on 587 Send Error. %s", err.Error())
|
||||
log.WithContext(ctx).WithFields(log.Fields{
|
||||
"action": "SMTP 邮件投递",
|
||||
"result": "failure",
|
||||
"object": domain.mxHost + ":587",
|
||||
}).Infof("SMTP 587 端口投递失败: %s", err.Error())
|
||||
|
||||
// 再次尝试465投递
|
||||
err = smtp.SendMailWithTls(strings.TrimSuffix(domain.mxHost, "."), domain.mxHost+":465", nil, from, fromDomain, buildAddress(tos), data)
|
||||
@@ -309,7 +317,11 @@ func doSend(ctx *context.Context, fromDomain string, data []byte, to []*parsemai
|
||||
recordFailure(err)
|
||||
return
|
||||
}
|
||||
log.WithContext(ctx).Infof("SMTPS on 465 Send Error. %s", err.Error())
|
||||
log.WithContext(ctx).WithFields(log.Fields{
|
||||
"action": "SMTP 邮件投递",
|
||||
"result": "failure",
|
||||
"object": domain.mxHost + ":465",
|
||||
}).Infof("SMTP 465 端口投递失败: %s", err.Error())
|
||||
|
||||
// 所有安全投递方式均失败后记录错误,不允许回退到明文连接。
|
||||
recordFailure(err)
|
||||
|
||||
@@ -306,3 +306,39 @@
|
||||
padding: 12px 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.contact-option-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.contact-option-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.contact-option-name {
|
||||
font-weight: 600;
|
||||
color: var(--pm-text-primary);
|
||||
}
|
||||
|
||||
.contact-option-email {
|
||||
color: var(--pm-text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.contact-del-icon {
|
||||
font-size: 14px;
|
||||
color: var(--pm-text-muted);
|
||||
padding: 4px;
|
||||
border-radius: 4px;
|
||||
transition: color 0.15s ease, background 0.15s ease;
|
||||
}
|
||||
|
||||
.contact-del-icon:hover {
|
||||
color: #ef4444;
|
||||
background: rgba(239, 68, 68, 0.1);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import {ElMessage} from 'element-plus'
|
||||
|
||||
import {onBeforeUnmount, reactive, ref, shallowRef} from 'vue'
|
||||
|
||||
import {Close, Paperclip, Position, ArrowDown, Document} from '@element-plus/icons-vue';
|
||||
import {Close, Paperclip, Position, ArrowDown, Document, Delete} from '@element-plus/icons-vue';
|
||||
|
||||
import lang from '../../i18n/i18n';
|
||||
|
||||
@@ -68,8 +68,32 @@ export function usePage() {
|
||||
})
|
||||
|
||||
const fileList = reactive([]);
|
||||
const contactOptions = ref([]);
|
||||
|
||||
const loadContacts = function () {
|
||||
http.get("/api/v1/email/contacts").then(res => {
|
||||
if (res.errorNo === 0 && Array.isArray(res.data)) {
|
||||
contactOptions.value = res.data
|
||||
}
|
||||
}).catch(() => {})
|
||||
}
|
||||
|
||||
const deleteContact = function (email) {
|
||||
if (!email) return
|
||||
http.post("/api/v1/email/contacts/delete", {email: email}).then(res => {
|
||||
if (res.errorNo === 0) {
|
||||
ElMessage.success("已从历史联系人中删除")
|
||||
contactOptions.value = contactOptions.value.filter(c => c.email !== email)
|
||||
} else {
|
||||
ElMessage.error(res.errorMsg || "删除失败")
|
||||
}
|
||||
}).catch(() => {
|
||||
ElMessage.error("删除联系人失败")
|
||||
})
|
||||
}
|
||||
|
||||
const init = function () {
|
||||
loadContacts()
|
||||
if ( Object.keys(globalStatus.userInfos)==0 || globalStatus.userInfos === null || globalStatus.userInfos == undefined ){
|
||||
globalStatus.init(()=>{
|
||||
ruleForm.sender = globalStatus.userInfos.account
|
||||
@@ -228,10 +252,10 @@ export function usePage() {
|
||||
Position,
|
||||
ArrowDown,
|
||||
Document,
|
||||
Delete,
|
||||
lang,
|
||||
Editor,
|
||||
Toolbar,
|
||||
i18nChangeLanguage,
|
||||
useRouter,
|
||||
http,
|
||||
useGroupStore,
|
||||
@@ -260,7 +284,10 @@ export function usePage() {
|
||||
send,
|
||||
upload,
|
||||
fileChange,
|
||||
delFile
|
||||
delFile,
|
||||
contactOptions,
|
||||
loadContacts,
|
||||
deleteContact
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,5 +298,6 @@ export {
|
||||
Toolbar,
|
||||
Editor,
|
||||
Document,
|
||||
Close
|
||||
Close,
|
||||
Delete
|
||||
}
|
||||
@@ -59,8 +59,25 @@
|
||||
<el-select
|
||||
v-model="ruleForm.receivers"
|
||||
multiple filterable allow-create :reserve-keyword="false"
|
||||
placeholder="请输入收件人地址"
|
||||
></el-select>
|
||||
placeholder="请输入收件人地址(输入后按回车,或从下方历史联系人选择)"
|
||||
>
|
||||
<el-option
|
||||
v-for="contact in contactOptions"
|
||||
:key="contact.email"
|
||||
:label="contact.name ? `${contact.name} <${contact.email}>` : contact.email"
|
||||
:value="contact.email"
|
||||
>
|
||||
<div class="contact-option-item">
|
||||
<div class="contact-option-info">
|
||||
<span class="contact-option-name" v-if="contact.name">{{ contact.name }}</span>
|
||||
<span class="contact-option-email">{{ contact.email }}</span>
|
||||
</div>
|
||||
<el-tooltip content="从历史记录删除" placement="top">
|
||||
<el-icon class="contact-del-icon" @click.stop="deleteContact(contact.email)"><Delete /></el-icon>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
@@ -71,7 +88,18 @@
|
||||
v-model="ruleForm.cc"
|
||||
multiple filterable allow-create :reserve-keyword="false"
|
||||
placeholder="请输入抄送人地址"
|
||||
></el-select>
|
||||
>
|
||||
<el-option
|
||||
v-for="contact in contactOptions"
|
||||
:key="'cc-' + contact.email"
|
||||
:label="contact.name ? `${contact.name} <${contact.email}>` : contact.email"
|
||||
:value="contact.email"
|
||||
>
|
||||
<div class="contact-option-item">
|
||||
<span class="contact-option-email">{{ contact.email }}</span>
|
||||
</div>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
@@ -82,7 +110,18 @@
|
||||
v-model="ruleForm.bcc"
|
||||
multiple filterable allow-create :reserve-keyword="false"
|
||||
placeholder="请输入密送人地址"
|
||||
></el-select>
|
||||
>
|
||||
<el-option
|
||||
v-for="contact in contactOptions"
|
||||
:key="'bcc-' + contact.email"
|
||||
:label="contact.name ? `${contact.name} <${contact.email}>` : contact.email"
|
||||
:value="contact.email"
|
||||
>
|
||||
<div class="contact-option-item">
|
||||
<span class="contact-option-email">{{ contact.email }}</span>
|
||||
</div>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
@@ -111,7 +150,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { usePage, Paperclip, Position, ArrowDown, Toolbar, Editor, Document, Close } from './Editer.js'
|
||||
import { usePage, Paperclip, Position, ArrowDown, Toolbar, Editor, Document, Close, Delete } from './Editer.js'
|
||||
|
||||
const {
|
||||
lang,
|
||||
@@ -131,7 +170,9 @@ const {
|
||||
editorConfig,
|
||||
handleCreated,
|
||||
fileList,
|
||||
delFile
|
||||
delFile,
|
||||
contactOptions,
|
||||
deleteContact
|
||||
} = usePage()
|
||||
</script>
|
||||
|
||||
|
||||
@@ -233,3 +233,30 @@
|
||||
padding-top: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.mail-status-tags {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.clickable-tag {
|
||||
cursor: pointer;
|
||||
transition: transform 0.15s ease, box-shadow 0.15s ease;
|
||||
}
|
||||
|
||||
.clickable-tag:hover {
|
||||
transform: scale(1.04);
|
||||
box-shadow: 0 2px 8px rgba(239, 68, 68, 0.25);
|
||||
}
|
||||
|
||||
.error-dialog-body {
|
||||
padding: 10px 0;
|
||||
}
|
||||
|
||||
.error-label {
|
||||
font-weight: 600;
|
||||
margin-bottom: 8px;
|
||||
color: var(--pm-text-primary);
|
||||
}
|
||||
@@ -2,11 +2,11 @@ import './List.js'
|
||||
|
||||
import {EpArrowDownBold} from "vue-icons-plus/ep";
|
||||
|
||||
import {Delete, View, Folder, EditPen, Warning, CircleCheck, Switch} from "@element-plus/icons-vue";
|
||||
import {Delete, View, Folder, EditPen, Warning, CircleCheck, Switch, Check} from "@element-plus/icons-vue";
|
||||
|
||||
import {useRouter} from 'vue-router'
|
||||
|
||||
import {ref, watch} from 'vue'
|
||||
import {ref, watch, computed} from 'vue'
|
||||
|
||||
import useGroupStore from '../../stores/group'
|
||||
|
||||
@@ -27,11 +27,23 @@ export function usePage() {
|
||||
|
||||
const selectedRows = ref([])
|
||||
|
||||
const errorDialogVisible = ref(false)
|
||||
const currentErrorMsg = ref('')
|
||||
|
||||
let tag = groupStore.tag;
|
||||
|
||||
if (tag === "") {
|
||||
tag = '{"type":0,"status":-1}'
|
||||
}
|
||||
|
||||
const isOutbox = computed(() => {
|
||||
try {
|
||||
const parsed = JSON.parse(groupStore.tag || tag || '{}')
|
||||
return parsed.type === 1 || groupStore.name === lang.outbox || groupStore.name === '已发送'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
|
||||
watch(groupStore, async (newV) => {
|
||||
tag = newV.tag;
|
||||
@@ -110,7 +122,7 @@ export function usePage() {
|
||||
http.post("/api/v1/email/read", {"ids": ids}).then(res => {
|
||||
if (res.errorNo === 0) {
|
||||
updateList()
|
||||
ElMessage.success('Marked as read');
|
||||
ElMessage.success('已标记为已读');
|
||||
} else {
|
||||
ElMessage.error(res.errorMsg)
|
||||
}
|
||||
@@ -172,6 +184,38 @@ export function usePage() {
|
||||
})
|
||||
}
|
||||
|
||||
const trustSender = function (senderEmail) {
|
||||
if (!senderEmail) return
|
||||
ElMessageBox.confirm(
|
||||
`确定将发件人 "${senderEmail}" 加入信任白名单吗?后续来自该地址的新邮件将不再提示风险。`,
|
||||
'信任发件人',
|
||||
{
|
||||
confirmButtonText: '信任并加入白名单',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning'
|
||||
}
|
||||
).then(() => {
|
||||
http.post("/api/v1/email/trust-sender", {email: senderEmail, trusted: true}).then(res => {
|
||||
if (res.errorNo === 0) {
|
||||
ElMessage.success('已加入信任白名单,风险提示已免除')
|
||||
// 局部更新视图,避免整页重新刷新
|
||||
data.value.forEach(item => {
|
||||
if (item.sender?.EmailAddress === senderEmail) {
|
||||
item.dangerous = false
|
||||
}
|
||||
})
|
||||
} else {
|
||||
ElMessage.error(res.errorMsg || '操作失败')
|
||||
}
|
||||
})
|
||||
}).catch(() => {})
|
||||
}
|
||||
|
||||
const showError = function (row) {
|
||||
currentErrorMsg.value = row.error || '未知投递错误'
|
||||
errorDialogVisible.value = true
|
||||
}
|
||||
|
||||
return {
|
||||
EpArrowDownBold,
|
||||
Delete,
|
||||
@@ -179,11 +223,13 @@ export function usePage() {
|
||||
Folder,
|
||||
EditPen,
|
||||
Warning,
|
||||
Check,
|
||||
CircleCheck,
|
||||
Switch,
|
||||
useRouter,
|
||||
ref,
|
||||
watch,
|
||||
computed,
|
||||
useGroupStore,
|
||||
lang,
|
||||
http,
|
||||
@@ -208,7 +254,12 @@ export function usePage() {
|
||||
move,
|
||||
del,
|
||||
rowStyle,
|
||||
pageChange
|
||||
pageChange,
|
||||
isOutbox,
|
||||
trustSender,
|
||||
showError,
|
||||
errorDialogVisible,
|
||||
currentErrorMsg
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,5 +271,6 @@ export {
|
||||
Folder,
|
||||
EpArrowDownBold,
|
||||
EditPen,
|
||||
Warning
|
||||
Warning,
|
||||
Check
|
||||
}
|
||||
@@ -54,12 +54,6 @@
|
||||
<template #default="scope">
|
||||
<div class="status-indicator">
|
||||
<el-badge is-dot class="unread-dot" type="primary" v-if="!scope.row.is_read"></el-badge>
|
||||
<el-tooltip effect="dark" :content="lang.dangerous" placement="top-start" v-if="scope.row.dangerous">
|
||||
<el-icon color="#ef4444"><Warning /></el-icon>
|
||||
</el-tooltip>
|
||||
<el-tooltip effect="dark" :content="scope.row.error" placement="top-start" v-if="scope.row.error !== ''">
|
||||
<el-icon color="#ef4444"><Warning /></el-icon>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
@@ -71,6 +65,27 @@
|
||||
<div class="mail-sender">
|
||||
{{ scope.row.sender.Name !== '' ? scope.row.sender.Name : scope.row.sender.EmailAddress }}
|
||||
</div>
|
||||
|
||||
<!-- 高辨识度安全与发送状态标签 -->
|
||||
<div class="mail-status-tags" v-if="scope.row.dangerous || isOutbox">
|
||||
<el-tooltip content="点击将该发件人添加至信任白名单,后续免除风险提示" placement="top" v-if="scope.row.dangerous">
|
||||
<el-tag type="danger" effect="dark" size="small" class="clickable-tag" @click.stop="trustSender(scope.row.sender.EmailAddress)">
|
||||
<el-icon><Warning /></el-icon> 疑似不安全 (点击信任)
|
||||
</el-tag>
|
||||
</el-tooltip>
|
||||
|
||||
<template v-if="isOutbox">
|
||||
<el-tag type="success" effect="light" size="small" v-if="!scope.row.error || scope.row.error === ''">
|
||||
<el-icon><Check /></el-icon> 发送成功
|
||||
</el-tag>
|
||||
<el-tooltip :content="scope.row.error" placement="top" v-else>
|
||||
<el-tag type="danger" effect="light" size="small" class="clickable-tag" @click.stop="showError(scope.row)">
|
||||
<el-icon><Warning /></el-icon> 发送失败 (查看详情)
|
||||
</el-tag>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="mail-subject">{{ scope.row.title }}</div>
|
||||
<div class="mail-snippet">{{ scope.row.desc }}</div>
|
||||
</div>
|
||||
@@ -91,11 +106,22 @@
|
||||
@current-change="pageChange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 错误详情对话框 -->
|
||||
<el-dialog v-model="errorDialogVisible" title="邮件发送失败详情" width="500px">
|
||||
<div class="error-dialog-body">
|
||||
<p class="error-label">错误原因:</p>
|
||||
<el-alert :title="currentErrorMsg" type="error" :closable="false" show-icon />
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button type="primary" @click="errorDialogVisible = false">关闭</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { usePage, CircleCheck, Switch, Delete, View, Folder, EpArrowDownBold, EditPen, Warning } from './List.js'
|
||||
import { usePage, CircleCheck, Switch, Delete, View, Folder, EpArrowDownBold, EditPen, Warning, Check } from './List.js'
|
||||
|
||||
const {
|
||||
taskTableDataRef,
|
||||
@@ -114,7 +140,12 @@ const {
|
||||
rowStyle,
|
||||
formatShortDate,
|
||||
totalPage,
|
||||
pageChange
|
||||
pageChange,
|
||||
isOutbox,
|
||||
trustSender,
|
||||
showError,
|
||||
errorDialogVisible,
|
||||
currentErrorMsg
|
||||
} = usePage()
|
||||
</script>
|
||||
|
||||
|
||||
@@ -179,4 +179,4 @@ const {
|
||||
} = useLogs()
|
||||
</script>
|
||||
|
||||
<style scoped src="./LogSettings.css"></style>
|
||||
<style scoped src="./LogSettings.css"></style>
|
||||
@@ -22,6 +22,86 @@ export function timeParts(value) {
|
||||
return { date: localDate.format(date), time: localTime.format(date) }
|
||||
}
|
||||
|
||||
export function cleanRuntimeMessage(text) {
|
||||
if (!text) return ''
|
||||
const boundary = text.lastIndexOf(' @event ')
|
||||
if (boundary >= 0) {
|
||||
return text.slice(0, boundary).trim()
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
export function friendlyOutcomeText(text) {
|
||||
if (!text) return '(无详细说明)'
|
||||
const trimmed = text.trim()
|
||||
const dictionary = {
|
||||
'IMAP authentication failed': 'IMAP 客户端登录认证失败',
|
||||
'IMAP authentication succeeded': 'IMAP 客户端登录认证成功',
|
||||
'POP3 authentication failed': 'POP3 客户端登录认证失败',
|
||||
'POP3 authentication succeeded': 'POP3 客户端登录认证成功',
|
||||
'SMTP authentication failed': 'SMTP 客户端登录认证失败',
|
||||
'SMTP authentication succeeded': 'SMTP 客户端登录认证成功',
|
||||
'SMTP MAIL accepted': 'SMTP 接收发件人地址',
|
||||
'SMTP RCPT accepted': 'SMTP 接收收件人地址',
|
||||
'Plugin Stop': '停止插件执行',
|
||||
'Server Start Success': '服务启动成功',
|
||||
'开始绑定监听端口': '开始绑定并监听网络端口'
|
||||
}
|
||||
if (dictionary[trimmed]) return dictionary[trimmed]
|
||||
|
||||
if (/^SMTP STARTTLS on 25 Send Error\.\s*(.*)$/i.test(trimmed)) {
|
||||
const detail = trimmed.replace(/^SMTP STARTTLS on 25 Send Error\.\s*/i, '')
|
||||
return `SMTP 25 端口 STARTTLS 投递失败:${detail}`
|
||||
}
|
||||
if (/^SMTPS on 587 Send Error\.\s*(.*)$/i.test(trimmed)) {
|
||||
const detail = trimmed.replace(/^SMTPS on 587 Send Error\.\s*/i, '')
|
||||
return `SMTP 587 端口投递失败:${detail}`
|
||||
}
|
||||
if (/^SMTPS on 465 Send Error\.\s*(.*)$/i.test(trimmed)) {
|
||||
const detail = trimmed.replace(/^SMTPS on 465 Send Error\.\s*/i, '')
|
||||
return `SMTP 465 端口投递失败:${detail}`
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
export function friendlyActionText(action) {
|
||||
if (!action) return '历史运行事件'
|
||||
const known = {
|
||||
'运行事件 · imap_server.(*serverSession).Login': 'IMAP 客户端登录',
|
||||
'运行事件 · imap_server.(*serverSession).Close': 'IMAP 断开连接',
|
||||
'运行事件 · imap_server.(*serverSession).Select': 'IMAP 选择邮箱',
|
||||
'运行事件 · imap_server.(*serverSession).Fetch': 'IMAP 获取邮件',
|
||||
'运行事件 · imap_server.(*serverSession).Append': 'IMAP 追加邮件',
|
||||
'运行事件 · imap_server.(*serverSession).Delete': 'IMAP 删除邮箱',
|
||||
'运行事件 · pop3_server.action.Pass': 'POP3 客户端登录',
|
||||
'运行事件 · pop3_server.action.Retr': 'POP3 获取邮件',
|
||||
'运行事件 · smtp_server.(*Session).AuthPlain': 'SMTP 客户端认证',
|
||||
'运行事件 · send.doSend': 'SMTP 邮件投递',
|
||||
'运行事件 · send.doSend.func2': 'SMTP 邮件投递',
|
||||
'运行事件 · send.Send': '发送邮件'
|
||||
}
|
||||
if (known[action]) return known[action]
|
||||
|
||||
const m = action.match(/^运行事件\s*·\s*([a-zA-Z0-9_]+)\.(?:\(\*?[a-zA-Z0-9_]+\)\.)?([a-zA-Z0-9_]+)(?:\.func\d+)?$/)
|
||||
if (m) {
|
||||
const pkg = m[1]
|
||||
const fn = m[2]
|
||||
const pkgLabel = {
|
||||
imap_server: 'IMAP 服务',
|
||||
pop3_server: 'POP3 服务',
|
||||
smtp_server: 'SMTP 服务',
|
||||
send: '邮件投递',
|
||||
controllers: '接口处理',
|
||||
services: '系统服务',
|
||||
res_init: '系统初始化',
|
||||
hooks: '插件钩子',
|
||||
adminreset: '超级管理'
|
||||
}[pkg] || pkg
|
||||
return `${pkgLabel} · ${fn}`
|
||||
}
|
||||
return action
|
||||
}
|
||||
|
||||
// 只识别已知的日志头;未知格式原样展示,不丢弃记录或猜测级别。
|
||||
export function parseRuntimeLine(line, sequence) {
|
||||
const raw = String(line ?? '')
|
||||
@@ -67,10 +147,17 @@ export function parseRuntimeLine(line, sequence) {
|
||||
// 旧日志或截断记录保留原文,不能猜测结果。
|
||||
}
|
||||
}
|
||||
const displayMessage = cleanRuntimeMessage(message)
|
||||
const rawAction = event.action || '历史运行事件'
|
||||
const action = friendlyActionText(rawAction)
|
||||
const rawOutcome = event.outcome || content
|
||||
const outcome = friendlyOutcomeText(rawOutcome)
|
||||
|
||||
return {
|
||||
sequence, raw, createdAt, level, source, sourceShort, requestId, message, summary,
|
||||
action: event.action || '历史运行事件', result: event.result || 'unknown',
|
||||
object: event.object || event.section || '', outcome: event.outcome || content,
|
||||
sequence, raw, createdAt, level, source, sourceShort, requestId,
|
||||
message: displayMessage, summary,
|
||||
action, result: event.result || 'unknown',
|
||||
object: event.object || event.section || '', outcome,
|
||||
...timeParts(createdAt), ...levels[level]
|
||||
}
|
||||
}
|
||||
@@ -90,4 +177,4 @@ export function formatFileSize(value) {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
}
|
||||
@@ -40,8 +40,8 @@
|
||||
<p v-else class="settings-desc">密保问题不能单独重置密码,必须与离线恢复码组合使用。</p>
|
||||
</div>
|
||||
<el-form :model="questionForm" label-position="top" class="settings-form">
|
||||
<el-form-item label="密保问题"><el-input v-model="questionForm.question" maxlength="128" placeholder="例如:我最喜欢的颜色是什么?" /></el-form-item>
|
||||
<el-form-item label="密保答案"><el-input v-model="questionForm.answer" type="password" show-password maxlength="256" placeholder="请输入答案,保存后不会回显" /></el-form-item>
|
||||
<el-form-item label="密保问题"><el-input v-model="questionForm.question" placeholder="例如:我最喜欢的颜色是什么?" /></el-form-item>
|
||||
<el-form-item label="密保答案"><el-input v-model="questionForm.answer" type="password" show-password placeholder="请输入答案,保存后不会回显" /></el-form-item>
|
||||
<div class="form-actions"><el-button type="primary" @click="saveSecurityQuestion">{{ securityQuestion.configured ? '更新密保问题' : '设置密保问题' }}</el-button></div>
|
||||
</el-form>
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import urllib.request, urllib.parse, hmac, hashlib, base64, time, json, paramiko, subprocess
|
||||
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect('47.108.78.12', port=22, username='root', password='10102442Lb!', timeout=10)
|
||||
stdin, stdout, stderr = client.exec_command('cat /opt/smail/ssl/dkim/dkim.priv')
|
||||
priv_key = stdout.read().decode('utf-8')
|
||||
client.close()
|
||||
|
||||
p = subprocess.Popen(['openssl', 'rsa', '-pubout', '-outform', 'PEM'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
out, err = p.communicate(input=priv_key.encode('utf-8'))
|
||||
pub_lines = [line.strip() for line in out.decode('utf-8').splitlines() if '---' not in line and line.strip()]
|
||||
dkim_pub = ''.join(pub_lines)
|
||||
dkim_val = 'v=DKIM1; k=rsa; p=' + dkim_pub
|
||||
print('DKIM Value:', dkim_val)
|
||||
|
||||
dmarc_val = 'v=DMARC1; p=quarantine; rua=mailto:admin@solit.cn'
|
||||
print('DMARC Value:', dmarc_val)
|
||||
|
||||
ak = 'LTAI5t5ihQv8vf7jS4CNKThu'
|
||||
sk = 'zzJODyPWOInEnI8ueQVPLNw2HzbfKx'
|
||||
|
||||
def aliyun_request(params):
|
||||
public_params = {
|
||||
'Format': 'JSON',
|
||||
'Version': '2015-01-09',
|
||||
'AccessKeyId': ak,
|
||||
'SignatureMethod': 'HMAC-SHA1',
|
||||
'Timestamp': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
|
||||
'SignatureVersion': '1.0',
|
||||
'SignatureNonce': str(int(time.time()*1000)),
|
||||
}
|
||||
all_params = {**public_params, **params}
|
||||
sorted_params = sorted(all_params.items())
|
||||
query_str = urllib.parse.urlencode(sorted_params)
|
||||
str_to_sign = 'GET' + chr(38) + '%2F' + chr(38) + urllib.parse.quote(query_str, safe='')
|
||||
h = hmac.new((sk + chr(38)).encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha1)
|
||||
signature = base64.b64encode(h.digest()).decode('utf-8')
|
||||
all_params['Signature'] = signature
|
||||
url = 'https://alidns.aliyuncs.com/?' + urllib.parse.urlencode(all_params)
|
||||
req = urllib.request.Request(url)
|
||||
with urllib.request.urlopen(req) as response:
|
||||
return json.loads(response.read().decode('utf-8'))
|
||||
|
||||
records = aliyun_request({'Action': 'DescribeDomainRecords', 'DomainName': 'solit.cn', 'PageSize': 50})
|
||||
existing = { (r.get('RR'), r.get('Type')): r.get('RecordId') for r in records.get('DomainRecords', {}).get('Record', []) }
|
||||
print('Existing RRs:', list(existing.keys()))
|
||||
|
||||
if ('_dmarc', 'TXT') not in existing:
|
||||
print('Adding _dmarc...')
|
||||
res = aliyun_request({
|
||||
'Action': 'AddDomainRecord',
|
||||
'DomainName': 'solit.cn',
|
||||
'RR': '_dmarc',
|
||||
'Type': 'TXT',
|
||||
'Value': dmarc_val,
|
||||
'TTL': 600
|
||||
})
|
||||
print('Added _dmarc result:', res)
|
||||
else:
|
||||
print('_dmarc already exists')
|
||||
|
||||
if ('default._domainkey', 'TXT') not in existing:
|
||||
print('Adding default._domainkey...')
|
||||
res = aliyun_request({
|
||||
'Action': 'AddDomainRecord',
|
||||
'DomainName': 'solit.cn',
|
||||
'RR': 'default._domainkey',
|
||||
'Type': 'TXT',
|
||||
'Value': dkim_val,
|
||||
'TTL': 600
|
||||
})
|
||||
print('Added default._domainkey result:', res)
|
||||
else:
|
||||
print('default._domainkey already exists')
|
||||
@@ -0,0 +1,62 @@
|
||||
import urllib.request, urllib.parse, hmac, hashlib, base64, time, json
|
||||
|
||||
ak = 'LTAI5t5ihQv8vf7jS4CNKThu'
|
||||
sk = 'zzJODyPWOInEnI8ueQVPLNw2HzbfKx'
|
||||
|
||||
def aliyun_request(params):
|
||||
public_params = {
|
||||
'Format': 'JSON',
|
||||
'Version': '2015-01-09',
|
||||
'AccessKeyId': ak,
|
||||
'SignatureMethod': 'HMAC-SHA1',
|
||||
'Timestamp': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
|
||||
'SignatureVersion': '1.0',
|
||||
'SignatureNonce': str(int(time.time()*1000)),
|
||||
}
|
||||
all_params = {**public_params, **params}
|
||||
sorted_params = sorted(all_params.items())
|
||||
query_str = urllib.parse.urlencode(sorted_params)
|
||||
str_to_sign = 'GET&%2F&' + urllib.parse.quote(query_str, safe='')
|
||||
h = hmac.new((sk + '&').encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha1)
|
||||
signature = base64.b64encode(h.digest()).decode('utf-8')
|
||||
all_params['Signature'] = signature
|
||||
url = 'https://alidns.aliyuncs.com/?' + urllib.parse.urlencode(all_params)
|
||||
req = urllib.request.Request(url)
|
||||
try:
|
||||
with urllib.request.urlopen(req) as response:
|
||||
return json.loads(response.read().decode('utf-8'))
|
||||
except urllib.error.HTTPError as e:
|
||||
print('Aliyun error body:', e.read().decode('utf-8'))
|
||||
raise e
|
||||
|
||||
dkim_pub = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm1F4k0SRUf0aAkIAJewM/oNzARx0XJjCXbA+HZNpqWg0rFpmGzNUsdXaD6Lw3VGok9P2JaE2t8wQxdIqZGX8f1WjXSEYkN2jv4mY2MTECy4Git8gwlwgXG4oBNcfdQ4MXJj+5YYRuqxAZPKhVoJgWbZwpHWmgdoKIoPHJVBRZQ00+K18WqYJC+kXQYGiB6+ztbYIhlZlvgoaPcvApMJE7TdhCulHKSG0DSz+lX4GaYzxGUZuGgKIb5lUBeatSsKsM8WH2eNG2NP+zS/HIdWsppkUh6u4m8V+8K3ieMENPxOsAJ9DSg1GFtCf1WU7KqTmUeQsApZOxbaHWn0W+6nfjwIDAQAB'
|
||||
dkim_val = 'v=DKIM1; k=rsa; p=' + dkim_pub
|
||||
dmarc_val = 'v=DMARC1; p=quarantine; rua=mailto:admin@solit.cn'
|
||||
|
||||
records = aliyun_request({'Action': 'DescribeDomainRecords', 'DomainName': 'solit.cn', 'PageSize': 50})
|
||||
existing = { (r.get('RR'), r.get('Type')): r.get('RecordId') for r in records.get('DomainRecords', {}).get('Record', []) }
|
||||
print('Existing RRs:', list(existing.keys()))
|
||||
|
||||
if ('_dmarc', 'TXT') not in existing:
|
||||
print('Adding _dmarc...')
|
||||
res = aliyun_request({
|
||||
'Action': 'AddDomainRecord',
|
||||
'DomainName': 'solit.cn',
|
||||
'RR': '_dmarc',
|
||||
'Type': 'TXT',
|
||||
'Value': dmarc_val,
|
||||
'TTL': 600
|
||||
})
|
||||
print('Added _dmarc result:', res)
|
||||
|
||||
if ('default._domainkey', 'TXT') not in existing:
|
||||
print('Adding default._domainkey...')
|
||||
res = aliyun_request({
|
||||
'Action': 'AddDomainRecord',
|
||||
'DomainName': 'solit.cn',
|
||||
'RR': 'default._domainkey',
|
||||
'Type': 'TXT',
|
||||
'Value': dkim_val,
|
||||
'TTL': 600
|
||||
})
|
||||
print('Added default._domainkey result:', res)
|
||||
@@ -0,0 +1,62 @@
|
||||
import urllib.request, urllib.parse, hmac, hashlib, base64, time, json
|
||||
|
||||
ak = 'LTAI5t5ihQv8vf7jS4CNKThu'
|
||||
sk = 'zzJODyPWOInEnI8ueQVPLNw2HzbfKx'
|
||||
|
||||
def percent_encode(val):
|
||||
res = urllib.parse.quote(str(val), safe='')
|
||||
res = res.replace('+', '%20')
|
||||
res = res.replace('*', '%2A')
|
||||
res = res.replace('%7E', '~')
|
||||
return res
|
||||
|
||||
def aliyun_request(params):
|
||||
public_params = {
|
||||
'Format': 'JSON',
|
||||
'Version': '2015-01-09',
|
||||
'AccessKeyId': ak,
|
||||
'SignatureMethod': 'HMAC-SHA1',
|
||||
'Timestamp': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
|
||||
'SignatureVersion': '1.0',
|
||||
'SignatureNonce': str(int(time.time()*1000)),
|
||||
}
|
||||
all_params = {**public_params, **params}
|
||||
sorted_params = sorted(all_params.items(), key=lambda x: x[0])
|
||||
query_str = '&'.join([f'{percent_encode(k)}={percent_encode(v)}' for k, v in sorted_params])
|
||||
str_to_sign = 'GET&%2F&' + percent_encode(query_str)
|
||||
h = hmac.new((sk + '&').encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha1)
|
||||
signature = base64.b64encode(h.digest()).decode('utf-8')
|
||||
final_url = f'https://alidns.aliyuncs.com/?{query_str}&Signature={percent_encode(signature)}'
|
||||
req = urllib.request.Request(final_url)
|
||||
try:
|
||||
with urllib.request.urlopen(req) as response:
|
||||
return json.loads(response.read().decode('utf-8'))
|
||||
except urllib.error.HTTPError as e:
|
||||
print('HTTP Error body:', e.read().decode('utf-8'))
|
||||
raise e
|
||||
|
||||
dkim_pub = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm1F4k0SRUf0aAkIAJewM/oNzARx0XJjCXbA+HZNpqWg0rFpmGzNUsdXaD6Lw3VGok9P2JaE2t8wQxdIqZGX8f1WjXSEYkN2jv4mY2MTECy4Git8gwlwgXG4oBNcfdQ4MXJj+5YYRuqxAZPKhVoJgWbZwpHWmgdoKIoPHJVBRZQ00+K18WqYJC+kXQYGiB6+ztbYIhlZlvgoaPcvApMJE7TdhCulHKSG0DSz+lX4GaYzxGUZuGgKIb5lUBeatSsKsM8WH2eNG2NP+zS/HIdWsppkUh6u4m8V+8K3ieMENPxOsAJ9DSg1GFtCf1WU7KqTmUeQsApZOxbaHWn0W+6nfjwIDAQAB'
|
||||
dkim_val = 'v=DKIM1; k=rsa; p=' + dkim_pub
|
||||
dmarc_val = 'v=DMARC1; p=quarantine; rua=mailto:admin@solit.cn'
|
||||
|
||||
print('--- 添加 _dmarc ---')
|
||||
res_dmarc = aliyun_request({
|
||||
'Action': 'AddDomainRecord',
|
||||
'DomainName': 'solit.cn',
|
||||
'RR': '_dmarc',
|
||||
'Type': 'TXT',
|
||||
'Value': dmarc_val,
|
||||
'TTL': 600
|
||||
})
|
||||
print('Success:', res_dmarc)
|
||||
|
||||
print('--- 添加 default._domainkey ---')
|
||||
res_dkim = aliyun_request({
|
||||
'Action': 'AddDomainRecord',
|
||||
'DomainName': 'solit.cn',
|
||||
'RR': 'default._domainkey',
|
||||
'Type': 'TXT',
|
||||
'Value': dkim_val,
|
||||
'TTL': 600
|
||||
})
|
||||
print('Success:', res_dkim)
|
||||
@@ -0,0 +1,35 @@
|
||||
import urllib.request, urllib.parse, hmac, hashlib, base64, time, json
|
||||
|
||||
ak = 'LTAI5t5ihQv8vf7jS4CNKThu'
|
||||
sk = 'zzJODyPWOInEnI8ueQVPLNw2HzbfKx'
|
||||
|
||||
def aliyun_request(params):
|
||||
public_params = {
|
||||
'Format': 'JSON',
|
||||
'Version': '2015-01-09',
|
||||
'AccessKeyId': ak,
|
||||
'SignatureMethod': 'HMAC-SHA1',
|
||||
'Timestamp': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
|
||||
'SignatureVersion': '1.0',
|
||||
'SignatureNonce': str(int(time.time()*1000)),
|
||||
}
|
||||
all_params = {**public_params, **params}
|
||||
sorted_params = sorted(all_params.items())
|
||||
query_str = urllib.parse.urlencode(sorted_params)
|
||||
str_to_sign = 'GET&%2F&' + urllib.parse.quote(query_str, safe='')
|
||||
h = hmac.new((sk + '&').encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha1)
|
||||
signature = base64.b64encode(h.digest()).decode('utf-8')
|
||||
all_params['Signature'] = signature
|
||||
url = 'https://alidns.aliyuncs.com/?' + urllib.parse.urlencode(all_params)
|
||||
req = urllib.request.Request(url)
|
||||
with urllib.request.urlopen(req) as response:
|
||||
return json.loads(response.read().decode('utf-8'))
|
||||
|
||||
records = aliyun_request({'Action': 'DescribeDomainRecords', 'DomainName': 'solit.cn', 'PageSize': 50})
|
||||
print('Total records in solit.cn:', records.get('TotalCount'))
|
||||
for r in records.get('DomainRecords', {}).get('Record', []):
|
||||
rr = r.get('RR')
|
||||
t = r.get('Type')
|
||||
v = r.get('Value')
|
||||
s = r.get('Status')
|
||||
print(f'{rr:<22} | {t:<6} | {s:<8} | {v}')
|
||||
@@ -0,0 +1,26 @@
|
||||
import paramiko
|
||||
|
||||
ssh = paramiko.SSHClient()
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
ssh.connect("47.108.78.12", port=22, username="root", password="10102442Lb!")
|
||||
|
||||
sftp = ssh.open_sftp()
|
||||
with sftp.open("/tmp/test_api.py", "w") as f:
|
||||
f.write("""import requests
|
||||
s = requests.Session()
|
||||
r = s.post('http://127.0.0.1/api/login', json={'account': 'xuans', 'password': '12345678'}, headers={'Content-Type': 'application/json'})
|
||||
print('LOGIN:', r.status_code, r.text)
|
||||
print('COOKIES:', s.cookies.get_dict())
|
||||
|
||||
r2 = s.get('http://127.0.0.1/api/v1/config/status')
|
||||
print('CONFIG_STATUS:', r2.status_code, r2.text)
|
||||
|
||||
r3 = s.get('http://127.0.0.1/api/v1/config/section/ssl')
|
||||
print('SSL_SECTION:', r3.status_code, r3.text)
|
||||
""")
|
||||
sftp.close()
|
||||
|
||||
stdin, stdout, stderr = ssh.exec_command("python3 /tmp/test_api.py")
|
||||
print("STDOUT:\n", stdout.read().decode('utf-8'))
|
||||
print("STDERR:\n", stderr.read().decode('utf-8'))
|
||||
ssh.close()
|
||||
@@ -0,0 +1,60 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os, sys
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(2500)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/editer', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# 打印页面上的 sender 相关信息
|
||||
sender_text = page.locator('.sender-selector').inner_text()
|
||||
print('Sender text:', repr(sender_text))
|
||||
|
||||
# 尝试用正确的选择器选 input
|
||||
input_elem = page.locator('.border-less-select input').first
|
||||
input_elem.click()
|
||||
page.keyboard.type('testuser2@solit.cn')
|
||||
page.wait_for_timeout(500)
|
||||
page.keyboard.press('Enter')
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
tags = page.locator('.border-less-select .el-tag')
|
||||
print('Tags after typing & Enter:', tags.count())
|
||||
if tags.count() > 0:
|
||||
print('Tag content:', tags.first.inner_text())
|
||||
|
||||
# 填写主题
|
||||
page.locator('.subject-row input').fill('自动化验证测试邮件')
|
||||
|
||||
# 填写正文
|
||||
page.locator('.editor-content').click()
|
||||
page.keyboard.type('正文内容...')
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
page.locator('.send-btn').click()
|
||||
page.wait_for_timeout(1000)
|
||||
|
||||
errors = page.locator('.el-form-item__error')
|
||||
print('Form errors count:', errors.count())
|
||||
for i in range(errors.count()):
|
||||
print('Error', i, ':', errors.nth(i).inner_text())
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,43 @@
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_log_dir = os.path.join(os.getcwd(), 'test-log', 'debug-login')
|
||||
os.makedirs(test_log_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=False, slow_mo=600, args=['--start-maximized', '--ignore-certificate-errors'])
|
||||
context = browser.new_context(viewport=None, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.on('console', lambda msg: print('[CONSOLE]', msg.type, msg.text))
|
||||
page.on('pageerror', lambda exc: print('[PAGE ERROR]', exc))
|
||||
|
||||
def on_res(res):
|
||||
try:
|
||||
print('[RES]', res.status, res.url, res.text()[:150])
|
||||
except Exception:
|
||||
print('[RES]', res.status, res.url)
|
||||
page.on('response', on_res)
|
||||
|
||||
page.goto('https://47.108.78.12/#/login', wait_until='networkidle')
|
||||
time.sleep(2)
|
||||
|
||||
acc = page.locator('.login-content input').nth(0)
|
||||
pwd = page.locator('.login-content input').nth(1)
|
||||
acc.fill('xuans')
|
||||
pwd.fill('12345678')
|
||||
time.sleep(1)
|
||||
|
||||
btn = page.locator('button.login-btn')
|
||||
btn.click()
|
||||
|
||||
time.sleep(4)
|
||||
# 检查所有 el-message
|
||||
messages = page.locator('.el-message')
|
||||
print('El-Messages count:', messages.count())
|
||||
for i in range(messages.count()):
|
||||
print(f'Msg {i}: {messages.nth(i).inner_text()}')
|
||||
|
||||
page.screenshot(path=os.path.join(test_log_dir, '04_detailed.png'))
|
||||
time.sleep(3)
|
||||
browser.close()
|
||||
@@ -0,0 +1,59 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.on('response', lambda res: print('[API RES]', res.status, res.url, res.text()[:200]) if 'email' in res.url or 'send' in res.url else None)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/editer', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# 填写收件人
|
||||
to_input = page.locator('.border-less-select input').first
|
||||
to_input.click()
|
||||
to_input.fill('testuser2@solit.cn')
|
||||
page.wait_for_timeout(500)
|
||||
# 模拟键盘回车和下拉项选择
|
||||
page.keyboard.press('Enter')
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
# 填写主题
|
||||
subject_input = page.locator('.subject-row input')
|
||||
subject_input.fill('全量测试主题')
|
||||
|
||||
# 填写正文
|
||||
editor = page.locator('.editor-content')
|
||||
editor.click()
|
||||
page.keyboard.type('测试内容123')
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
# 查看当前表单绑定的数据
|
||||
tags = page.locator('.el-select__tags-text, .el-tag')
|
||||
print('已选收件人标签数量:', tags.count())
|
||||
for i in range(tags.count()):
|
||||
print('Tag:', tags.nth(i).inner_text())
|
||||
|
||||
# 点击发送
|
||||
print('点击发送...')
|
||||
page.locator('.send-btn').click()
|
||||
page.wait_for_timeout(4000)
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,9 @@
|
||||
import paramiko
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect('47.108.78.12', port=22, username='root', password='10102442Lb!', timeout=10)
|
||||
cmd = 'openssl rsa -in /opt/smail/ssl/dkim/dkim.priv -pubout -outform PEM'
|
||||
stdin, stdout, stderr = client.exec_command(cmd)
|
||||
lines = [l.strip() for l in stdout.read().decode('utf-8').splitlines() if '---' not in l and l.strip()]
|
||||
print(''.join(lines))
|
||||
client.close()
|
||||
@@ -0,0 +1,79 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os, sys
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
output_dir = os.path.join(os.getcwd(), 'test-log', 'acceptance_contact_security')
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
# 1. 登录
|
||||
print('--- Step 1: Login ---')
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(2500)
|
||||
page.screenshot(path=os.path.join(output_dir, '01_logged_in.png'))
|
||||
print('Logged in, URL:', page.url)
|
||||
|
||||
# 2. 验证收件箱安全提示
|
||||
print('--- Step 2: Inbox Security Tags ---')
|
||||
page.goto('https://mail.solit.cn/#/list?tag=0', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(output_dir, '02_inbox_list.png'))
|
||||
|
||||
danger_tags = page.locator('.mail-status-tags .el-tag--danger')
|
||||
print('Inbox danger tag count:', danger_tags.count())
|
||||
for i in range(danger_tags.count()):
|
||||
print('Danger tag text:', danger_tags.nth(i).inner_text())
|
||||
|
||||
# 3. 验证发件箱状态标签与错误详情
|
||||
print('--- Step 3: Outbox Status Tags & Error Dialog ---')
|
||||
page.goto('https://mail.solit.cn/#/list?tag=1', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(output_dir, '03_outbox_list.png'))
|
||||
success_tags = page.locator('.mail-status-tags .el-tag--success')
|
||||
fail_tags = page.locator('.mail-status-tags .el-tag--danger')
|
||||
print('Outbox success tag count:', success_tags.count())
|
||||
print('Outbox fail tag count:', fail_tags.count())
|
||||
|
||||
if fail_tags.count() > 0:
|
||||
print('Clicking fail tag...')
|
||||
fail_tags.first.click()
|
||||
page.wait_for_timeout(1000)
|
||||
page.screenshot(path=os.path.join(output_dir, '04_outbox_error_dialog.png'))
|
||||
close_btn = page.locator('.el-dialog button')
|
||||
if close_btn.count() > 0:
|
||||
close_btn.first.click()
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
# 4. 验证写信页联系人
|
||||
print('--- Step 4: Editer Page Contacts ---')
|
||||
page.goto('https://mail.solit.cn/#/editer', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(output_dir, '05_editer_page.png'))
|
||||
|
||||
select_input = page.locator('.border-less-select')
|
||||
select_input.click()
|
||||
page.wait_for_timeout(800)
|
||||
page.screenshot(path=os.path.join(output_dir, '06_editer_contacts_dropdown.png'))
|
||||
|
||||
dropdown_items = page.locator('.el-select-dropdown__item')
|
||||
print('Dropdown items count:', dropdown_items.count())
|
||||
for i in range(dropdown_items.count()):
|
||||
print('Item:', dropdown_items.nth(i).inner_text())
|
||||
|
||||
browser.close()
|
||||
print('Acceptance check finished.')
|
||||
@@ -0,0 +1,71 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_dir = os.path.join(os.getcwd(), 'test-log', 'config_verification_suite')
|
||||
os.makedirs(test_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
page.locator('.settings-btn').click()
|
||||
page.wait_for_timeout(1500)
|
||||
page.locator('#tab-config').click()
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# List all buttons in .config-navigation
|
||||
btns = page.locator('.config-navigation button')
|
||||
print('Navigation buttons count:', btns.count())
|
||||
for i in range(btns.count()):
|
||||
text = btns.nth(i).inner_text().strip().replace(chr(10), ' ')
|
||||
print(f'Btn {i}: {text}')
|
||||
|
||||
# Click Email Config
|
||||
if btns.count() > 1:
|
||||
btns.nth(1).click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '03_config_mail.png'))
|
||||
|
||||
# Click SSL Config
|
||||
if btns.count() > 2:
|
||||
btns.nth(2).click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '04_config_ssl.png'))
|
||||
|
||||
# Test Plugins tab in settings
|
||||
page.locator('#tab-plugins').click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '05_plugins.png'))
|
||||
|
||||
# Test Users tab in settings
|
||||
page.locator('#tab-users').click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '06_users.png'))
|
||||
|
||||
# Test Logs tab in settings
|
||||
page.locator('#tab-logs').click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '07_logs.png'))
|
||||
|
||||
# Test Security tab in settings
|
||||
page.locator('#tab-security').click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '08_security.png'))
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,44 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_dir = os.path.join(os.getcwd(), 'test-log', 'config_verification_suite')
|
||||
os.makedirs(test_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
page.locator('.settings-btn').click()
|
||||
page.wait_for_timeout(1500)
|
||||
page.screenshot(path=os.path.join(test_dir, '01_settings_drawer.png'))
|
||||
|
||||
items = page.locator('.el-tabs__item')
|
||||
print('Tabs count:', items.count())
|
||||
for i in range(items.count()):
|
||||
text = items.nth(i).inner_text().replace(chr(10), ' ')
|
||||
print(f'Tab {i}: {text}')
|
||||
|
||||
config_tab = page.locator('#tab-config')
|
||||
print('Config tab count:', config_tab.count())
|
||||
if config_tab.count() > 0:
|
||||
config_tab.click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '02_config_base.png'))
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,90 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os, sys
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
output_dir = os.path.join(os.getcwd(), 'test-log', 'acceptance_contact_security')
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
# 1. 登录 xuans
|
||||
print('1. 登录 xuans...')
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(2500)
|
||||
|
||||
# 2. 检查收件箱中的信任发件人交互
|
||||
print('2. 检查收件箱信任操作...')
|
||||
page.goto('https://mail.solit.cn/#/list?tag=0', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
danger_tags = page.locator('.mail-status-tags .el-tag--danger')
|
||||
print('当前收件箱疑似不安全标签数量:', danger_tags.count())
|
||||
if danger_tags.count() > 0:
|
||||
print('点击第一个不安全标签...')
|
||||
danger_tags.first.click()
|
||||
page.wait_for_timeout(500)
|
||||
page.screenshot(path=os.path.join(output_dir, '30_trust_sender_confirm_box.png'))
|
||||
|
||||
confirm_btn = page.locator('.el-message-box .el-button--primary')
|
||||
print('确认按钮数量:', confirm_btn.count())
|
||||
confirm_btn.click()
|
||||
page.wait_for_timeout(1500)
|
||||
page.screenshot(path=os.path.join(output_dir, '31_after_trusted.png'))
|
||||
|
||||
# 3. 检查发件箱标签
|
||||
print('3. 检查发件箱...')
|
||||
page.goto('https://mail.solit.cn/#/list?tag=%7B%22type%22%3A1%2C%22status%22%3A-1%7D', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(output_dir, '32_outbox_view.png'))
|
||||
|
||||
# 4. 进入写信页,测试删除联系人
|
||||
print('4. 写信页测试删除联系人...')
|
||||
page.goto('https://mail.solit.cn/#/editer', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
wrapper = page.locator('.border-less-select .el-select__wrapper')
|
||||
wrapper.click()
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
del_icon = page.locator('.contact-del-icon:visible')
|
||||
print('删除图标数量:', del_icon.count())
|
||||
if del_icon.count() > 0:
|
||||
del_icon.first.click()
|
||||
page.wait_for_timeout(1000)
|
||||
page.screenshot(path=os.path.join(output_dir, '33_after_delete_contact.png'))
|
||||
|
||||
# 5. 验证多租户隔离:登录 testuser2
|
||||
print('5. 验证多租户隔离...')
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('testuser2')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(2500)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/editer', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
wrapper = page.locator('.border-less-select .el-select__wrapper')
|
||||
wrapper.click()
|
||||
page.wait_for_timeout(500)
|
||||
page.screenshot(path=os.path.join(output_dir, '34_testuser2_contacts_dropdown.png'))
|
||||
user2_items = page.locator('.el-select-dropdown__item:visible')
|
||||
print('testuser2 联系人下拉选项数:', user2_items.count())
|
||||
|
||||
browser.close()
|
||||
print('验收流程全部执行完毕!')
|
||||
@@ -0,0 +1,41 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_dir = os.path.join(os.getcwd(), 'test-log', 'mail_flow_suite')
|
||||
os.makedirs(test_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.on('response', lambda res: print('[API]', res.status, res.url, res.text()[:250]) if 'email' in res.url or 'group' in res.url else None)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
# 打印菜单项
|
||||
menu_items = page.locator('.sidebar-menu .el-menu-item')
|
||||
print('侧边栏菜单项数:', menu_items.count())
|
||||
for i in range(menu_items.count()):
|
||||
print(f'Menu {i}:', menu_items.nth(i).inner_text().strip())
|
||||
|
||||
# 点击发件箱 / 已发送
|
||||
if menu_items.count() > 1:
|
||||
menu_items.nth(1).click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '25_outbox_clicked.png'))
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,59 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_dir = os.path.join(os.getcwd(), 'test-log', 'log_audit_suite')
|
||||
os.makedirs(test_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.on('response', lambda res: print('[API]', res.status, res.url) if 'log' in res.url or 'audit' in res.url else None)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
# 打开设置抽屉
|
||||
page.locator('.settings-btn').click()
|
||||
page.wait_for_timeout(1500)
|
||||
page.locator('#tab-logs').click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '01_logs_overview.png'))
|
||||
|
||||
# 查看日志页面中的子菜单/选项卡
|
||||
log_tabs = page.locator('.log-settings button, .settings-submenu-item')
|
||||
print('日志导航选项数量:', log_tabs.count())
|
||||
for i in range(log_tabs.count()):
|
||||
t = log_tabs.nth(i).inner_text().strip().replace('\n', ' ')
|
||||
print(f'Tab {i}: {t}')
|
||||
|
||||
# 查看运行日志表格
|
||||
rows = page.locator('.el-table__row')
|
||||
print('当前日志行数:', rows.count())
|
||||
for i in range(min(5, rows.count())):
|
||||
print(f'Row {i}:', rows.nth(i).inner_text().replace('\n', ' | '))
|
||||
|
||||
# 切换子菜单查看操作日志和收发信日志(如果有)
|
||||
if log_tabs.count() > 1:
|
||||
log_tabs.nth(1).click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '02_log_subtab1.png'))
|
||||
if log_tabs.count() > 2:
|
||||
log_tabs.nth(2).click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '03_log_subtab2.png'))
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,69 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_dir = os.path.join(os.getcwd(), 'test-log', 'log_audit_suite')
|
||||
os.makedirs(test_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
# 打开设置抽屉并进入日志
|
||||
page.locator('.settings-btn').click()
|
||||
page.wait_for_timeout(1500)
|
||||
page.locator('#tab-logs').click()
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# 查看三大单选按钮
|
||||
radio_btns = page.locator('.log-categories .el-radio-button')
|
||||
print('单选按钮数量:', radio_btns.count())
|
||||
for i in range(radio_btns.count()):
|
||||
print(f'Radio {i}:', radio_btns.nth(i).inner_text())
|
||||
|
||||
# 1. 点击“运行日志”
|
||||
run_btn = page.locator('.log-categories .el-radio-button:has-text("运行日志")')
|
||||
if run_btn.count() > 0:
|
||||
run_btn.click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '10_runtime_logs.png'))
|
||||
|
||||
# 点击第一条运行日志的“查看”按钮
|
||||
view_btn = page.locator('.runtime-table .el-button--primary').first
|
||||
if view_btn.count() > 0:
|
||||
view_btn.click()
|
||||
page.wait_for_timeout(1000)
|
||||
page.screenshot(path=os.path.join(test_dir, '11_runtime_detail_dialog.png'))
|
||||
# 关闭弹窗
|
||||
page.keyboard.press('Escape')
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
# 2. 点击“收发信日志”
|
||||
mail_btn = page.locator('.log-categories .el-radio-button:has-text("收发")')
|
||||
if mail_btn.count() > 0:
|
||||
mail_btn.click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '20_mail_logs.png'))
|
||||
|
||||
# 检查刚刚发送邮件的收发信日志
|
||||
rows = page.locator('.log-table .el-table__row')
|
||||
print('收发信日志行数:', rows.count())
|
||||
for i in range(min(5, rows.count())):
|
||||
print(f'Mail Log {i}:', rows.nth(i).inner_text().replace('\n', ' | '))
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,38 @@
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_log_dir = os.path.join(os.getcwd(), "test-log", "login-and-dashboard-v2")
|
||||
os.makedirs(test_log_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
print("鍚姩鍙鍖栫湡瀹炴祻瑙堝櫒...")
|
||||
browser = p.chromium.launch(
|
||||
headless=False,
|
||||
slow_mo=800,
|
||||
args=["--start-maximized", "--no-sandbox", "--ignore-certificate-errors"]
|
||||
)
|
||||
context = browser.new_context(viewport=None, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
print("璁块棶鐧诲綍椤? https://47.108.78.12/#/login")
|
||||
page.goto("https://47.108.78.12/#/login", wait_until="networkidle")
|
||||
time.sleep(2)
|
||||
page.screenshot(path=os.path.join(test_log_dir, "01_login_page.png"))
|
||||
|
||||
print("杈撳叆绠$悊鍛樿处鍙峰瘑鐮? xuans / 12345678")
|
||||
inputs = page.locator("input")
|
||||
print("杈撳叆妗嗘暟閲?", inputs.count())
|
||||
inputs.nth(0).fill("xuans")
|
||||
inputs.nth(1).fill("12345678")
|
||||
time.sleep(1)
|
||||
page.screenshot(path=os.path.join(test_log_dir, "02_credentials_filled.png"))
|
||||
|
||||
print("鐐瑰嚮鐧诲綍鎸夐挳...")
|
||||
page.locator(".login-btn").click()
|
||||
time.sleep(3)
|
||||
page.screenshot(path=os.path.join(test_log_dir, "03_after_login_action.png"))
|
||||
print("褰撳墠椤甸潰 URL:", page.url)
|
||||
time.sleep(2)
|
||||
page.screenshot(path=os.path.join(test_log_dir, "04_security_dialog_or_dashboard.png"))
|
||||
time.sleep(5)
|
||||
browser.close()
|
||||
@@ -0,0 +1,38 @@
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_log_dir = os.path.join(os.getcwd(), "test-log", "login-and-dashboard-v2")
|
||||
os.makedirs(test_log_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
print("�动�视化真实�览器...")
|
||||
browser = p.chromium.launch(
|
||||
headless=False,
|
||||
slow_mo=800,
|
||||
args=["--start-maximized", "--no-sandbox", "--ignore-certificate-errors"]
|
||||
)
|
||||
context = browser.new_context(viewport=None, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
print("访问登录� https://47.108.78.12/#/login")
|
||||
page.goto("https://47.108.78.12/#/login", wait_until="networkidle")
|
||||
time.sleep(2)
|
||||
page.screenshot(path=os.path.join(test_log_dir, "01_login_page.png"))
|
||||
|
||||
print("输入管ç�†å‘˜è´¦å�·å¯†ç ? xuans / 12345678")
|
||||
inputs = page.locator("input")
|
||||
print("输入框数�", inputs.count())
|
||||
inputs.nth(0).fill("xuans")
|
||||
inputs.nth(1).fill("12345678")
|
||||
time.sleep(1)
|
||||
page.screenshot(path=os.path.join(test_log_dir, "02_credentials_filled.png"))
|
||||
|
||||
print("点击登录按钮...")
|
||||
page.locator("button").filter(has_text="登录").first.click()
|
||||
time.sleep(3)
|
||||
page.screenshot(path=os.path.join(test_log_dir, "03_after_login_action.png"))
|
||||
print("当�页� URL:", page.url)
|
||||
time.sleep(2)
|
||||
page.screenshot(path=os.path.join(test_log_dir, "04_security_dialog_or_dashboard.png"))
|
||||
time.sleep(5)
|
||||
browser.close()
|
||||
@@ -0,0 +1,73 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_dir = os.path.join(os.getcwd(), 'test-log', 'mail_flow_suite')
|
||||
os.makedirs(test_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.on('response', lambda res: print('[API]', res.status, res.url) if 'api' in res.url else None)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
# 查看侧边栏并点击“写邮件”或路由切换到 /editer
|
||||
page.goto('https://mail.solit.cn/#/editer', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '01_editer_page.png'))
|
||||
|
||||
# 查看发件人信息
|
||||
sender_info = page.locator('.sender-selector').inner_text()
|
||||
print('当前发件人展示:', sender_info)
|
||||
|
||||
# 填写收件人
|
||||
# 收件人是一个 el-select 允许输入的
|
||||
to_input = page.locator('.border-less-select input').first
|
||||
to_input.fill('testuser2@solit.cn')
|
||||
page.keyboard.press('Enter')
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
# 填写主题
|
||||
subject_input = page.locator('.subject-row input')
|
||||
subject_input.fill('全量测试验收邮件 - ' + str(int(time.time())))
|
||||
|
||||
# 在富文本编辑器中输入正文
|
||||
editor = page.locator('.editor-content')
|
||||
editor.click()
|
||||
page.keyboard.type('这是一封用于全量功能与发件箱归档测试的真实邮件内容。')
|
||||
page.wait_for_timeout(500)
|
||||
page.screenshot(path=os.path.join(test_dir, '02_mail_filled.png'))
|
||||
|
||||
# 点击发送
|
||||
print('点击发送邮件...')
|
||||
page.locator('.send-btn').click()
|
||||
page.wait_for_timeout(4000)
|
||||
page.screenshot(path=os.path.join(test_dir, '03_after_send.png'))
|
||||
print('当前页面 URL:', page.url)
|
||||
|
||||
# 查看发件箱
|
||||
print('切换至发件箱...')
|
||||
# 查找侧边栏中名为“已发送”或“发件箱”的菜单项
|
||||
outbox_item = page.locator('.sidebar-menu .el-menu-item:has-text("已发送"), .sidebar-menu .el-menu-item:has-text("发件箱")')
|
||||
print('发件箱菜单数量:', outbox_item.count())
|
||||
if outbox_item.count() > 0:
|
||||
outbox_item.first.click()
|
||||
page.wait_for_timeout(2500)
|
||||
page.screenshot(path=os.path.join(test_dir, '04_outbox_list.png'))
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,51 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from playwright.sync_api import sync_playwright
|
||||
import time
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
context = browser.new_context(ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.on("request", lambda req: print("[REQ]", req.method, req.url) if "api" in req.url else None)
|
||||
page.on("response", lambda res: print("[RES]", res.status, res.url, res.text()) if "question" in res.url else None)
|
||||
|
||||
# 登录
|
||||
page.goto("https://mail.solit.cn/#/login")
|
||||
page.wait_for_selector(".login-btn")
|
||||
inputs = page.locator(".login-content input")
|
||||
inputs.nth(0).fill("xuans")
|
||||
inputs.nth(1).fill("12345678")
|
||||
page.locator(".login-btn").click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
# 直接访问设置安全路由
|
||||
page.goto("https://mail.solit.cn/#/setting?tab=security")
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# 查看当前页面按钮和文本
|
||||
print("Page URL:", page.url)
|
||||
|
||||
# 点击密保问题选项卡
|
||||
page.locator(".settings-submenu-item:has-text('密保问题')").click()
|
||||
page.wait_for_timeout(1000)
|
||||
|
||||
q_input = page.locator("input[placeholder*='最喜欢的颜色']")
|
||||
a_input = page.locator("input[placeholder*='请输入答案']")
|
||||
print("q_input visible:", q_input.is_visible())
|
||||
print("a_input visible:", a_input.is_visible())
|
||||
|
||||
# 尝试两字符输入:90 和 12
|
||||
print("--- 测试 1:问题 '90',答案 '12' ---")
|
||||
q_input.fill("90")
|
||||
a_input.fill("12")
|
||||
page.locator("button:has-text('设置密保问题')").click()
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# 尝试8字符输入:90 和 12345678
|
||||
print("--- 测试 2:问题 '90',答案 '12345678' ---")
|
||||
a_input.fill("12345678")
|
||||
page.locator("button:has-text('设置密保问题')").click()
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,65 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_dir = os.path.join(os.getcwd(), 'test-log', 'security_verification_suite')
|
||||
os.makedirs(test_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
page.locator('.settings-btn').click()
|
||||
page.wait_for_timeout(1500)
|
||||
page.locator('#tab-security').click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '01_security_tab.png'))
|
||||
|
||||
# 查找安全中心内所有的按钮或卡片操作
|
||||
btns = page.locator('.settings-drawer button')
|
||||
print('Buttons in settings drawer:', btns.count())
|
||||
for i in range(btns.count()):
|
||||
t = btns.nth(i).inner_text().strip().replace('\n', ' ')
|
||||
if t:
|
||||
print(f'Btn {i}: {t}')
|
||||
|
||||
# 寻找设置密保按钮
|
||||
set_q_btn = page.locator('button:has-text("密保")')
|
||||
print('密保按钮数量:', set_q_btn.count())
|
||||
if set_q_btn.count() > 0:
|
||||
set_q_btn.first.click()
|
||||
page.wait_for_timeout(1500)
|
||||
page.screenshot(path=os.path.join(test_dir, '02_question_dialog.png'))
|
||||
|
||||
dialog = page.locator('.el-dialog')
|
||||
d_inputs = dialog.locator('input')
|
||||
print('弹窗内输入框数量:', d_inputs.count())
|
||||
if d_inputs.count() >= 2:
|
||||
d_inputs.nth(0).fill('幸运数字')
|
||||
d_inputs.nth(1).fill('8')
|
||||
page.wait_for_timeout(500)
|
||||
page.screenshot(path=os.path.join(test_dir, '03_question_filled.png'))
|
||||
|
||||
confirm_btn = dialog.locator('button:has-text("确定"), button:has-text("保存")')
|
||||
print('确定按钮数量:', confirm_btn.count())
|
||||
if confirm_btn.count() > 0:
|
||||
confirm_btn.last.click()
|
||||
page.wait_for_timeout(2500)
|
||||
page.screenshot(path=os.path.join(test_dir, '04_after_question_save.png'))
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,57 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_dir = os.path.join(os.getcwd(), 'test-log', 'security_verification_suite')
|
||||
os.makedirs(test_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
page.locator('.settings-btn').click()
|
||||
page.wait_for_timeout(1500)
|
||||
page.locator('#tab-security').click()
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# 点击左侧子菜单中的“密保问题”
|
||||
question_nav = page.locator('.security-workspace .settings-submenu-item:has-text("密保"), .security-workspace button:has-text("密保")')
|
||||
print('密保菜单数量:', question_nav.count())
|
||||
if question_nav.count() > 0:
|
||||
question_nav.first.click()
|
||||
page.wait_for_timeout(1500)
|
||||
page.screenshot(path=os.path.join(test_dir, '10_security_question_section.png'))
|
||||
|
||||
# 在表单中输入密保问题和 1 位密保答案
|
||||
inputs = page.locator('.security-main input')
|
||||
print('安全主体输入框数量:', inputs.count())
|
||||
if inputs.count() >= 2:
|
||||
inputs.nth(0).fill('幸运数字')
|
||||
inputs.nth(1).fill('8')
|
||||
page.wait_for_timeout(500)
|
||||
page.screenshot(path=os.path.join(test_dir, '11_question_filled_1char.png'))
|
||||
|
||||
# 点击保存/更新密保问题按钮
|
||||
save_btn = page.locator('.security-main button.el-button--primary')
|
||||
print('保存按钮数量:', save_btn.count())
|
||||
if save_btn.count() > 0:
|
||||
save_btn.first.click()
|
||||
page.wait_for_timeout(2500)
|
||||
page.screenshot(path=os.path.join(test_dir, '12_question_saved_result.png'))
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,56 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os, sys
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(2500)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/editer', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# 观察 el-select 结构
|
||||
wrapper = page.locator('.border-less-select .el-select__wrapper')
|
||||
print('Wrapper count:', wrapper.count())
|
||||
wrapper.click()
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
# 打印当前 active 元素或者向页面输入
|
||||
page.keyboard.type('testuser2@solit.cn')
|
||||
page.wait_for_timeout(500)
|
||||
page.screenshot(path='test-log/typing_step1.png')
|
||||
|
||||
# 查看下拉菜单是否有内容
|
||||
dropdown_visible = page.locator('.el-select-dropdown:visible')
|
||||
print('Dropdown visible:', dropdown_visible.count())
|
||||
items = page.locator('.el-select-dropdown__item:visible')
|
||||
print('Dropdown items count:', items.count())
|
||||
for i in range(items.count()):
|
||||
print('Item', i, ':', items.nth(i).inner_text())
|
||||
|
||||
# 按 Enter
|
||||
page.keyboard.press('Enter')
|
||||
page.wait_for_timeout(500)
|
||||
page.screenshot(path='test-log/after_enter.png')
|
||||
|
||||
tags = page.locator('.border-less-select .el-tag')
|
||||
print('Tags after enter:', tags.count())
|
||||
for i in range(tags.count()):
|
||||
print('Tag', i, ':', tags.nth(i).inner_text())
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,70 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os, sys, time
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
output_dir = os.path.join(os.getcwd(), 'test-log', 'acceptance_contact_security')
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
# 登录
|
||||
print('1. 登录 xuans...')
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(2500)
|
||||
|
||||
# 打开写信页
|
||||
print('2. 前往写信页...')
|
||||
page.goto('https://mail.solit.cn/#/editer', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# 填写收件人
|
||||
select_box = page.locator('.border-less-select')
|
||||
select_box.click()
|
||||
page.wait_for_timeout(300)
|
||||
page.keyboard.type('testuser2@solit.cn')
|
||||
page.wait_for_timeout(500)
|
||||
page.keyboard.press('Enter')
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
# 填写主题
|
||||
page.locator('.subject-row input').fill('自动化联系人验证测试')
|
||||
# 填写正文
|
||||
page.locator('.editor-content').click()
|
||||
page.keyboard.type('测试正文:验证发信后收件人是否记录入库。')
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
print('3. 点击发送...')
|
||||
page.locator('.send-btn').click()
|
||||
page.wait_for_timeout(4000)
|
||||
page.screenshot(path=os.path.join(output_dir, '10_sent_first_mail.png'))
|
||||
|
||||
# 再次前往写信页,查看下拉列表
|
||||
print('4. 重新进入写信页,查看历史联系人下拉...')
|
||||
page.goto('https://mail.solit.cn/#/editer', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
select_box = page.locator('.border-less-select')
|
||||
select_box.click()
|
||||
page.wait_for_timeout(800)
|
||||
page.screenshot(path=os.path.join(output_dir, '11_contacts_dropdown_after_send.png'))
|
||||
|
||||
items = page.locator('.el-select-dropdown__item:visible')
|
||||
print('下拉数量:', items.count())
|
||||
for i in range(items.count()):
|
||||
print('Item', i, ':', items.nth(i).inner_text())
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,78 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_dir = os.path.join(os.getcwd(), 'test-log', 'mail_flow_suite')
|
||||
os.makedirs(test_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.on('response', lambda res: print('[API RES]', res.status, res.url, res.text()[:200]) if 'email' in res.url or 'send' in res.url else None)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/editer', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# 聚焦到收件人输入框
|
||||
wrapper = page.locator('.border-less-select .el-select__wrapper').first
|
||||
wrapper.click()
|
||||
page.wait_for_timeout(300)
|
||||
|
||||
to_input = page.locator('.border-less-select input').first
|
||||
to_input.fill('testuser2@solit.cn')
|
||||
page.wait_for_timeout(300)
|
||||
page.keyboard.press('Enter')
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
# 填写主题
|
||||
subject_input = page.locator('.subject-row input')
|
||||
subject_input.fill('全量测试邮件主题 - 自动化验证')
|
||||
|
||||
# 填写正文
|
||||
editor = page.locator('.editor-content')
|
||||
editor.click()
|
||||
page.keyboard.type('测试内容:这是由全量验收流程发送的正式测试邮件。')
|
||||
page.wait_for_timeout(500)
|
||||
page.screenshot(path=os.path.join(test_dir, '10_mail_composed.png'))
|
||||
|
||||
# 查看当前已选收件人标签
|
||||
tags = page.locator('.border-less-select .el-tag')
|
||||
print('已选收件人标签数量:', tags.count())
|
||||
for i in range(tags.count()):
|
||||
print('Tag:', tags.nth(i).inner_text())
|
||||
|
||||
# 点击发送按钮
|
||||
print('点击发送邮件...')
|
||||
page.locator('.send-btn').click()
|
||||
page.wait_for_timeout(5000)
|
||||
page.screenshot(path=os.path.join(test_dir, '11_after_send.png'))
|
||||
print('发送后当前页面 URL:', page.url)
|
||||
|
||||
# 检查已发送列表
|
||||
page.goto('https://mail.solit.cn/#/list?tag=outbox', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '12_outbox_list.png'))
|
||||
|
||||
# 查看列表中的邮件
|
||||
items = page.locator('.email-item, .mail-item, tr.el-table__row')
|
||||
print('已发送列表条目数:', items.count())
|
||||
for i in range(min(5, items.count())):
|
||||
print(f'Mail {i}:', items.nth(i).inner_text().replace('\n', ' | '))
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,63 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os, sys
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.on('console', lambda msg: print('[CONSOLE]', msg.type, msg.text))
|
||||
page.on('pageerror', lambda err: print('[PAGE ERROR]', err))
|
||||
page.on('response', lambda res: print('[NET RES]', res.status, res.url) if '/api/' in res.url else None)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(2500)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/editer', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# 选择收件人
|
||||
wrapper = page.locator('.border-less-select .el-select__wrapper')
|
||||
wrapper.click()
|
||||
page.wait_for_timeout(300)
|
||||
page.keyboard.type('testuser2@solit.cn')
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
item = page.locator('.el-select-dropdown__item:visible').first
|
||||
item.click()
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
tags = page.locator('.border-less-select .el-tag')
|
||||
print('Tags count:', tags.count())
|
||||
|
||||
# 填写主题
|
||||
page.locator('.subject-row input').fill('自动化测试验证收件人')
|
||||
|
||||
# 填写正文
|
||||
page.locator('.editor-content').click()
|
||||
page.keyboard.type('测试正文内容123456')
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
print('Clicking send...')
|
||||
page.locator('.send-btn').click()
|
||||
page.wait_for_timeout(4000)
|
||||
|
||||
print('After click send, URL:', page.url)
|
||||
errors = page.locator('.el-form-item__error')
|
||||
print('Errors count:', errors.count())
|
||||
for i in range(errors.count()):
|
||||
print('Error text:', errors.nth(i).inner_text())
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,78 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_dir = os.path.join(os.getcwd(), 'test-log', 'mail_flow_suite')
|
||||
os.makedirs(test_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.on('response', lambda res: print('[API RES]', res.status, res.url, res.text()[:200]) if 'send' in res.url else None)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/editer', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# 模拟真实在 el-select 内部输入并点击创建选项
|
||||
select_box = page.locator('.border-less-select')
|
||||
select_box.click()
|
||||
page.wait_for_timeout(300)
|
||||
page.keyboard.type('testuser2@solit.cn')
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
# 检查下拉列表中出现的“创建”选项或按 Enter
|
||||
page.screenshot(path=os.path.join(test_dir, '20_typing_receiver.png'))
|
||||
# 查看是否有 el-select-dropdown__item
|
||||
dropdown_item = page.locator('.el-select-dropdown__item:visible')
|
||||
print('下拉选项数量:', dropdown_item.count())
|
||||
if dropdown_item.count() > 0:
|
||||
dropdown_item.first.click()
|
||||
else:
|
||||
page.keyboard.press('Enter')
|
||||
page.wait_for_timeout(500)
|
||||
page.screenshot(path=os.path.join(test_dir, '21_receiver_selected.png'))
|
||||
|
||||
# 填写主题
|
||||
subject_input = page.locator('.subject-row input')
|
||||
subject_input.fill('全量测试邮件主题 - 自动化验证')
|
||||
|
||||
# 填写正文
|
||||
editor = page.locator('.editor-content')
|
||||
editor.click()
|
||||
page.keyboard.type('测试内容:这是由全量验收流程发送的正式测试邮件。')
|
||||
page.wait_for_timeout(500)
|
||||
page.screenshot(path=os.path.join(test_dir, '22_ready_to_send.png'))
|
||||
|
||||
# 查看标签
|
||||
tags = page.locator('.border-less-select .el-tag')
|
||||
print('已选收件人标签数量:', tags.count())
|
||||
|
||||
# 点击发送
|
||||
print('点击发送邮件...')
|
||||
page.locator('.send-btn').click()
|
||||
page.wait_for_timeout(5000)
|
||||
page.screenshot(path=os.path.join(test_dir, '23_after_send.png'))
|
||||
print('当前页面 URL:', page.url)
|
||||
|
||||
# 检查发件箱
|
||||
page.goto('https://mail.solit.cn/#/list?tag={"type":1,"status":-1}', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '24_outbox.png'))
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_dir = os.path.join(os.getcwd(), 'test-log', 'user_management_suite')
|
||||
os.makedirs(test_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.on('response', lambda res: print('[API]', res.status, res.url, res.text()[:200]) if 'user' in res.url else None)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
page.locator('.settings-btn').click()
|
||||
page.wait_for_timeout(1500)
|
||||
page.locator('#tab-users').click()
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# 再次新建一个用户测试响应
|
||||
page.locator('.new-btn').click()
|
||||
page.wait_for_timeout(1000)
|
||||
dialog = page.locator('.el-dialog:visible')
|
||||
d_inputs = dialog.locator('input')
|
||||
d_inputs.nth(0).fill('testuser2')
|
||||
d_inputs.nth(1).fill('测试员二')
|
||||
d_inputs.nth(2).fill('Test123456')
|
||||
page.wait_for_timeout(500)
|
||||
dialog.locator('button.el-button--primary:has-text("确定"), button.el-button--primary:has-text("确认")').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
# 查看当前表格
|
||||
rows = page.locator('.modern-table .el-table__row')
|
||||
print('最新用户列表总行数:', rows.count())
|
||||
for i in range(rows.count()):
|
||||
print(f'Row {i}:', rows.nth(i).inner_text().replace('\n', ' | '))
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,68 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_dir = os.path.join(os.getcwd(), 'test-log', 'user_management_suite')
|
||||
os.makedirs(test_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
# 打开设置抽屉
|
||||
page.locator('.settings-btn').click()
|
||||
page.wait_for_timeout(1500)
|
||||
page.locator('#tab-users').click()
|
||||
page.wait_for_timeout(2000)
|
||||
page.screenshot(path=os.path.join(test_dir, '01_users_table.png'))
|
||||
|
||||
# 打印表格表头和行数据
|
||||
rows = page.locator('.modern-table .el-table__row')
|
||||
print('用户行数:', rows.count())
|
||||
for i in range(rows.count()):
|
||||
print(f'Row {i}:', rows.nth(i).inner_text().replace('\n', ' | '))
|
||||
|
||||
# 点击“新建”按钮
|
||||
new_btn = page.locator('.new-btn, button:has-text("新建")')
|
||||
print('新建按钮数量:', new_btn.count())
|
||||
if new_btn.count() > 0:
|
||||
new_btn.first.click()
|
||||
page.wait_for_timeout(1000)
|
||||
page.screenshot(path=os.path.join(test_dir, '02_create_user_dialog.png'))
|
||||
|
||||
# 填写新用户信息
|
||||
dialog = page.locator('.el-dialog:visible')
|
||||
d_inputs = dialog.locator('input')
|
||||
print('对话框输入框数量:', d_inputs.count())
|
||||
# 0: account, 1: name, 2: password
|
||||
if d_inputs.count() >= 3:
|
||||
d_inputs.nth(0).fill('tester01')
|
||||
d_inputs.nth(1).fill('测试员')
|
||||
d_inputs.nth(2).fill('Tester123456!')
|
||||
page.wait_for_timeout(500)
|
||||
page.screenshot(path=os.path.join(test_dir, '03_form_filled.png'))
|
||||
|
||||
# 点击确认按钮
|
||||
confirm_btn = dialog.locator('button.el-button--primary:has-text("确定"), button.el-button--primary:has-text("确认")')
|
||||
print('确认按钮数量:', confirm_btn.count())
|
||||
if confirm_btn.count() > 0:
|
||||
confirm_btn.last.click()
|
||||
page.wait_for_timeout(2500)
|
||||
page.screenshot(path=os.path.join(test_dir, '04_after_user_created.png'))
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,40 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os, sys
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
'--host-resolver-rules=MAP mail.solit.cn 47.108.78.12, MAP solit.cn 47.108.78.12'
|
||||
]
|
||||
)
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 900}, ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
inputs = page.locator('.login-content input')
|
||||
inputs.nth(0).fill('xuans')
|
||||
inputs.nth(1).fill('12345678')
|
||||
page.locator('button.login-btn').click()
|
||||
page.wait_for_timeout(2500)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/editer', wait_until='networkidle')
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
# 展开下拉列表
|
||||
wrapper = page.locator('.border-less-select .el-select__wrapper')
|
||||
wrapper.click()
|
||||
page.wait_for_timeout(500)
|
||||
|
||||
items = page.locator('.el-select-dropdown__item:visible')
|
||||
print('Dropdown items count:', items.count())
|
||||
for i in range(items.count()):
|
||||
print('Item', i, ':', items.nth(i).inner_text())
|
||||
|
||||
# 截图
|
||||
page.screenshot(path='test-log/contacts_dropdown_rendered.png')
|
||||
|
||||
browser.close()
|
||||
@@ -0,0 +1,38 @@
|
||||
import time, os
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
test_log_dir = os.path.join(os.getcwd(), 'test-log', 'domain-login-acceptance-v2')
|
||||
os.makedirs(test_log_dir, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=False,
|
||||
slow_mo=600,
|
||||
args=['--start-maximized', '--no-sandbox']
|
||||
)
|
||||
context = browser.new_context(viewport=None)
|
||||
page = context.new_page()
|
||||
|
||||
page.on('console', lambda msg: print('[CONSOLE]', msg.type, msg.text))
|
||||
page.on('pageerror', lambda exc: print('[ERROR]', exc))
|
||||
page.on('request', lambda req: print('[REQ]', req.method, req.url) if 'api' in req.url else None)
|
||||
page.on('response', lambda res: print('[RES]', res.status, res.url) if 'api' in res.url else None)
|
||||
|
||||
page.goto('https://mail.solit.cn/#/login', wait_until='networkidle')
|
||||
time.sleep(2)
|
||||
|
||||
acc = page.locator('.login-content input').nth(0)
|
||||
pwd = page.locator('.login-content input').nth(1)
|
||||
acc.fill('xuans')
|
||||
pwd.fill('12345678')
|
||||
time.sleep(1)
|
||||
|
||||
page.locator('button.login-btn').click()
|
||||
|
||||
time.sleep(5)
|
||||
page.screenshot(path=os.path.join(test_log_dir, 'after_login.png'))
|
||||
print('URL after login:', page.url)
|
||||
|
||||
# 检查页面上的文本或状态
|
||||
time.sleep(10)
|
||||
browser.close()
|
||||
Reference in new issue
Block a user