BillionMail gives you open-source MailServer, NewsLetter, Email Marketing — fully self-hosted, dev-friendly, and free from monthly fees. Join the discord: https://discord.gg/asfXzBUhZr
added Rspamd GUI reverse-proxy. added options_mgr.
Jackdb8f3c085132
diff --git a/core/internal/cmd/cmd.go b/core/internal/cmd/cmd.goindex 6435b033..d51692bd 100644--- a/core/internal/cmd/cmd.go+++ b/core/internal/cmd/cmd.go@@ -19,6 +19,7 @@ import ("billionmail-core/internal/service/public"rbac2 "billionmail-core/internal/service/rbac""billionmail-core/internal/service/redis_initialization"+ "billionmail-core/internal/service/rspamd""billionmail-core/internal/service/timers""context""github.com/gogf/gf/v2/frame/g"@@ -77,6 +78,14 @@ var (defer dk.Close()+ // Init Rspamd worker-controller+ err = rspamd.InitWorkerController()++ if err != nil {+ g.Log().Warning(ctx, "rspamd init failed ", err)+ err = nil+ }+// Create a new server instances := g.Server(consts.DEFAULT_SERVER_NAME)@@ -201,6 +210,37 @@ var (proxy.ServeHTTP(r.Response.BufferWriter, r.Request)})+ // Proxy Rspamd GUI+ s.BindHandler("/rspamd/*any", func(r *ghttp.Request) {+ if !r.Session.MustGet("UserLogin", false).Bool() {+ r.Response.WriteHeader(403)+ r.Response.Write([]byte("Access denied"))+ return+ }++ host := "127.0.0.1:21334"++ if public.IsRunningInContainer() {+ host = "rspamd:11334"+ }++ proxy := httputil.NewSingleHostReverseProxy(&url.URL{+ Scheme: "http",+ Host: host,+ })++ var password string+ err = public.OptionsMgrInstance.GetOption(ctx, "rspamd_worker_controller_password", &password)++ if err == nil {+ r.Header.Set("Password", password)+ }++ r.URL.Path = strings.Replace(r.URL.Path, "/rspamd", "", 1)++ proxy.ServeHTTP(r.Response.BufferWriter, r.Request)+ })+// Email Campaign Trackers.BindHandler("/pmta/*any", func(r *ghttp.Request) {maillog_stat.CampaignEventHandler(r, r.Get("any").String())diff --git a/core/internal/service/public/options_mgr.go b/core/internal/service/public/options_mgr.gonew file mode 100644index 00000000..8fcb9c78--- /dev/null+++ b/core/internal/service/public/options_mgr.go@@ -0,0 +1,208 @@+package public++import (+ "context"+ "encoding/json"+ "errors"+ "github.com/gogf/gf/v2/frame/g"+ "github.com/gogf/gf/v2/os/gcache"+ "time"+)++// OptionsMgr Options Manager+type OptionsMgr struct {+ cache *gcache.Cache // Cache instance+ expiration time.Duration // Cache expiration time+}++// NewOptionsMgr Create options manager+func NewOptionsMgr() *OptionsMgr {+ return &OptionsMgr{+ cache: gcache.New(),+ expiration: time.Hour * 24, // Default 24 hours cache+ }+}++// OptionsMgrInstance Options manager singleton+var OptionsMgrInstance = NewOptionsMgr()++// SetOption Set option+func (o *OptionsMgr) SetOption(ctx context.Context, key string, value interface{}) error {+ if key == "" {+ return errors.New("key cannot be empty")+ }++ if value == nil {+ return errors.New("value cannot be nil")+ }++ // Serialize value+ jsonValue, err := o.serialize(value)+ if err != nil {+ return err+ }++ // Save to database+ if err := o.saveToDatabase(ctx, key, jsonValue); err != nil {+ return err+ }++ // Update cache+ cacheKey := o.buildCacheKey(key)+ if err := o.cache.Set(ctx, cacheKey, jsonValue, o.expiration); err != nil {+ return err+ }++ return nil+}++// GetOption Get option and deserialize to specified type+func (o *OptionsMgr) GetOption(ctx context.Context, key string, ptr interface{}) error {+ if key == "" {+ return errors.New("key cannot be empty")+ }++ if ptr == nil {+ return errors.New("pointer cannot be nil")+ }++ // Try to get from cache+ cacheKey := o.buildCacheKey(key)+ cached, err := o.cache.Get(ctx, cacheKey)+ var jsonValue string++ if err != nil || cached == nil {+ // Cache miss, read from database+ var result struct {+ Value string `json:"value"`+ }++ err := g.DB().Model("bm_options").+ Where("name", key).+ Fields("value").+ Scan(&result)++ if err != nil {+ return errors.New("failed to get option from database: " + err.Error())+ }++ if result.Value == "" {+ return errors.New("option not found")+ }++ jsonValue = result.Value++ // Store in cache+ if err := o.cache.Set(ctx, cacheKey, jsonValue, o.expiration); err != nil {+ g.Log().Warning(ctx, "Failed to set option cache:", err)+ }+ } else {+ // Cache hit+ jsonValue = cached.String()+ }++ // Deserialize+ return o.deserialize(jsonValue, ptr)+}++// GetAllOptions Get all options+func (o *OptionsMgr) GetAllOptions(ctx context.Context) (map[string]string, error) {+ var options []struct {+ Name string `json:"name"`+ Value string `json:"value"`+ }++ err := g.DB().Model("bm_options").Scan(&options)+ if err != nil {+ return nil, err+ }++ result := make(map[string]string, len(options))+ for _, opt := range options {+ result[opt.Name] = opt.Value++ // Update cache+ cacheKey := o.buildCacheKey(opt.Name)+ if err := o.cache.Set(ctx, cacheKey, opt.Value, o.expiration); err != nil {+ g.Log().Warning(ctx, "Failed to set option cache when loading all:", err)+ }+ }++ return result, nil+}++// DeleteOption Delete option+func (o *OptionsMgr) DeleteOption(ctx context.Context, key string) (err error) {+ if key == "" {+ return errors.New("key cannot be empty")+ }++ // Delete from database+ _, err = g.DB().Model("bm_options").Where("name", key).Delete()+ if err != nil {+ return+ }++ // Delete from cache+ cacheKey := o.buildCacheKey(key)+ _, err = o.cache.Remove(ctx, cacheKey)++ return+}++// SetCacheExpiration Set cache expiration time+func (o *OptionsMgr) SetCacheExpiration(expiration time.Duration) {+ o.expiration = expiration+}++// ClearCache Clear all cache+func (o *OptionsMgr) ClearCache(ctx context.Context) error {+ return o.cache.Clear(ctx)+}++// buildCacheKey Build cache key+func (o *OptionsMgr) buildCacheKey(key string) string {+ return "BM_OPTION:" + key+}++// serialize Serialize value to JSON string+func (o *OptionsMgr) serialize(value interface{}) (string, error) {+ // If already a string, return directly+ if str, ok := value.(string); ok {+ return str, nil+ }++ // Serialize other types to JSON+ bytes, err := json.Marshal(value)+ if err != nil {+ return "", err+ }+ return string(bytes), nil+}++// deserialize Deserialize JSON string to specified type+func (o *OptionsMgr) deserialize(jsonValue string, ptr interface{}) error {+ // If target is string pointer, assign directly+ if strPtr, ok := ptr.(*string); ok {+ *strPtr = jsonValue+ return nil+ }++ // Deserialize from JSON for other types+ return json.Unmarshal([]byte(jsonValue), ptr)+}++// saveToDatabase Save to database+func (o *OptionsMgr) saveToDatabase(ctx context.Context, key string, value string) error {+ _, err := g.DB().Model("bm_options").+ Where("name", key).+ Fields("name", "value").+ OnDuplicate("value").+ Data(g.Map{+ "name": key,+ "value": value,+ }).+ Save()++ return err+}diff --git a/core/internal/service/rbac/jwt.go b/core/internal/service/rbac/jwt.goindex 548073b6..d41453ca 100644--- a/core/internal/service/rbac/jwt.go+++ b/core/internal/service/rbac/jwt.go@@ -202,5 +202,12 @@ func (s *JWTService) JWTAuthMiddleware(r *ghttp.Request) {r.SetCtxVar("roles", roles)}+ // Update Session+ err = r.Session.Set("UserLogin", true)++ if err != nil {+ g.Log().Warning(r.GetCtx(), "set UserLogin failed ", err)+ }+r.Middleware.Next()}diff --git a/core/internal/service/rspamd/worker_controller.go b/core/internal/service/rspamd/worker_controller.gonew file mode 100644index 00000000..a6975dd6--- /dev/null+++ b/core/internal/service/rspamd/worker_controller.go@@ -0,0 +1,71 @@+package rspamd++import (+ "billionmail-core/internal/consts"+ docker "billionmail-core/internal/service/dockerapi"+ "billionmail-core/internal/service/public"+ "context"+ "errors"+ "github.com/gogf/gf/util/grand"+ "github.com/gogf/gf/v2/frame/g"+ "path/filepath"+ "strings"+)++// InitWorkerController initializes the worker controller+func InitWorkerController() (err error) {+ wci := filepath.Join(consts.RSPAMD_LOCAL_D_PATH, "worker-controller.inc")++ // Check if the file exists+ if public.FileExists(wci) {+ return+ }++ // Generate password+ passwordPlain := grand.S(16)++ // Generate the worker controller configuration+ dk, err := docker.NewDockerAPI()++ if err != nil {+ return+ }++ defer dk.Close()++ res, err := dk.ExecCommandByName(context.Background(), "billionmail-rspamd-billionmail-1", []string{"rspamadm", "pw", "-p", passwordPlain}, "root")++ if err != nil {+ return+ }++ if res == nil {+ err = errors.New("rspamdadm not found")+ return+ }++ _, err = public.WriteFile(wci, `count = 1;+password = "`+strings.TrimSpace(res.Output)+`";+secure_ip = "127.0.0.1";+secure_ip = "::1";+static_dir = "${WWWDIR}";`)++ if err != nil {+ return+ }++ // Save the password+ _, err = g.DB().Model("bm_options").OnConflict("name").OnDuplicate("value").Save(g.Map{+ "name": "rspamd_worker_controller_password",+ "value": passwordPlain,+ })++ if err != nil {+ return+ }++ // Restart the RSPAMD container+ err = dk.RestartContainer(context.Background(), "billionmail-rspamd-billionmail-1")++ return+}