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:
@ -4,9 +4,6 @@ import (
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
)
|
||||
|
||||
// AdminService 管理后台业务逻辑
|
||||
// 集中处理所有权限边界检查,避免胖控制器
|
||||
type AdminService struct {
|
||||
userRepo userAdminStore
|
||||
}
|
||||
@ -34,20 +31,15 @@ type ListUsersResult struct {
|
||||
|
||||
// ListUsers 分页搜索用户列表
|
||||
func (s *AdminService) ListUsers(params ListUsersParams) (*ListUsersResult, error) {
|
||||
if params.Page < 1 {
|
||||
params.Page = 1
|
||||
}
|
||||
if params.PageSize < 1 || params.PageSize > 100 {
|
||||
params.PageSize = 20
|
||||
}
|
||||
offset := (params.Page - 1) * params.PageSize
|
||||
p := common.Pagination{Page: params.Page, PageSize: params.PageSize}
|
||||
p.DefaultPagination()
|
||||
|
||||
total, err := s.userRepo.CountSearchUsers(params.Keyword, params.Role, params.Status)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
users, err := s.userRepo.SearchUsers(params.Keyword, params.Role, params.Status, offset, params.PageSize)
|
||||
users, err := s.userRepo.SearchUsers(params.Keyword, params.Role, params.Status, p.Offset(), p.PageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -55,7 +47,7 @@ func (s *AdminService) ListUsers(params ListUsersParams) (*ListUsersResult, erro
|
||||
return &ListUsersResult{
|
||||
Users: users,
|
||||
Total: total,
|
||||
Page: params.Page,
|
||||
Page: p.Page,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
295
internal/service/audit_service.go
Normal file
295
internal/service/audit_service.go
Normal file
@ -0,0 +1,295 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/config"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// auditRepo AuditService 所需的最小仓储接口(ISP)
|
||||
type auditRepo interface {
|
||||
Create(audit *model.AuditSubmission) error
|
||||
FindByID(id uint) (*model.AuditSubmission, error)
|
||||
FindPendingByUserAndType(userID uint, auditType string) (*model.AuditSubmission, error)
|
||||
Update(audit *model.AuditSubmission) error
|
||||
ListAudits(auditType, status string, offset, limit int) ([]model.AuditSubmission, error)
|
||||
CountAudits(auditType, status string) (int64, error)
|
||||
FindPendingByUserID(userID uint) ([]model.AuditSubmission, error)
|
||||
ExistsPendingByTypeAndValue(auditType, newValue string, excludeUserID uint) (bool, error)
|
||||
}
|
||||
|
||||
// userProfileStore 审核服务所需的最小用户仓储接口(ISP)
|
||||
type userProfileStore interface {
|
||||
FindByID(id uint) (*model.User, error)
|
||||
Update(user *model.User) error
|
||||
ExistsByUsername(username string) (bool, error)
|
||||
}
|
||||
|
||||
// siteSettingsChecker 审核服务所需的站点设置接口(ISP:仅读取审核开关)
|
||||
type siteSettingsChecker interface {
|
||||
IsAuditEnabled() bool
|
||||
IsAuditTypeEnabled(auditType string, defaultVal bool) bool
|
||||
}
|
||||
|
||||
// auditNotifier 审核服务所需的通知接口(ISP:审核通过/拒绝时发送通知)
|
||||
type auditNotifier interface {
|
||||
NotifyAuditApproved(userID uint, auditType string, relatedID uint)
|
||||
NotifyAuditRejected(userID uint, auditType, reason string, relatedID uint)
|
||||
}
|
||||
|
||||
// AuditService 审核业务逻辑
|
||||
type AuditService struct {
|
||||
auditRepo auditRepo
|
||||
userRepo userProfileStore
|
||||
settings siteSettingsChecker
|
||||
defaultCfg config.AuditConfig
|
||||
notifier auditNotifier
|
||||
}
|
||||
|
||||
// NewAuditService 构造函数
|
||||
func NewAuditService(auditRepo auditRepo, userRepo userProfileStore, settings siteSettingsChecker, cfg config.AuditConfig, notifier auditNotifier) *AuditService {
|
||||
return &AuditService{
|
||||
auditRepo: auditRepo,
|
||||
userRepo: userRepo,
|
||||
settings: settings,
|
||||
defaultCfg: cfg,
|
||||
notifier: notifier,
|
||||
}
|
||||
}
|
||||
|
||||
// ErrXxx 重导出
|
||||
var (
|
||||
ErrAuditNotFound = common.ErrAuditNotFound
|
||||
ErrAuditNotPending = common.ErrAuditNotPending
|
||||
ErrAuditDisabled = common.ErrAuditDisabled
|
||||
ErrAuditTypeOff = common.ErrAuditTypeOff
|
||||
)
|
||||
|
||||
// ShouldAudit 判断指定用户是否需要走审核流程
|
||||
// 规则:admin 及以上角色免审
|
||||
func (s *AuditService) ShouldAudit(userID uint) (bool, error) {
|
||||
user, err := s.userRepo.FindByID(userID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return !model.HasMinRole(user.Role, model.RoleAdmin), nil
|
||||
}
|
||||
|
||||
// Submit 提交审核
|
||||
// - 总开关未开 → 返回 ErrAuditDisabled
|
||||
// - 类型开关未开 → 返回 ErrAuditTypeOff
|
||||
// - 用户名类型 → 先检查是否已被占用
|
||||
// - 若存在同类型 pending → 标记旧记录为 rejected(理由"用户重新提交"),创建新 pending
|
||||
func (s *AuditService) Submit(userID uint, auditType, newValue string) error {
|
||||
// 检查总开关
|
||||
if !s.settings.IsAuditEnabled() {
|
||||
return ErrAuditDisabled
|
||||
}
|
||||
|
||||
// 检查类型开关
|
||||
if !s.settings.IsAuditTypeEnabled(auditType, s.typeDefault(auditType)) {
|
||||
return ErrAuditTypeOff
|
||||
}
|
||||
|
||||
// 用户名冲突检查(提交时即拦截,避免提交到后台后审核失败)
|
||||
if auditType == model.AuditTypeUsername {
|
||||
// 1) users 表中已被占用
|
||||
exists, err := s.userRepo.ExistsByUsername(newValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
return ErrUsernameTaken
|
||||
}
|
||||
// 2) 审核表中已有其他用户提交了同名 pending
|
||||
pendingExists, err := s.auditRepo.ExistsPendingByTypeAndValue(auditType, newValue, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if pendingExists {
|
||||
return ErrUsernameTaken
|
||||
}
|
||||
}
|
||||
|
||||
// 覆盖旧的同类型 pending
|
||||
existing, err := s.auditRepo.FindPendingByUserAndType(userID, auditType)
|
||||
if err == nil {
|
||||
reason := "用户重新提交"
|
||||
existing.Status = model.AuditStatusRejected
|
||||
existing.RejectReason = &reason
|
||||
_ = s.auditRepo.Update(existing)
|
||||
}
|
||||
|
||||
submission := &model.AuditSubmission{
|
||||
UserID: userID,
|
||||
AuditType: auditType,
|
||||
NewValue: newValue,
|
||||
Status: model.AuditStatusPending,
|
||||
}
|
||||
return s.auditRepo.Create(submission)
|
||||
}
|
||||
|
||||
// SubmitProfileChanges 批量提交资料变更(用户名/签名),每个变更字段独立提交
|
||||
// 仅提交有变更的字段,无变更的跳过
|
||||
func (s *AuditService) SubmitProfileChanges(userID uint, currentUser *model.User, newUsername, newBio string) error {
|
||||
if newUsername != "" && newUsername != currentUser.Username {
|
||||
if err := s.Submit(userID, model.AuditTypeUsername, newUsername); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if newBio != "" && newBio != currentUser.Bio {
|
||||
if err := s.Submit(userID, model.AuditTypeBio, newBio); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Approve 通过审核 → 更新 User 表对应字段
|
||||
// 仅审核人可操作,不可审核自己的提交
|
||||
func (s *AuditService) Approve(reviewerID uint, submissionID uint) error {
|
||||
return s.review(reviewerID, submissionID, true, "")
|
||||
}
|
||||
|
||||
// Reject 拒绝审核 → 记录拒绝理由
|
||||
func (s *AuditService) Reject(reviewerID uint, submissionID uint, reason string) error {
|
||||
return s.review(reviewerID, submissionID, false, reason)
|
||||
}
|
||||
|
||||
// review 通用审核操作
|
||||
func (s *AuditService) review(reviewerID uint, submissionID uint, approved bool, reason string) error {
|
||||
// 1. 查审核记录
|
||||
submission, err := s.auditRepo.FindByID(submissionID)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return ErrAuditNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// 2. 必须 pending
|
||||
if submission.Status != model.AuditStatusPending {
|
||||
return ErrAuditNotPending
|
||||
}
|
||||
|
||||
// 3. 查审核人信息
|
||||
reviewer, err := s.userRepo.FindByID(reviewerID)
|
||||
if err != nil {
|
||||
return common.ErrUserNotFound
|
||||
}
|
||||
|
||||
// 5. 标记审核结果
|
||||
submission.ReviewedBy = &reviewerID
|
||||
submission.ReviewerName = &reviewer.Username
|
||||
if approved {
|
||||
submission.Status = model.AuditStatusApproved
|
||||
// 更新 User 表对应字段
|
||||
if err := s.applyApproval(submission); err != nil {
|
||||
return err
|
||||
}
|
||||
// 通知用户审核通过
|
||||
if s.notifier != nil {
|
||||
s.notifier.NotifyAuditApproved(submission.UserID, submission.AuditType, submission.ID)
|
||||
}
|
||||
} else {
|
||||
submission.Status = model.AuditStatusRejected
|
||||
submission.RejectReason = &reason
|
||||
// 通知用户审核被拒
|
||||
if s.notifier != nil {
|
||||
reasonMsg := reason
|
||||
s.notifier.NotifyAuditRejected(submission.UserID, submission.AuditType, reasonMsg, submission.ID)
|
||||
}
|
||||
}
|
||||
return s.auditRepo.Update(submission)
|
||||
}
|
||||
|
||||
// applyApproval 将审核通过的内容写入 User 表
|
||||
// 用户名审批前再次检查冲突(防止提交到审批期间被其他用户抢占)
|
||||
func (s *AuditService) applyApproval(submission *model.AuditSubmission) error {
|
||||
user, err := s.userRepo.FindByID(submission.UserID)
|
||||
if err != nil {
|
||||
return common.ErrUserNotFound
|
||||
}
|
||||
|
||||
switch submission.AuditType {
|
||||
case model.AuditTypeUsername:
|
||||
exists, err := s.userRepo.ExistsByUsername(submission.NewValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
return ErrUsernameTaken
|
||||
}
|
||||
user.Username = submission.NewValue
|
||||
case model.AuditTypeAvatar:
|
||||
user.Avatar = submission.NewValue
|
||||
case model.AuditTypeBio:
|
||||
user.Bio = submission.NewValue
|
||||
}
|
||||
return s.userRepo.Update(user)
|
||||
}
|
||||
|
||||
// List 分页查询审核列表
|
||||
func (s *AuditService) List(auditType, status string, page, pageSize int) (*AuditListResult, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 || pageSize > 100 {
|
||||
pageSize = 20
|
||||
}
|
||||
offset := (page - 1) * pageSize
|
||||
|
||||
total, err := s.auditRepo.CountAudits(auditType, status)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items, err := s.auditRepo.ListAudits(auditType, status, offset, pageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if items == nil {
|
||||
items = []model.AuditSubmission{}
|
||||
}
|
||||
|
||||
return &AuditListResult{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: page,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetPendingTypes 获取用户所有待审核类型(用于个人中心提示)
|
||||
func (s *AuditService) GetPendingTypes(userID uint) ([]string, error) {
|
||||
submissions, err := s.auditRepo.FindPendingByUserID(userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
types := make([]string, 0, len(submissions))
|
||||
for _, sub := range submissions {
|
||||
types = append(types, sub.AuditType)
|
||||
}
|
||||
return types, nil
|
||||
}
|
||||
|
||||
// typeDefault 获取某审核类型在 config.yaml 中的默认开关值
|
||||
func (s *AuditService) typeDefault(auditType string) bool {
|
||||
switch auditType {
|
||||
case model.AuditTypeUsername:
|
||||
return s.defaultCfg.UsernameAudit
|
||||
case model.AuditTypeAvatar:
|
||||
return s.defaultCfg.AvatarAudit
|
||||
case model.AuditTypeBio:
|
||||
return s.defaultCfg.BioAudit
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// AuditListResult 审核列表查询结果
|
||||
type AuditListResult struct {
|
||||
Items []model.AuditSubmission `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
}
|
||||
@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
@ -25,18 +26,21 @@ func NewAuthService(userRepo userAuthStore, tokenSvc tokenProvider, cfg *config.
|
||||
}
|
||||
|
||||
var (
|
||||
ErrEmailExists = common.ErrEmailExists
|
||||
ErrUsernameTaken = common.ErrUsernameTaken
|
||||
ErrInvalidCred = common.ErrInvalidCred
|
||||
ErrUserNotFound = common.ErrUserNotFound
|
||||
ErrUserBanned = common.ErrUserBanned
|
||||
ErrUserLocked = common.ErrUserLocked
|
||||
ErrUserDeleted = common.ErrUserDeleted
|
||||
ErrWeakPassword = common.ErrWeakPassword
|
||||
ErrTokenExpired = common.ErrTokenExpired
|
||||
ErrTokenInvalid = common.ErrTokenInvalid
|
||||
ErrTokenRevoked = common.ErrTokenRevoked
|
||||
ErrPermissionDenied = common.ErrPermissionDenied
|
||||
ErrEmailExists = common.ErrEmailExists
|
||||
ErrUsernameTaken = common.ErrUsernameTaken
|
||||
ErrInvalidCred = common.ErrInvalidCred
|
||||
ErrUserNotFound = common.ErrUserNotFound
|
||||
ErrUserBanned = common.ErrUserBanned
|
||||
ErrUserLocked = common.ErrUserLocked
|
||||
ErrUserDeleted = common.ErrUserDeleted
|
||||
ErrWeakPassword = common.ErrWeakPassword
|
||||
ErrTokenExpired = common.ErrTokenExpired
|
||||
ErrTokenInvalid = common.ErrTokenInvalid
|
||||
ErrTokenRevoked = common.ErrTokenRevoked
|
||||
ErrPermissionDenied = common.ErrPermissionDenied
|
||||
ErrIncorrectPassword = common.ErrIncorrectPassword
|
||||
ErrNeedsConfirmRestore = common.ErrNeedsConfirmRestore
|
||||
ErrOwnerCannotDelete = common.ErrOwnerCannotDelete
|
||||
)
|
||||
|
||||
var pwLetter = regexp.MustCompile(`[a-zA-Z]`)
|
||||
@ -68,7 +72,8 @@ func validatePassword(pw string) error {
|
||||
// Register 注册
|
||||
// 流程:密码强度 → 邮箱查重 → 哈希 → 生成唯一用户名 → 创建 → access JWT + refresh JWT
|
||||
// rememberMe=true: refresh Cookie 持久化(30天);false: session cookie(关浏览器即清除)
|
||||
func (s *AuthService) Register(req model.RegisterRequest) (string, string, *model.User, error) {
|
||||
// regIP: 注册 IP 地址
|
||||
func (s *AuthService) Register(req model.RegisterRequest, regIP string) (string, string, *model.User, error) {
|
||||
// 1. 密码强度
|
||||
if err := validatePassword(req.Password); err != nil {
|
||||
return "", "", nil, err
|
||||
@ -102,6 +107,7 @@ func (s *AuthService) Register(req model.RegisterRequest) (string, string, *mode
|
||||
Username: username,
|
||||
Role: model.RoleUser,
|
||||
Status: model.StatusActive,
|
||||
RegIP: regIP,
|
||||
}
|
||||
if err := s.userRepo.Create(user); err != nil {
|
||||
return "", "", nil, err
|
||||
@ -123,24 +129,25 @@ func (s *AuthService) Register(req model.RegisterRequest) (string, string, *mode
|
||||
}
|
||||
|
||||
// Login 登录
|
||||
// 流程:按邮箱查找 → 检查状态 → 验证密码 → access JWT + refresh JWT
|
||||
// 流程:按邮箱查找 → 已注销则验证密码后要求二次确认 → 检查状态 → 验证密码 → 记录登录 IP/时间 → access JWT + refresh JWT
|
||||
// 防时序攻击:邮箱不存在时仍执行完整 bcrypt 比对
|
||||
// rememberMe=true: refresh Cookie 持久化(30天);false: session cookie(关浏览器即清除)
|
||||
func (s *AuthService) Login(req model.LoginRequest) (string, string, *model.User, error) {
|
||||
// loginIP: 登录 IP 地址
|
||||
// 若用户处于 deleted 状态且密码正确 → 返回 ErrNeedsConfirmRestore(不自动恢复,不签发 token)
|
||||
func (s *AuthService) Login(req model.LoginRequest, loginIP string) (string, string, *model.User, error) {
|
||||
user, err := s.userRepo.FindByEmail(req.Email)
|
||||
if err != nil {
|
||||
_ = bcrypt.CompareHashAndPassword(dummyHash, []byte(req.Password))
|
||||
return "", "", nil, ErrInvalidCred
|
||||
}
|
||||
|
||||
// 已注销(deleted)→ 自动恢复
|
||||
// 已注销(deleted)→ 验证密码后要求二次确认,不自动恢复
|
||||
if user.Status == model.StatusDeleted {
|
||||
user.Status = model.StatusActive
|
||||
user.DeletedAt = gorm.DeletedAt{}
|
||||
if err := s.userRepo.Update(user); err != nil {
|
||||
return "", "", nil, err
|
||||
if !common.CheckPassword(req.Password, user.PasswordHash) {
|
||||
_ = bcrypt.CompareHashAndPassword(dummyHash, []byte(req.Password))
|
||||
return "", "", nil, ErrInvalidCred
|
||||
}
|
||||
// 恢复后继续正常登录流程
|
||||
return "", "", nil, ErrNeedsConfirmRestore
|
||||
}
|
||||
|
||||
// 永久锁定
|
||||
@ -158,6 +165,14 @@ func (s *AuthService) Login(req model.LoginRequest) (string, string, *model.User
|
||||
return "", "", nil, ErrInvalidCred
|
||||
}
|
||||
|
||||
// 记录登录 IP 和时间
|
||||
now := time.Now()
|
||||
user.LastLoginIP = loginIP
|
||||
user.LastLoginAt = &now
|
||||
if err := s.userRepo.Update(user); err != nil {
|
||||
return "", "", nil, err
|
||||
}
|
||||
|
||||
// 生成 access JWT
|
||||
accessToken, err := s.tokenService.BuildAccessToken(user)
|
||||
if err != nil {
|
||||
@ -173,6 +188,47 @@ func (s *AuthService) Login(req model.LoginRequest) (string, string, *model.User
|
||||
return accessToken, refreshToken, user, nil
|
||||
}
|
||||
|
||||
// ConfirmRestore 二次确认恢复已注销账号
|
||||
// 流程:按邮箱查找 → 验证密码 → 恢复为 active → 记录登录 IP/时间 → 签发 token
|
||||
func (s *AuthService) ConfirmRestore(req model.LoginRequest, loginIP string) (string, string, *model.User, error) {
|
||||
user, err := s.userRepo.FindByEmail(req.Email)
|
||||
if err != nil {
|
||||
_ = bcrypt.CompareHashAndPassword(dummyHash, []byte(req.Password))
|
||||
return "", "", nil, ErrInvalidCred
|
||||
}
|
||||
|
||||
// 仅 deleted 状态允许恢复
|
||||
if user.Status != model.StatusDeleted {
|
||||
return "", "", nil, ErrUserNotFound
|
||||
}
|
||||
|
||||
if !common.CheckPassword(req.Password, user.PasswordHash) {
|
||||
return "", "", nil, ErrInvalidCred
|
||||
}
|
||||
|
||||
// 恢复账号
|
||||
user.Status = model.StatusActive
|
||||
user.DeletedAt = gorm.DeletedAt{}
|
||||
now := time.Now()
|
||||
user.LastLoginIP = loginIP
|
||||
user.LastLoginAt = &now
|
||||
if err := s.userRepo.Update(user); err != nil {
|
||||
return "", "", nil, err
|
||||
}
|
||||
|
||||
accessToken, err := s.tokenService.BuildAccessToken(user)
|
||||
if err != nil {
|
||||
return "", "", nil, err
|
||||
}
|
||||
|
||||
refreshToken, err := s.tokenService.BuildRefreshToken(user, req.RememberMe)
|
||||
if err != nil {
|
||||
return "", "", nil, err
|
||||
}
|
||||
|
||||
return accessToken, refreshToken, user, nil
|
||||
}
|
||||
|
||||
// CheckEmail 检查邮箱是否已被注册(无需认证的轻量检查)
|
||||
func (s *AuthService) CheckEmail(email string) (bool, error) {
|
||||
return s.userRepo.ExistsByEmail(email)
|
||||
@ -183,6 +239,68 @@ func (s *AuthService) GetProfile(userID uint) (*model.User, error) {
|
||||
return s.userRepo.FindByID(userID)
|
||||
}
|
||||
|
||||
// ChangePassword 修改密码
|
||||
// 流程:验证当前密码 → 校验新密码强度 → 哈希 → 更新 → 吊销所有 JWT(强制重新登录)
|
||||
func (s *AuthService) ChangePassword(userID uint, currentPassword, newPassword string) error {
|
||||
user, err := s.userRepo.FindByID(userID)
|
||||
if err != nil {
|
||||
return common.ErrUserNotFound
|
||||
}
|
||||
|
||||
// 验证当前密码
|
||||
if !common.CheckPassword(currentPassword, user.PasswordHash) {
|
||||
return ErrIncorrectPassword
|
||||
}
|
||||
|
||||
// 新密码强度校验
|
||||
if err := validatePassword(newPassword); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 哈希新密码
|
||||
hash, err := common.HashPassword(newPassword, s.cfg.Bcrypt.Cost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
user.PasswordHash = hash
|
||||
if err := s.userRepo.Update(user); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 强制所有设备重新登录(安全性)
|
||||
return s.InvalidateSessions(userID)
|
||||
}
|
||||
|
||||
// DeleteAccount 用户自主注销
|
||||
// 流程:检查角色 → 验证密码 → 记录原因 → 设置 deleted 状态 → 吊销所有 JWT → 7 天冷却期内登录需二次确认恢复
|
||||
func (s *AuthService) DeleteAccount(userID uint, password, reason string) error {
|
||||
user, err := s.userRepo.FindByID(userID)
|
||||
if err != nil {
|
||||
return common.ErrUserNotFound
|
||||
}
|
||||
|
||||
// 站长不允许自主注销(避免权限体系死锁)
|
||||
if user.Role == model.RoleOwner {
|
||||
return ErrOwnerCannotDelete
|
||||
}
|
||||
|
||||
// 验证当前密码(防止 CSRF 或未授权操作)
|
||||
if !common.CheckPassword(password, user.PasswordHash) {
|
||||
return ErrIncorrectPassword
|
||||
}
|
||||
|
||||
user.Status = model.StatusDeleted
|
||||
user.DeleteReason = reason
|
||||
|
||||
if err := s.userRepo.Update(user); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 递增 token_version,即时吊销所有 JWT 强制退登
|
||||
return s.InvalidateSessions(userID)
|
||||
}
|
||||
|
||||
// InvalidateSessions 吊销某用户所有 JWT(递增 token_version,强制所有设备重新登录)
|
||||
// 适用场景:修改密码、账号被盗、管理员强制下线
|
||||
func (s *AuthService) InvalidateSessions(userID uint) error {
|
||||
|
||||
@ -36,6 +36,7 @@ const (
|
||||
type userAvatarStore interface {
|
||||
FindByID(id uint) (*model.User, error)
|
||||
Update(user *model.User) error
|
||||
FindByIDUnscoped(userID uint) (*model.User, error)
|
||||
}
|
||||
|
||||
// AvatarService 头像上传处理服务
|
||||
@ -49,10 +50,27 @@ func NewAvatarService(userRepo userAvatarStore) *AvatarService {
|
||||
return &AvatarService{userRepo: userRepo, storageDir: avatarStorageDir}
|
||||
}
|
||||
|
||||
// ProcessAvatar 处理头像上传流程
|
||||
// cropX, cropY, cropSize: 自定义裁切参数(原图像素坐标),全 0 则默认中心裁切
|
||||
// 返回头像 URL,失败返回错误
|
||||
// ProcessAvatar 处理头像上传流程(完整流程:处理图片 + 更新 User)
|
||||
func (s *AvatarService) ProcessAvatar(userID uint, file io.Reader, contentType string, cropX, cropY, cropSize int) (string, error) {
|
||||
avatarURL, err := s.ProcessImage(userID, file, contentType, cropX, cropY, cropSize)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
user, err := s.userRepo.FindByID(userID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("用户不存在")
|
||||
}
|
||||
user.Avatar = avatarURL
|
||||
if err := s.userRepo.Update(user); err != nil {
|
||||
return "", fmt.Errorf("更新头像失败")
|
||||
}
|
||||
|
||||
return avatarURL, nil
|
||||
}
|
||||
|
||||
// ProcessImage 处理头像上传流程(仅处理图片 + 保存文件,不更新 User,审核场景用)
|
||||
func (s *AvatarService) ProcessImage(userID uint, file io.Reader, contentType string, cropX, cropY, cropSize int) (string, error) {
|
||||
// 1. 检查文件类型(不支持 GIF:裁切后无法保持动画)
|
||||
if contentType != "image/jpeg" && contentType != "image/png" && contentType != "image/webp" {
|
||||
return "", fmt.Errorf("仅支持 JPEG、PNG、WebP 格式")
|
||||
@ -127,18 +145,7 @@ func (s *AvatarService) ProcessAvatar(userID uint, file io.Reader, contentType s
|
||||
return "", fmt.Errorf("保存文件失败")
|
||||
}
|
||||
|
||||
// 10. 更新用户头像字段
|
||||
user, err := s.userRepo.FindByID(userID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("用户不存在")
|
||||
}
|
||||
avatarURL := fmt.Sprintf("/uploads/avatars/%d_%d.webp", userID, ts)
|
||||
user.Avatar = avatarURL
|
||||
if err := s.userRepo.Update(user); err != nil {
|
||||
return "", fmt.Errorf("更新头像失败")
|
||||
}
|
||||
|
||||
return avatarURL, nil
|
||||
return fmt.Sprintf("/uploads/avatars/%d_%d.webp", userID, ts), nil
|
||||
}
|
||||
|
||||
// cleanOldAvatars 删除指定用户的所有旧头像文件(仅保留最新一次上传)
|
||||
|
||||
112
internal/service/notification_service.go
Normal file
112
internal/service/notification_service.go
Normal file
@ -0,0 +1,112 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
)
|
||||
|
||||
// notifRepo 通知服务所需的最小仓储接口(ISP)
|
||||
type notifRepo interface {
|
||||
Create(n *model.Notification) error
|
||||
ListByUser(userID uint, offset, limit int) ([]model.Notification, error)
|
||||
CountByUser(userID uint) (int64, error)
|
||||
CountUnread(userID uint) (int64, error)
|
||||
MarkRead(id, userID uint) error
|
||||
MarkAllRead(userID uint) error
|
||||
}
|
||||
|
||||
// NotificationService 消息/通知业务逻辑
|
||||
type NotificationService struct {
|
||||
repo notifRepo
|
||||
}
|
||||
|
||||
// NewNotificationService 构造函数
|
||||
func NewNotificationService(repo notifRepo) *NotificationService {
|
||||
return &NotificationService{repo: repo}
|
||||
}
|
||||
|
||||
// Create 创建消息
|
||||
func (s *NotificationService) Create(userID uint, notifyType, title, content string, relatedID *uint) error {
|
||||
n := &model.Notification{
|
||||
UserID: userID,
|
||||
NotifyType: notifyType,
|
||||
Title: title,
|
||||
Content: content,
|
||||
IsRead: false,
|
||||
RelatedID: relatedID,
|
||||
}
|
||||
return s.repo.Create(n)
|
||||
}
|
||||
|
||||
// List 分页查询用户消息列表
|
||||
func (s *NotificationService) List(userID uint, page, pageSize int) (*model.NotificationListResult, error) {
|
||||
p := common.Pagination{Page: page, PageSize: pageSize}
|
||||
p.DefaultPagination()
|
||||
|
||||
total, err := s.repo.CountByUser(userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items, err := s.repo.ListByUser(userID, p.Offset(), p.PageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if items == nil {
|
||||
items = []model.Notification{}
|
||||
}
|
||||
|
||||
totalPages := int((total + int64(p.PageSize) - 1) / int64(p.PageSize))
|
||||
unread, _ := s.CountUnread(userID)
|
||||
|
||||
return &model.NotificationListResult{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: p.Page,
|
||||
TotalPages: totalPages,
|
||||
Unread: unread,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CountUnread 统计未读消息数
|
||||
func (s *NotificationService) CountUnread(userID uint) (int64, error) {
|
||||
return s.repo.CountUnread(userID)
|
||||
}
|
||||
|
||||
// MarkRead 标记单条消息为已读
|
||||
func (s *NotificationService) MarkRead(id, userID uint) error {
|
||||
return s.repo.MarkRead(id, userID)
|
||||
}
|
||||
|
||||
// MarkAllRead 标记所有未读为已读
|
||||
func (s *NotificationService) MarkAllRead(userID uint) error {
|
||||
return s.repo.MarkAllRead(userID)
|
||||
}
|
||||
|
||||
// NotifyAuditApproved 审核通过通知
|
||||
func (s *NotificationService) NotifyAuditApproved(userID uint, auditType string, relatedID uint) {
|
||||
typeName := model.AuditTypeNames[auditType]
|
||||
if typeName == "" {
|
||||
typeName = auditType
|
||||
}
|
||||
_ = s.Create(userID, model.NotifyAuditApproved,
|
||||
"审核已通过",
|
||||
"你的"+typeName+"修改已通过审核",
|
||||
&relatedID)
|
||||
}
|
||||
|
||||
// NotifyAuditRejected 审核拒绝通知
|
||||
func (s *NotificationService) NotifyAuditRejected(userID uint, auditType, reason string, relatedID uint) {
|
||||
typeName := model.AuditTypeNames[auditType]
|
||||
if typeName == "" {
|
||||
typeName = auditType
|
||||
}
|
||||
content := "你的" + typeName + "修改被拒绝"
|
||||
if reason != "" {
|
||||
content += ",理由:" + reason
|
||||
}
|
||||
_ = s.Create(userID, model.NotifyAuditRejected,
|
||||
"审核未通过",
|
||||
content,
|
||||
&relatedID)
|
||||
}
|
||||
82
internal/service/site_setting_service.go
Normal file
82
internal/service/site_setting_service.go
Normal file
@ -0,0 +1,82 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// siteSettingsManager 站点设置服务所需的最小接口(ISP)
|
||||
type siteSettingsManager interface {
|
||||
Get(key, defaultVal string) string
|
||||
GetBool(key string, defaultVal bool) bool
|
||||
Set(key, value string) error
|
||||
SetBool(key string, value bool) error
|
||||
All() map[string]string
|
||||
}
|
||||
|
||||
// SiteSettingService 站点设置业务逻辑
|
||||
type SiteSettingService struct {
|
||||
settings siteSettingsManager
|
||||
}
|
||||
|
||||
// NewSiteSettingService 构造函数
|
||||
func NewSiteSettingService(settings siteSettingsManager) *SiteSettingService {
|
||||
return &SiteSettingService{settings: settings}
|
||||
}
|
||||
|
||||
// GetSettings 获取所有站点设置(仅 owner 可见)
|
||||
func (s *SiteSettingService) GetSettings() map[string]string {
|
||||
return s.settings.All()
|
||||
}
|
||||
|
||||
// UpdateSetting 更新单项设置
|
||||
func (s *SiteSettingService) UpdateSetting(key, value string) error {
|
||||
return s.settings.Set(key, value)
|
||||
}
|
||||
|
||||
// UpdateBoolSetting 更新布尔设置
|
||||
func (s *SiteSettingService) UpdateBoolSetting(key string, value bool) error {
|
||||
return s.settings.SetBool(key, value)
|
||||
}
|
||||
|
||||
// GetBool gets a boolean setting with a default
|
||||
func (s *SiteSettingService) GetBool(key string, defaultVal bool) bool {
|
||||
return s.settings.GetBool(key, defaultVal)
|
||||
}
|
||||
|
||||
// --- 审核相关设置快捷方法 ---
|
||||
|
||||
// AuditSettings 审核相关站点设置集合(用于前端展示)
|
||||
type AuditSettings struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
UsernameAudit bool `json:"username_audit"`
|
||||
AvatarAudit bool `json:"avatar_audit"`
|
||||
BioAudit bool `json:"bio_audit"`
|
||||
}
|
||||
|
||||
// GetAuditSettings 获取审核相关设置
|
||||
func (s *SiteSettingService) GetAuditSettings(defaultCfg *AuditDefaults) *AuditSettings {
|
||||
return &AuditSettings{
|
||||
Enabled: s.settings.GetBool("audit.enabled", defaultCfg.Enabled),
|
||||
UsernameAudit: s.settings.GetBool("audit.username_audit", defaultCfg.UsernameAudit),
|
||||
AvatarAudit: s.settings.GetBool("audit.avatar_audit", defaultCfg.AvatarAudit),
|
||||
BioAudit: s.settings.GetBool("audit.bio_audit", defaultCfg.BioAudit),
|
||||
}
|
||||
}
|
||||
|
||||
// AuditDefaults config.yaml 中的审核默认值
|
||||
type AuditDefaults struct {
|
||||
Enabled bool
|
||||
UsernameAudit bool
|
||||
AvatarAudit bool
|
||||
BioAudit bool
|
||||
}
|
||||
|
||||
// GetBoolSetting is a generic getter used by controllers
|
||||
func (s *SiteSettingService) GetBoolSetting(key string, defaultVal bool) bool {
|
||||
return s.settings.GetBool(key, defaultVal)
|
||||
}
|
||||
|
||||
// ParseBool 解析字符串为布尔值
|
||||
func ParseBool(v string) (bool, error) {
|
||||
return strconv.ParseBool(v)
|
||||
}
|
||||
Reference in New Issue
Block a user