## 新增功能 ### 消息通知中心 (全新模块) - 新增 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
227 lines
6.6 KiB
Go
227 lines
6.6 KiB
Go
package service
|
||
|
||
import (
|
||
"bytes"
|
||
"fmt"
|
||
"image"
|
||
_ "image/gif"
|
||
_ "image/jpeg"
|
||
_ "image/png"
|
||
"io"
|
||
"os"
|
||
"path/filepath"
|
||
"strconv"
|
||
"strings"
|
||
"time"
|
||
|
||
"metazone.cc/metalab/internal/model"
|
||
|
||
"github.com/chai2010/webp"
|
||
"golang.org/x/image/draw"
|
||
)
|
||
|
||
// 头像处理常量
|
||
const (
|
||
avatarMaxFileSize = 5 * 1024 * 1024 // 5MB
|
||
avatarMinWidth = 128 // 最小宽高,防止马赛克图被拉升
|
||
avatarMinHeight = 128
|
||
avatarMaxWidth = 3840
|
||
avatarMaxHeight = 2160
|
||
avatarOutputSize = 512
|
||
avatarTargetKB = 100
|
||
avatarStorageDir = "storage/uploads/avatars"
|
||
)
|
||
|
||
// userAvatarStore 头像服务所需的最小仓储接口
|
||
type userAvatarStore interface {
|
||
FindByID(id uint) (*model.User, error)
|
||
Update(user *model.User) error
|
||
FindByIDUnscoped(userID uint) (*model.User, error)
|
||
}
|
||
|
||
// AvatarService 头像上传处理服务
|
||
type AvatarService struct {
|
||
userRepo userAvatarStore
|
||
storageDir string
|
||
}
|
||
|
||
// NewAvatarService 构造函数
|
||
func NewAvatarService(userRepo userAvatarStore) *AvatarService {
|
||
return &AvatarService{userRepo: userRepo, storageDir: avatarStorageDir}
|
||
}
|
||
|
||
// 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 格式")
|
||
}
|
||
|
||
// 2. 读取全部字节并校验大小
|
||
data, err := io.ReadAll(io.LimitReader(file, avatarMaxFileSize+1))
|
||
if err != nil {
|
||
return "", fmt.Errorf("读取文件失败")
|
||
}
|
||
if len(data) > avatarMaxFileSize {
|
||
return "", fmt.Errorf("文件大小不能超过 5MB")
|
||
}
|
||
|
||
// 3. 解码图片(WebP 需显式调用 webp.Decode,Go 标准库不含 WebP 解码器)
|
||
var img image.Image
|
||
switch contentType {
|
||
case "image/webp":
|
||
img, err = webp.Decode(bytes.NewReader(data))
|
||
default:
|
||
img, _, err = image.Decode(bytes.NewReader(data))
|
||
}
|
||
if err != nil {
|
||
return "", fmt.Errorf("图片解码失败:%v", err)
|
||
}
|
||
bounds := img.Bounds()
|
||
w, h := bounds.Dx(), bounds.Dy()
|
||
if w > avatarMaxWidth || h > avatarMaxHeight {
|
||
return "", fmt.Errorf("图片分辨率不能超过 3840x2160")
|
||
}
|
||
if w < avatarMinWidth || h < avatarMinHeight {
|
||
return "", fmt.Errorf("图片分辨率不能低于 128x128")
|
||
}
|
||
|
||
// 4. 裁切为正方形(优先使用自定义裁切参数)
|
||
var cropped image.Image
|
||
if cropSize > 0 && cropX >= 0 && cropY >= 0 &&
|
||
cropX+cropSize <= w && cropY+cropSize <= h {
|
||
cropped = subImage(img, cropX, cropY, cropSize)
|
||
} else {
|
||
cropped = centerCrop(img)
|
||
}
|
||
|
||
// 5. 缩放至 512x512(CatmullRom 高质量)
|
||
resized := image.NewNRGBA(image.Rect(0, 0, avatarOutputSize, avatarOutputSize))
|
||
draw.CatmullRom.Scale(resized, resized.Bounds(), cropped, cropped.Bounds(), draw.Over, nil)
|
||
|
||
// 6. 编码为 WebP,目标 ≤100KB
|
||
webpData, err := encodeWebP(resized, avatarTargetKB*1024)
|
||
if err != nil {
|
||
return "", fmt.Errorf("图片编码失败:%v", err)
|
||
}
|
||
|
||
// 7. 确保存储目录存在
|
||
if err := os.MkdirAll(s.storageDir, 0755); err != nil {
|
||
return "", fmt.Errorf("创建存储目录失败")
|
||
}
|
||
|
||
// 8. 删除该用户的旧头像,仅保留最新
|
||
s.cleanOldAvatars(userID)
|
||
|
||
// 9. 原子写入:先写临时文件,再 rename 到最终路径
|
||
ts := time.Now().Unix()
|
||
filename := fmt.Sprintf("%d_%d.webp", userID, ts)
|
||
tmpPath := filepath.Join(s.storageDir, filename+".tmp")
|
||
finalPath := filepath.Join(s.storageDir, filename)
|
||
if err := os.WriteFile(tmpPath, webpData, 0644); err != nil {
|
||
return "", fmt.Errorf("写入临时文件失败")
|
||
}
|
||
if err := os.Rename(tmpPath, finalPath); err != nil {
|
||
os.Remove(tmpPath)
|
||
return "", fmt.Errorf("保存文件失败")
|
||
}
|
||
|
||
return fmt.Sprintf("/uploads/avatars/%d_%d.webp", userID, ts), nil
|
||
}
|
||
|
||
// cleanOldAvatars 删除指定用户的所有旧头像文件(仅保留最新一次上传)
|
||
func (s *AvatarService) cleanOldAvatars(userID uint) {
|
||
prefix := strconv.FormatUint(uint64(userID), 10) + "_"
|
||
entries, err := os.ReadDir(s.storageDir)
|
||
if err != nil {
|
||
return
|
||
}
|
||
for _, e := range entries {
|
||
if !e.IsDir() && strings.HasPrefix(e.Name(), prefix) && strings.HasSuffix(e.Name(), ".webp") {
|
||
os.Remove(filepath.Join(s.storageDir, e.Name()))
|
||
}
|
||
}
|
||
}
|
||
|
||
// subImage 从原图中裁切指定正方形区域
|
||
func subImage(img image.Image, x, y, size int) image.Image {
|
||
cropped := image.NewNRGBA(image.Rect(0, 0, size, size))
|
||
draw.Draw(cropped, cropped.Bounds(), img, image.Point{x, y}, draw.Src)
|
||
return cropped
|
||
}
|
||
|
||
// centerCrop 中心裁切为正方形(取 min(width, height))
|
||
func centerCrop(img image.Image) image.Image {
|
||
b := img.Bounds()
|
||
w, h := b.Dx(), b.Dy()
|
||
size := w
|
||
if h < size {
|
||
size = h
|
||
}
|
||
ox := (w - size) / 2
|
||
oy := (h - size) / 2
|
||
cropped := image.NewNRGBA(image.Rect(0, 0, size, size))
|
||
draw.Draw(cropped, cropped.Bounds(), img, image.Point{ox, oy}, draw.Src)
|
||
return cropped
|
||
}
|
||
|
||
// encodeWebP 编码为 WebP,通过二分查找质量参数使文件大小接近 targetBytes
|
||
func encodeWebP(img image.Image, targetBytes int) ([]byte, error) {
|
||
buf := &bytes.Buffer{}
|
||
|
||
// 如果图片非常简单(如纯色),即使 quality=1 也可能很小
|
||
if err := webp.Encode(buf, img, &webp.Options{Quality: 80}); err != nil {
|
||
return nil, err
|
||
}
|
||
if buf.Len() <= targetBytes {
|
||
return buf.Bytes(), nil
|
||
}
|
||
|
||
// 二分查找合适的质量参数
|
||
low, high := 1, 80
|
||
var best []byte
|
||
for low <= high {
|
||
mid := (low + high) / 2
|
||
buf.Reset()
|
||
if err := webp.Encode(buf, img, &webp.Options{Quality: float32(mid)}); err != nil {
|
||
return nil, err
|
||
}
|
||
if buf.Len() <= targetBytes {
|
||
best = make([]byte, buf.Len())
|
||
copy(best, buf.Bytes())
|
||
low = mid + 1 // 尝试更高画质
|
||
} else {
|
||
high = mid - 1
|
||
}
|
||
}
|
||
if best != nil {
|
||
return best, nil
|
||
}
|
||
// 降到底仍超限,返回最低质量
|
||
buf.Reset()
|
||
if err := webp.Encode(buf, img, &webp.Options{Quality: 1}); err != nil {
|
||
return nil, err
|
||
}
|
||
return buf.Bytes(), nil
|
||
}
|
||
|