feat: 消息通知中心 + 账号安全体系 + Bug修复
## 新增功能 ### 消息通知中心 (全新模块) - 新增 MessageController / NotificationService / NotificationRepo - SSR 消息页面 (/messages):左侧边栏 + 右侧卡片列表,noindex 元标签 - 通知能力:列表分页、单条标为已读、一键全部标为已读 - 未读数角标 (1/66/99+):侧边栏 + 导航栏铃铛图标 - 导航栏轮询 /api/messages/unread 每 60 秒刷新未读数 - 审核通过/驳回时自动 fire-and-forget 推送通知 ### 密码修改 - ChangePassword:验证当前密码 → 新密码强度校验(8位+字母+数字) → 哈希更新 - 修改后递增 token_version 强制所有设备退登 ### 账号自助注销 - DeleteAccount:验证密码 → 设置 deleted 状态 → 记录原因 → 吊销 JWT - 注销后登录二次确认:Login 检测 deleted → 返回 confirm_restore - ConfirmRestore 恢复账号,重新签发 token - 注销页文案:"账号将在 7 天后正式注销,期间可随时重新登录恢复" ### IP 审计记录 - 注册时记录 RegIP,登录时记录 LastLoginIP + LastLoginAt - clientIP() 支持 X-Forwarded-For / X-Real-IP 反向代理 ### 安全加固 - Login 防时序攻击:用户不存在时仍执行完整 bcrypt 比对 - FindByEmail 改用 Unscoped() 覆盖软删除用户 - 站长 (owner) 不允许自主注销,避免权限体系死锁 ## Bug 修复 1. 注销按钮不触发:JS IIFE 中 profile 代码 return 阻塞了 account 标签页处理器注册 → 拆分为两层 IIFE,profile 放在内层 2. label 缺少 for 属性导致控制台警告 → 全部补充 for 属性 3. 注销后未自动退登:DeleteAccount 只设状态未吊销 JWT → 末尾加 InvalidateSessions 4. 退登后重定向 500 panic:authenticateToken 中 err||versionMismatch 合并判断 在 err=nil 但版本不匹配时返回 (nil,nil) → 拆为两个独立判断 injectUserContext 增加 claims==nil / 类型断言空安全守卫 5. 注销后登录直接提示"登录成功":FindByEmail 默认 scope 排除软删除记录 → 改用 Unscoped() ## 文件变更 - 新建 17 个文件 (消息/审核/站点设置完整模块) - 修改 25 个文件 (认证/设置/中间件/前端) - 统计:+3229 / -161,42 files changed
This commit is contained in:
140
internal/controller/admin/audit_controller.go
Normal file
140
internal/controller/admin/audit_controller.go
Normal file
@ -0,0 +1,140 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// AuditController 审核管理控制器
|
||||
type AuditController struct {
|
||||
auditService auditUseCase
|
||||
userRepo auditStatusProvider
|
||||
}
|
||||
|
||||
// NewAuditController 构造函数
|
||||
func NewAuditController(auditService auditUseCase, userRepo auditStatusProvider) *AuditController {
|
||||
return &AuditController{auditService: auditService, userRepo: userRepo}
|
||||
}
|
||||
|
||||
// AuditPage 审核管理页面
|
||||
func (ac *AuditController) AuditPage(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "admin/audit/index.html", common.BuildAdminPageData(c, gin.H{
|
||||
"Title": "审核管理",
|
||||
"ExtraCSS": "/admin/static/css/audit.css",
|
||||
"ExtraJS": "/admin/static/js/audit.js",
|
||||
"AuditTypes": model.AuditTypeNames,
|
||||
"AuditStatus": model.AuditStatusNames,
|
||||
}))
|
||||
}
|
||||
|
||||
// ListAudits 审核列表 API(分页 + 类型筛选)
|
||||
func (ac *AuditController) ListAudits(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
auditType := c.Query("type")
|
||||
status := c.Query("status")
|
||||
|
||||
// 默认查 pending
|
||||
if status == "" {
|
||||
status = model.AuditStatusPending
|
||||
}
|
||||
|
||||
result, err := ac.auditService.List(auditType, status, page, pageSize)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 为每个审核记录附加提交者的用户名
|
||||
type auditItem struct {
|
||||
model.AuditSubmission
|
||||
SubmitterUsername string `json:"submitter_username"`
|
||||
}
|
||||
|
||||
items := make([]auditItem, 0, len(result.Items))
|
||||
for _, a := range result.Items {
|
||||
item := auditItem{AuditSubmission: a}
|
||||
if user, err := ac.userRepo.FindByID(a.UserID); err == nil {
|
||||
item.SubmitterUsername = user.Username
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
|
||||
common.Ok(c, gin.H{
|
||||
"items": items,
|
||||
"total": result.Total,
|
||||
"page": result.Page,
|
||||
})
|
||||
}
|
||||
|
||||
// Approve 通过审核
|
||||
func (ac *AuditController) Approve(c *gin.Context) {
|
||||
submissionID, err := parseIDParam(c.Param("id"))
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的审核 ID")
|
||||
return
|
||||
}
|
||||
|
||||
reviewerID := c.GetUint("uid")
|
||||
if err := ac.auditService.Approve(reviewerID, submissionID); err != nil {
|
||||
handleAuditError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "审核通过")
|
||||
}
|
||||
|
||||
// Reject 拒绝审核
|
||||
func (ac *AuditController) Reject(c *gin.Context) {
|
||||
submissionID, err := parseIDParam(c.Param("id"))
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的审核 ID")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
reviewerID := c.GetUint("uid")
|
||||
if err := ac.auditService.Reject(reviewerID, submissionID, req.Reason); err != nil {
|
||||
handleAuditError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "已拒绝")
|
||||
}
|
||||
|
||||
// parseIDParam 从 URL 路径参数解析 uint ID
|
||||
func parseIDParam(s string) (uint, error) {
|
||||
id, err := strconv.ParseUint(s, 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return uint(id), nil
|
||||
}
|
||||
|
||||
// handleAuditError 统一处理审核接口的 service 层错误
|
||||
func handleAuditError(c *gin.Context, err error) {
|
||||
switch err {
|
||||
case common.ErrAuditNotFound:
|
||||
common.Error(c, http.StatusNotFound, "审核记录不存在")
|
||||
case common.ErrAuditNotPending:
|
||||
common.Error(c, http.StatusBadRequest, "该审核记录已处理")
|
||||
case common.ErrUserNotFound:
|
||||
common.Error(c, http.StatusNotFound, "用户不存在")
|
||||
case common.ErrUsernameTaken:
|
||||
common.Error(c, http.StatusConflict, "该用户名已被其他用户占用,审批失败")
|
||||
default:
|
||||
common.Error(c, http.StatusInternalServerError, "操作失败")
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,9 @@
|
||||
package admin
|
||||
|
||||
import "metazone.cc/metalab/internal/service"
|
||||
import (
|
||||
"metazone.cc/metalab/internal/model"
|
||||
"metazone.cc/metalab/internal/service"
|
||||
)
|
||||
|
||||
// adminUseCase AdminController 对 AdminService 的最小依赖(ISP:4 个方法)
|
||||
type adminUseCase interface {
|
||||
@ -9,3 +12,24 @@ type adminUseCase interface {
|
||||
ResetUserToken(operatorUID, targetUID uint) error
|
||||
CountUsers() (int64, error)
|
||||
}
|
||||
|
||||
// auditUseCase AuditController 对 AuditService 的最小依赖(ISP:4 个方法)
|
||||
type auditUseCase interface {
|
||||
List(auditType, status string, page, pageSize int) (*service.AuditListResult, error)
|
||||
Approve(reviewerID uint, submissionID uint) error
|
||||
Reject(reviewerID uint, submissionID uint, reason string) error
|
||||
}
|
||||
|
||||
// siteSettingUseCase SiteSettingController 对 SiteSettingService 的最小依赖(ISP:3 个方法)
|
||||
type siteSettingUseCase interface {
|
||||
GetSettings() map[string]string
|
||||
UpdateSetting(key, value string) error
|
||||
UpdateBoolSetting(key string, value bool) error
|
||||
GetAuditSettings(defaults *service.AuditDefaults) *service.AuditSettings
|
||||
}
|
||||
|
||||
// auditStatusProvider 审核控制器所需的用户信息查询(ISP)
|
||||
type auditStatusProvider interface {
|
||||
FindByID(id uint) (*model.User, error)
|
||||
FindByUsername(username string) (*model.User, error)
|
||||
}
|
||||
|
||||
103
internal/controller/admin/site_setting_controller.go
Normal file
103
internal/controller/admin/site_setting_controller.go
Normal file
@ -0,0 +1,103 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// SiteSettingController 站点设置控制器(仅 owner 可访问)
|
||||
type SiteSettingController struct {
|
||||
settingService siteSettingUseCase
|
||||
defaults *service.AuditDefaults
|
||||
}
|
||||
|
||||
// NewSiteSettingController 构造函数
|
||||
func NewSiteSettingController(settingService siteSettingUseCase, defaults *service.AuditDefaults) *SiteSettingController {
|
||||
return &SiteSettingController{settingService: settingService, defaults: defaults}
|
||||
}
|
||||
|
||||
// GetSettings 获取所有站点设置
|
||||
func (sc *SiteSettingController) GetSettings(c *gin.Context) {
|
||||
all := sc.settingService.GetSettings()
|
||||
audit := sc.settingService.GetAuditSettings(sc.defaults)
|
||||
common.Ok(c, gin.H{
|
||||
"all": all,
|
||||
"audit": audit,
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateSetting 更新单项设置
|
||||
func (sc *SiteSettingController) UpdateSetting(c *gin.Context) {
|
||||
var req struct {
|
||||
Key string `json:"key" binding:"required"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
if err := sc.settingService.UpdateSetting(req.Key, req.Value); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "保存失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "设置已更新")
|
||||
}
|
||||
|
||||
// UpdateBoolSetting 更新布尔设置
|
||||
func (sc *SiteSettingController) UpdateBoolSetting(c *gin.Context) {
|
||||
var req struct {
|
||||
Key string `json:"key" binding:"required"`
|
||||
Value string `json:"value" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
v, err := service.ParseBool(req.Value)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "值必须为 true 或 false")
|
||||
return
|
||||
}
|
||||
|
||||
if err := sc.settingService.UpdateBoolSetting(req.Key, v); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "保存失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "设置已更新")
|
||||
}
|
||||
|
||||
// GetBoolSetting 获取单个布尔设置的当前值
|
||||
func (sc *SiteSettingController) GetBoolSetting(c *gin.Context) {
|
||||
key := c.Query("key")
|
||||
if key == "" {
|
||||
common.Error(c, http.StatusBadRequest, "缺少 key 参数")
|
||||
return
|
||||
}
|
||||
|
||||
defaultVal := c.DefaultQuery("default", "false")
|
||||
d, _ := strconv.ParseBool(defaultVal)
|
||||
|
||||
val := sc.settingService.GetAuditSettings(sc.defaults)
|
||||
// 简单键值查找
|
||||
switch key {
|
||||
case "audit.enabled":
|
||||
common.Ok(c, gin.H{"value": val.Enabled})
|
||||
case "audit.username_audit":
|
||||
common.Ok(c, gin.H{"value": val.UsernameAudit})
|
||||
case "audit.avatar_audit":
|
||||
common.Ok(c, gin.H{"value": val.AvatarAudit})
|
||||
case "audit.bio_audit":
|
||||
common.Ok(c, gin.H{"value": val.BioAudit})
|
||||
default:
|
||||
common.Ok(c, gin.H{"value": d})
|
||||
}
|
||||
}
|
||||
@ -90,7 +90,7 @@ func (ac *AuthController) Login(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
accessToken, refreshToken, user, err := ac.authService.Login(req)
|
||||
accessToken, refreshToken, user, err := ac.authService.Login(req, ip)
|
||||
if err != nil {
|
||||
// 记录失败 → 两个维度各 +1
|
||||
if recordAccount != nil {
|
||||
@ -107,9 +107,13 @@ func (ac *AuthController) Login(c *gin.Context) {
|
||||
common.Error(c, http.StatusForbidden, "账号已被封禁")
|
||||
case common.ErrUserLocked:
|
||||
common.Error(c, http.StatusUnauthorized, "邮箱或密码错误")
|
||||
case common.ErrUserDeleted:
|
||||
// deleted 状态本应在 Login 中自动恢复,此 case 作为兜底
|
||||
common.Error(c, http.StatusForbidden, "该账号已申请注销,登录即自动恢复")
|
||||
case common.ErrNeedsConfirmRestore:
|
||||
// 注销账号登录 → 需要二次确认恢复
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"action": "confirm_restore",
|
||||
"message": "你的账号正在注销中,登录将中止注销流程",
|
||||
})
|
||||
default:
|
||||
common.Error(c, http.StatusInternalServerError, "登录失败,请稍后重试")
|
||||
}
|
||||
@ -124,6 +128,29 @@ func (ac *AuthController) Login(c *gin.Context) {
|
||||
common.OkWithMessage(c, user, "登录成功")
|
||||
}
|
||||
|
||||
// ConfirmRestore 二次确认恢复已注销账号
|
||||
func (ac *AuthController) ConfirmRestore(c *gin.Context) {
|
||||
var req model.LoginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "请检查输入")
|
||||
return
|
||||
}
|
||||
|
||||
accessToken, refreshToken, user, err := ac.authService.ConfirmRestore(req, clientIP(c))
|
||||
if err != nil {
|
||||
switch err {
|
||||
case common.ErrInvalidCred:
|
||||
common.Error(c, http.StatusUnauthorized, "邮箱或密码错误")
|
||||
default:
|
||||
common.Error(c, http.StatusInternalServerError, "操作失败,请稍后重试")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
common.SetAuthCookies(c, accessToken, refreshToken, req.RememberMe, ac.cfg)
|
||||
common.OkWithMessage(c, user, "账号已恢复,欢迎回来")
|
||||
}
|
||||
|
||||
// CheckEmail 检查邮箱是否已注册
|
||||
func (ac *AuthController) CheckEmail(c *gin.Context) {
|
||||
var req model.CheckEmailRequest
|
||||
@ -156,7 +183,7 @@ func (ac *AuthController) Register(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
accessToken, refreshToken, user, err := ac.authService.Register(req)
|
||||
accessToken, refreshToken, user, err := ac.authService.Register(req, clientIP(c))
|
||||
if err != nil {
|
||||
if recordReg != nil {
|
||||
recordReg()
|
||||
|
||||
@ -5,10 +5,11 @@ import (
|
||||
"metazone.cc/metalab/internal/model"
|
||||
)
|
||||
|
||||
// authUseCase AuthController 对 AuthService 的最小依赖(ISP:3 个方法)
|
||||
// authUseCase AuthController 对 AuthService 的最小依赖(ISP:4 个方法)
|
||||
type authUseCase interface {
|
||||
Register(req model.RegisterRequest) (string, string, *model.User, error)
|
||||
Login(req model.LoginRequest) (string, string, *model.User, error)
|
||||
Register(req model.RegisterRequest, regIP string) (string, string, *model.User, error)
|
||||
Login(req model.LoginRequest, loginIP string) (string, string, *model.User, error)
|
||||
ConfirmRestore(req model.LoginRequest, loginIP string) (string, string, *model.User, error)
|
||||
CheckEmail(email string) (bool, error)
|
||||
}
|
||||
|
||||
|
||||
129
internal/controller/message_controller.go
Normal file
129
internal/controller/message_controller.go
Normal file
@ -0,0 +1,129 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// notifProvider MessageController 所需的通知服务接口(ISP:5 个方法)
|
||||
type notifProvider interface {
|
||||
List(userID uint, page, pageSize int) (*model.NotificationListResult, error)
|
||||
CountUnread(userID uint) (int64, error)
|
||||
MarkRead(id, userID uint) error
|
||||
MarkAllRead(userID uint) error
|
||||
}
|
||||
|
||||
// MessageController 消息中心控制器
|
||||
type MessageController struct {
|
||||
notifService notifProvider
|
||||
}
|
||||
|
||||
// NewMessageController 构造函数
|
||||
func NewMessageController(notifService notifProvider) *MessageController {
|
||||
return &MessageController{notifService: notifService}
|
||||
}
|
||||
|
||||
// MessagesPage 消息中心页面(需登录,noindex)
|
||||
func (mc *MessageController) MessagesPage(c *gin.Context) {
|
||||
uidVal, exists := c.Get("uid")
|
||||
if !exists {
|
||||
c.Redirect(http.StatusFound, "/auth/login")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
uid := uidVal.(uint)
|
||||
|
||||
// 从 query 取分页参数
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
pageSize := 20
|
||||
|
||||
result, err := mc.notifService.List(uid, page, pageSize)
|
||||
if err != nil {
|
||||
result = &model.NotificationListResult{Items: []model.Notification{}, Total: 0, Page: 1}
|
||||
}
|
||||
|
||||
totalPages := result.TotalPages
|
||||
if totalPages == 0 && result.Total > 0 {
|
||||
totalPages = int((result.Total + int64(pageSize) - 1) / int64(pageSize))
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "messages/index.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "消息中心",
|
||||
"ExtraCSS": "/static/css/messages.css",
|
||||
"Messages": result.Items,
|
||||
"Total": result.Total,
|
||||
"Page": result.Page,
|
||||
"TotalPages": totalPages,
|
||||
"PrevPage": result.Page - 1,
|
||||
"NextPage": result.Page + 1,
|
||||
"HasPrev": result.Page > 1,
|
||||
"HasNext": result.Page < totalPages,
|
||||
"UnreadCount": result.Unread,
|
||||
"NotifyTypeNames": model.NotifyTypeNames,
|
||||
"AuditTypeNames": model.AuditTypeNames,
|
||||
}))
|
||||
}
|
||||
|
||||
// UnreadCount 获取未读消息数(API,供导航栏轮询)
|
||||
func (mc *MessageController) UnreadCount(c *gin.Context) {
|
||||
uidVal, exists := c.Get("uid")
|
||||
if !exists {
|
||||
common.Ok(c, gin.H{"unread": 0})
|
||||
return
|
||||
}
|
||||
|
||||
count, err := mc.notifService.CountUnread(uidVal.(uint))
|
||||
if err != nil {
|
||||
common.Ok(c, gin.H{"unread": 0})
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, gin.H{"unread": count})
|
||||
}
|
||||
|
||||
// MarkRead 标记单条消息已读(API)
|
||||
func (mc *MessageController) MarkRead(c *gin.Context) {
|
||||
uidVal, exists := c.Get("uid")
|
||||
if !exists {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
idStr := c.Param("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "消息 ID 无效")
|
||||
return
|
||||
}
|
||||
|
||||
if err := mc.notifService.MarkRead(uint(id), uidVal.(uint)); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "操作失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "已标记为已读")
|
||||
}
|
||||
|
||||
// MarkAllRead 一键全部已读(API)
|
||||
func (mc *MessageController) MarkAllRead(c *gin.Context) {
|
||||
uidVal, exists := c.Get("uid")
|
||||
if !exists {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
if err := mc.notifService.MarkAllRead(uidVal.(uint)); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "操作失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "已全部标为已读")
|
||||
}
|
||||
@ -11,26 +11,38 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// profileProvider SettingsController 对 Service 层的最小依赖(ISP:2 个方法)
|
||||
// profileProvider SettingsController 对 Service 层的最小依赖(ISP:4 个方法)
|
||||
type profileProvider interface {
|
||||
GetProfile(userID uint) (*model.User, error)
|
||||
UpdateProfile(userID uint, username, bio string) error
|
||||
ChangePassword(userID uint, currentPassword, newPassword string) error
|
||||
DeleteAccount(userID uint, password, reason string) error
|
||||
}
|
||||
|
||||
// avatarProvider 头像上传对 Service 层的最小依赖(ISP:1 个方法)
|
||||
// avatarProvider 头像上传对 Service 层的最小依赖(ISP:2 个方法)
|
||||
type avatarProvider interface {
|
||||
ProcessAvatar(userID uint, file io.Reader, contentType string, cropX, cropY, cropSize int) (string, error)
|
||||
ProcessImage(userID uint, file io.Reader, contentType string, cropX, cropY, cropSize int) (string, error)
|
||||
}
|
||||
|
||||
// auditSubmittable 个人设置对审核服务的依赖(ISP:3 个方法)
|
||||
type auditSubmittable interface {
|
||||
ShouldAudit(userID uint) (bool, error)
|
||||
SubmitProfileChanges(userID uint, currentUser *model.User, newUsername, newBio string) error
|
||||
Submit(userID uint, auditType, newValue string) error
|
||||
GetPendingTypes(userID uint) ([]string, error)
|
||||
}
|
||||
|
||||
// SettingsController 个人设置控制器
|
||||
type SettingsController struct {
|
||||
authService profileProvider
|
||||
avatarService avatarProvider
|
||||
auditService auditSubmittable
|
||||
}
|
||||
|
||||
// NewSettingsController 构造函数
|
||||
func NewSettingsController(authService profileProvider, avatarService avatarProvider) *SettingsController {
|
||||
return &SettingsController{authService: authService, avatarService: avatarService}
|
||||
func NewSettingsController(authService profileProvider, avatarService avatarProvider, auditService auditSubmittable) *SettingsController {
|
||||
return &SettingsController{authService: authService, avatarService: avatarService, auditService: auditService}
|
||||
}
|
||||
|
||||
// SettingsPage 个人设置页面(需登录)
|
||||
@ -55,17 +67,23 @@ func (sc *SettingsController) SettingsPage(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 查询待审核类型(用于前端显示审核提示)
|
||||
pendingTypes, _ := sc.auditService.GetPendingTypes(uid)
|
||||
|
||||
c.HTML(http.StatusOK, "settings/index.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "个人设置",
|
||||
"ExtraCSS": "/static/css/settings.css",
|
||||
"ActiveTab": tab,
|
||||
"User": user,
|
||||
"RoleName": model.RoleDisplayNames[user.Role],
|
||||
"StatusName": model.StatusDisplayNames[user.Status],
|
||||
"Title": "个人设置",
|
||||
"ExtraCSS": "/static/css/settings.css",
|
||||
"ActiveTab": tab,
|
||||
"User": user,
|
||||
"RoleName": model.RoleDisplayNames[user.Role],
|
||||
"StatusName": model.StatusDisplayNames[user.Status],
|
||||
"PendingTypes": pendingTypes,
|
||||
"AuditTypes": model.AuditTypeNames,
|
||||
}))
|
||||
}
|
||||
|
||||
// UpdateProfile 修改个人资料(用户名 + 个性签名,需登录)
|
||||
// 普通用户走审核流程,管理员及以上直接落库
|
||||
func (sc *SettingsController) UpdateProfile(c *gin.Context) {
|
||||
uid, exists := c.Get("uid")
|
||||
if !exists {
|
||||
@ -82,7 +100,31 @@ func (sc *SettingsController) UpdateProfile(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := sc.authService.UpdateProfile(uid.(uint), req.Username, req.Bio); err != nil {
|
||||
userID := uid.(uint)
|
||||
|
||||
// 判断是否需要审核
|
||||
shouldAudit, err := sc.auditService.ShouldAudit(userID)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "操作失败")
|
||||
return
|
||||
}
|
||||
|
||||
if shouldAudit {
|
||||
user, err := sc.authService.GetProfile(userID)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "操作失败")
|
||||
return
|
||||
}
|
||||
if err := sc.auditService.SubmitProfileChanges(userID, user, req.Username, req.Bio); err != nil {
|
||||
handleAuditSubmitError(c, err)
|
||||
return
|
||||
}
|
||||
common.OkMessage(c, "修改已提交审核,通过前当前信息保持不变")
|
||||
return
|
||||
}
|
||||
|
||||
// 管理员及以上直接更新
|
||||
if err := sc.authService.UpdateProfile(userID, req.Username, req.Bio); err != nil {
|
||||
handleSettingsError(c, err)
|
||||
return
|
||||
}
|
||||
@ -91,6 +133,7 @@ func (sc *SettingsController) UpdateProfile(c *gin.Context) {
|
||||
}
|
||||
|
||||
// UploadAvatar 上传头像(需登录,multipart/form-data)
|
||||
// 普通用户走审核流程,管理员及以上直接更新
|
||||
func (sc *SettingsController) UploadAvatar(c *gin.Context) {
|
||||
uid, exists := c.Get("uid")
|
||||
if !exists {
|
||||
@ -110,7 +153,32 @@ func (sc *SettingsController) UploadAvatar(c *gin.Context) {
|
||||
cropY, _ := strconv.Atoi(c.PostForm("crop_y"))
|
||||
cropSize, _ := strconv.Atoi(c.PostForm("crop_size"))
|
||||
|
||||
url, err := sc.avatarService.ProcessAvatar(uid.(uint), file, header.Header.Get("Content-Type"), cropX, cropY, cropSize)
|
||||
userID := uid.(uint)
|
||||
|
||||
// 判断是否需要审核
|
||||
shouldAudit, err := sc.auditService.ShouldAudit(userID)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "操作失败")
|
||||
return
|
||||
}
|
||||
|
||||
if shouldAudit {
|
||||
// 仅处理图片,不更新用户
|
||||
avatarURL, err := sc.avatarService.ProcessImage(userID, file, header.Header.Get("Content-Type"), cropX, cropY, cropSize)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if err := sc.auditService.Submit(userID, model.AuditTypeAvatar, avatarURL); err != nil {
|
||||
handleAuditSubmitError(c, err)
|
||||
return
|
||||
}
|
||||
common.OkMessage(c, "头像已提交审核,通过前当前头像保持不变")
|
||||
return
|
||||
}
|
||||
|
||||
// 管理员及以上直接更新
|
||||
url, err := sc.avatarService.ProcessAvatar(userID, file, header.Header.Get("Content-Type"), cropX, cropY, cropSize)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
@ -119,6 +187,56 @@ func (sc *SettingsController) UploadAvatar(c *gin.Context) {
|
||||
common.Ok(c, gin.H{"url": url})
|
||||
}
|
||||
|
||||
// ChangePassword 修改密码(需登录)
|
||||
func (sc *SettingsController) ChangePassword(c *gin.Context) {
|
||||
uid, exists := c.Get("uid")
|
||||
if !exists {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
CurrentPassword string `json:"current_password" binding:"required"`
|
||||
NewPassword string `json:"new_password" binding:"required,min=8"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "请检查输入")
|
||||
return
|
||||
}
|
||||
|
||||
if err := sc.authService.ChangePassword(uid.(uint), req.CurrentPassword, req.NewPassword); err != nil {
|
||||
handleSettingsError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "密码已修改,请重新登录")
|
||||
}
|
||||
|
||||
// DeleteAccount 自助注销账号(需登录,验证密码 + 注销原因)
|
||||
func (sc *SettingsController) DeleteAccount(c *gin.Context) {
|
||||
uid, exists := c.Get("uid")
|
||||
if !exists {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Password string `json:"password" binding:"required"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "请检查输入")
|
||||
return
|
||||
}
|
||||
|
||||
if err := sc.authService.DeleteAccount(uid.(uint), req.Password, req.Reason); err != nil {
|
||||
handleSettingsError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "账号已注销,7 天内重新登录即可恢复")
|
||||
}
|
||||
|
||||
// handleSettingsError 统一处理 settings 接口的 service 层错误
|
||||
func handleSettingsError(c *gin.Context, err error) {
|
||||
switch err {
|
||||
@ -128,7 +246,44 @@ func handleSettingsError(c *gin.Context, err error) {
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
case common.ErrBioTooLong:
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
case common.ErrIncorrectPassword:
|
||||
common.Error(c, http.StatusForbidden, err.Error())
|
||||
case common.ErrOwnerCannotDelete:
|
||||
common.Error(c, http.StatusForbidden, err.Error())
|
||||
default:
|
||||
common.Error(c, http.StatusInternalServerError, "操作失败")
|
||||
}
|
||||
}
|
||||
|
||||
// handleAuditSubmitError 统一处理审核提交的错误
|
||||
func handleAuditSubmitError(c *gin.Context, err error) {
|
||||
switch err {
|
||||
case common.ErrAuditDisabled:
|
||||
common.Error(c, http.StatusForbidden, "审核功能未开启")
|
||||
case common.ErrAuditTypeOff:
|
||||
common.Error(c, http.StatusForbidden, "该类型审核未开启,请联系管理员")
|
||||
case common.ErrUsernameTaken:
|
||||
common.Error(c, http.StatusConflict, err.Error())
|
||||
default:
|
||||
common.Error(c, http.StatusInternalServerError, "提交审核失败")
|
||||
}
|
||||
}
|
||||
|
||||
// AuditStatus 查询当前用户的待审核类型(需登录)
|
||||
func (sc *SettingsController) AuditStatus(c *gin.Context) {
|
||||
uid, exists := c.Get("uid")
|
||||
if !exists {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
types, err := sc.auditService.GetPendingTypes(uid.(uint))
|
||||
if err != nil {
|
||||
common.Ok(c, gin.H{"pending_types": []string{}})
|
||||
return
|
||||
}
|
||||
if types == nil {
|
||||
types = []string{}
|
||||
}
|
||||
common.Ok(c, gin.H{"pending_types": types})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user