feat: 新增维护模式 + 修复注册关闭页面标题显示问题

- 修复注册关闭时标题“创建账号”和副标题仍显示的问题,三态互斥(维护中 > 关闭注册 > 正常)
- 新增 maintenance.enabled 站点设置,默认关闭,仅 Owner 可见可调节
- 维护中间件:全局拦截,维护期间仅站长可访问,白名单放行登录相关路径
- 登录服务:维护期间仅 Owner 角色可登录,Register 优先检查维护状态
- Nav 模板新增维护通知条(黄色横幅)
- 管理后台站点设置新增“启用维护模式”开关
- BuildPageData 自动注入 IsMaintenance 到所有页面模板
This commit is contained in:
2026-05-30 20:54:23 +08:00
parent fb2eff5f23
commit 6229c81f6e
16 changed files with 186 additions and 8 deletions

View File

@ -35,6 +35,7 @@ var (
ErrNeedsConfirmRestore = errors.New("需要二次确认恢复账号")
ErrOwnerCannotDelete = errors.New("站长不可自主注销,请先转让站长权限")
ErrRegistrationDisabled = errors.New("注册功能已关闭")
ErrMaintenanceMode = errors.New("社区正在维护中,仅站长可登录")
// 帖子相关
ErrPostNotFound = errors.New("帖子不存在")

View File

@ -40,6 +40,10 @@ func BuildPageData(c *gin.Context, extra gin.H) gin.H {
if role, exists := c.Get("role"); exists {
data["CanAccessAdmin"] = model.HasMinRole(role.(string), model.RoleModerator)
}
// 注入维护状态
if isMaintenance, exists := c.Get("is_maintenance"); exists {
data["IsMaintenance"] = isMaintenance
}
return data
}

View File

@ -128,3 +128,8 @@ func (s *SiteSettings) SiteInfo() SiteInfoDefaults {
func (s *SiteSettings) IsRegistrationEnabled() bool {
return s.GetBool("registration.enabled", true)
}
// IsMaintenanceEnabled 是否处于维护模式(维护期间仅站长可登录和访问)
func (s *SiteSettings) IsMaintenanceEnabled() bool {
return s.GetBool("maintenance.enabled", false)
}

View File

@ -62,6 +62,8 @@ func (ac *AuthController) Login(c *gin.Context) {
common.Error(c, http.StatusForbidden, "账号已被封禁")
case common.ErrUserLocked:
common.Error(c, http.StatusUnauthorized, "邮箱或密码错误")
case common.ErrMaintenanceMode:
common.Error(c, http.StatusForbidden, "社区正在维护中,仅站长可登录")
case common.ErrNeedsConfirmRestore:
// 注销账号登录 → 需要二次确认恢复
c.JSON(http.StatusOK, gin.H{

View File

@ -47,6 +47,8 @@ func (ac *AuthController) Register(c *gin.Context) {
recordReg()
}
switch err {
case common.ErrMaintenanceMode:
common.Error(c, http.StatusForbidden, "社区正在维护中,暂不支持注册")
case common.ErrEmailExists:
common.Error(c, http.StatusConflict, "该邮箱已注册")
case common.ErrWeakPassword:

View File

@ -0,0 +1,97 @@
package middleware
import (
"net/http"
"strings"
"metazone.cc/metalab/internal/common"
"metazone.cc/metalab/internal/config"
"metazone.cc/metalab/internal/model"
"github.com/gin-gonic/gin"
)
// MaintenanceMiddleware 维护模式中间件维护期间仅站长Owner可访问
type MaintenanceMiddleware struct {
cfg *config.Config
siteSettings *config.SiteSettings
}
// NewMaintenanceMiddleware 构造函数
func NewMaintenanceMiddleware(cfg *config.Config, siteSettings *config.SiteSettings) *MaintenanceMiddleware {
return &MaintenanceMiddleware{cfg: cfg, siteSettings: siteSettings}
}
// Handler 返回 Gin 中间件处理函数
func (mm *MaintenanceMiddleware) Handler() gin.HandlerFunc {
return func(c *gin.Context) {
// 未启用维护模式 → 放行
if !mm.siteSettings.IsMaintenanceEnabled() {
c.Next()
return
}
path := c.Request.URL.Path
// 白名单:登录相关页面和 API 始终可访问
if isMaintenanceWhitelist(path) {
c.Next()
return
}
// 尝试读取 token 并解析角色
tokenStr, err := c.Cookie(common.CookieName)
if err != nil {
// 未登录 → 重定向到登录页API 返回 403
blockAccess(c, path)
return
}
claims, err := parseToken(tokenStr, mm.cfg.JWT.Secret)
if err != nil {
blockAccess(c, path)
return
}
role, _ := claims["role"].(string)
if !model.HasMinRole(role, model.RoleOwner) {
blockAccess(c, path)
return
}
// 注入用户信息到 context后续 auth 中间件可能还需要)
injectUserContext(c, claims)
c.Next()
}
}
// isMaintenanceWhitelist 判断路径是否在维护白名单中
func isMaintenanceWhitelist(path string) bool {
// 登录页面和认证 API
if path == "/auth/login" || strings.HasPrefix(path, "/api/auth/") {
return true
}
// 静态资源
if strings.HasPrefix(path, "/static/") || strings.HasPrefix(path, "/shared/") {
return true
}
// favicon
if path == "/favicon.ico" || path == "/favicon.svg" {
return true
}
return false
}
// blockAccess 根据请求类型阻止访问页面重定向API 返回 403 JSON
func blockAccess(c *gin.Context, path string) {
if strings.HasPrefix(path, "/api/") || strings.HasPrefix(path, "/admin/api/") {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"success": false,
"message": "社区正在维护中,仅站长可访问",
})
return
}
c.Redirect(http.StatusFound, "/auth/login")
c.Abort()
}

View File

@ -7,12 +7,13 @@ import (
)
// InjectSiteInfo 注入站点展示信息到请求上下文(供 BuildPageData 使用)
// 应用于引擎级全局中间件,确保所有 SSR 页面都能读取 Framework/CopyrightStart
// 应用于引擎级全局中间件,确保所有 SSR 页面都能读取 Framework/CopyrightStart/IsMaintenance
func InjectSiteInfo(siteSettings *config.SiteSettings) gin.HandlerFunc {
return func(c *gin.Context) {
info := siteSettings.SiteInfo()
c.Set("site_framework", info.Framework)
c.Set("site_copyright_start", info.CopyrightStart)
c.Set("is_maintenance", siteSettings.IsMaintenanceEnabled())
c.Next()
}
}

View File

@ -14,6 +14,7 @@ import (
type dependencies struct {
authCtrl *controller.AuthController
authMdw *middleware.AuthMiddleware
maintenanceMdw *middleware.MaintenanceMiddleware
settingsCtrl *controller.SettingsController
messageCtrl *controller.MessageController
postCtrl *controller.PostController

View File

@ -4,6 +4,7 @@ import (
"metazone.cc/metalab/internal/config"
"metazone.cc/metalab/internal/controller"
adminCtrl "metazone.cc/metalab/internal/controller/admin"
"metazone.cc/metalab/internal/middleware"
"metazone.cc/metalab/internal/repository"
"metazone.cc/metalab/internal/service"
@ -41,8 +42,11 @@ func buildDeps(db *gorm.DB, cfg *config.Config, siteSettings *config.SiteSetting
spaceService := service.NewSpaceService(userRepo, postRepo)
spaceCtrl := controller.NewSpaceController(spaceService)
maintenanceMdw := middleware.NewMaintenanceMiddleware(cfg, siteSettings)
return &dependencies{
authCtrl: authCtrl, authMdw: authMdw, settingsCtrl: settingsCtrl,
authCtrl: authCtrl, authMdw: authMdw, maintenanceMdw: maintenanceMdw,
settingsCtrl: settingsCtrl,
messageCtrl: messageController, postCtrl: postCtrl, spaceCtrl: spaceCtrl,
studioCtrl: studioCtrl,
adminPostCtrl: adminPostCtrl,

View File

@ -15,6 +15,9 @@ func Setup(r *gin.Engine, db *gorm.DB, cfg *config.Config, siteSettings *config.
deps := buildDeps(db, cfg, siteSettings)
// 维护模式中间件(全局,在路由匹配之前)
r.Use(deps.maintenanceMdw.Handler())
setupFrontendRoutes(r, cfg, deps)
setupAPIRoutes(r, cfg, deps)
setupAdminRoutes(r, cfg, deps)

View File

@ -62,7 +62,11 @@ func (s *AuthService) IsRegistrationEnabled() bool {
// rememberMe=true: refresh Cookie 持久化30天false: session cookie关浏览器即清除
// regIP: 注册 IP 地址
func (s *AuthService) Register(req model.RegisterRequest, regIP string) (string, string, *model.User, error) {
// 0. 检查注册开关
// 0. 维护期间禁止注册
if s.siteSettings.IsMaintenanceEnabled() {
return "", "", nil, common.ErrMaintenanceMode
}
// 1. 检查注册开关
if !s.siteSettings.IsRegistrationEnabled() {
return "", "", nil, common.ErrRegistrationDisabled
}
@ -154,6 +158,11 @@ func (s *AuthService) Login(req model.LoginRequest, loginIP string) (string, str
return "", "", nil, common.ErrUserBanned
}
// 维护期间仅站长可登录
if s.siteSettings.IsMaintenanceEnabled() && !model.HasMinRole(user.Role, model.RoleOwner) {
return "", "", nil, common.ErrMaintenanceMode
}
if !common.CheckPassword(req.Password, user.PasswordHash) {
return "", "", nil, common.ErrInvalidCred
}