287 lines
11 KiB
Go
287 lines
11 KiB
Go
package models
|
|
|
|
import (
|
|
"log/slog"
|
|
"time"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
const PasswordCryptLevel = 12
|
|
|
|
// 站点基础设置键名
|
|
const (
|
|
OptionSiteName = "site_name"
|
|
OptionSiteDesc = "site_desc"
|
|
OptionShowComments = "show_comments" // "1" 显示评论 / "0" 隐藏评论
|
|
OptionCommentPageSize = "comments_per_page" // 前台评论每页条数
|
|
)
|
|
|
|
// ==================== 用户模型 ====================
|
|
|
|
type User struct {
|
|
ID uint `gorm:"primaryKey" json:"id"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
|
Username string `gorm:"uniqueIndex;size:50;not null" json:"username"`
|
|
Password string `gorm:"size:255;not null" json:"-"`
|
|
Nickname string `gorm:"size:100" json:"nickname"`
|
|
Email string `gorm:"size:100" json:"email"`
|
|
Avatar string `gorm:"size:255" json:"avatar"`
|
|
Role string `gorm:"size:20;default:'user'" json:"role"` // admin, user
|
|
Status int `gorm:"default:1" json:"status"` // 1:启用 0:禁用
|
|
IsActive bool `gorm:"default:true" json:"is_active"` // 账号激活状态
|
|
LastLoginAt *time.Time `json:"last_login_at"` // 最后登录时间
|
|
LoginCount int `gorm:"default:0" json:"login_count"` // 登录次数统计
|
|
}
|
|
|
|
// TableName 指定表名
|
|
func (User) TableName() string {
|
|
return "users"
|
|
}
|
|
|
|
// SetPassword 设置密码加密
|
|
func (u *User) SetPassword(password string) error {
|
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), PasswordCryptLevel)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
u.Password = string(hashedPassword)
|
|
return nil
|
|
}
|
|
|
|
// CheckPassword 验证密码是否匹配
|
|
func (u *User) CheckPassword(password string) bool {
|
|
err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
|
|
return err == nil
|
|
}
|
|
|
|
// RecordLogin 记录登录信息
|
|
func (u *User) RecordLogin(db *gorm.DB) error {
|
|
now := time.Now()
|
|
u.LastLoginAt = &now
|
|
u.LoginCount++
|
|
return db.Model(u).Updates(map[string]interface{}{
|
|
"last_login_at": now,
|
|
"login_count": u.LoginCount,
|
|
}).Error
|
|
}
|
|
|
|
// ==================== 文章模型 ====================
|
|
|
|
type Post struct {
|
|
ID uint `gorm:"primaryKey" json:"id"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
|
Title string `gorm:"size:200;not null" json:"title"`
|
|
Slug string `gorm:"uniqueIndex;size:200" json:"slug"`
|
|
Content string `gorm:"type:text" json:"content"`
|
|
Summary string `gorm:"size:500" json:"summary"`
|
|
Cover string `gorm:"size:255" json:"cover"`
|
|
AuthorID uint `gorm:"index" json:"author_id"` // 增加索引
|
|
Author User `gorm:"foreignKey:AuthorID" json:"author"`
|
|
CategoryID uint `gorm:"index" json:"category_id"` // 增加索引
|
|
Category Category `gorm:"foreignKey:CategoryID" json:"category"`
|
|
Tags []Tag `gorm:"many2many:post_tags;" json:"tags"`
|
|
Views int `gorm:"default:0" json:"views"`
|
|
Status string `gorm:"index;size:20;default:'draft'" json:"status"` // 增加索引
|
|
IsTop bool `gorm:"default:false" json:"is_top"`
|
|
PublishedAt *time.Time `json:"published_at"`
|
|
Password string `gorm:"size:255" json:"password"` // 访问密码保护
|
|
AllowComment bool `gorm:"default:true" json:"allow_comment"` // 是否允许评论
|
|
AllowPing bool `gorm:"default:true" json:"allow_ping"` // 是否允许Pingback
|
|
Template string `gorm:"size:100" json:"template"` // 自定义模板文件
|
|
Comments []Comment `json:"comments,omitempty"`
|
|
}
|
|
|
|
// TableName 指定表名
|
|
func (Post) TableName() string {
|
|
return "posts"
|
|
}
|
|
|
|
// ==================== 分类模型 ====================
|
|
|
|
type Category struct {
|
|
ID uint `gorm:"primaryKey" json:"id"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
Name string `gorm:"size:100;not null" json:"name"`
|
|
Slug string `gorm:"uniqueIndex;size:100" json:"slug"`
|
|
Description string `gorm:"size:255" json:"description"`
|
|
ParentID *uint `json:"parent_id"`
|
|
PostCount int `gorm:"default:0" json:"post_count"`
|
|
}
|
|
|
|
// TableName 指定表名
|
|
func (Category) TableName() string {
|
|
return "categories"
|
|
}
|
|
|
|
// ==================== 标签模型 ====================
|
|
|
|
type Tag struct {
|
|
ID uint `gorm:"primaryKey" json:"id"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
Name string `gorm:"size:100;not null" json:"name"`
|
|
Slug string `gorm:"uniqueIndex;size:100" json:"slug"`
|
|
PostCount int `gorm:"default:0" json:"post_count"`
|
|
}
|
|
|
|
// TableName 指定表名
|
|
func (Tag) TableName() string {
|
|
return "tags"
|
|
}
|
|
|
|
// ==================== 评论模型 ====================
|
|
|
|
type Comment struct {
|
|
ID uint `gorm:"primaryKey" json:"id"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
|
PostID uint `gorm:"index" json:"post_id"` // 增加索引
|
|
Post Post `gorm:"foreignKey:PostID" json:"-"`
|
|
ParentID *uint `json:"parent_id"`
|
|
Author string `gorm:"size:100" json:"author"`
|
|
Email string `gorm:"size:100" json:"email"`
|
|
Website string `gorm:"size:255" json:"website"`
|
|
Content string `gorm:"type:text;not null" json:"content"`
|
|
IP string `gorm:"size:50" json:"-"`
|
|
Status string `gorm:"index;size:20;default:'pending'" json:"status"` // 增加索引
|
|
UserID *uint `json:"user_id"`
|
|
User *User `gorm:"foreignKey:UserID" json:"user,omitempty"`
|
|
Children []Comment `gorm:"foreignKey:ParentID" json:"children,omitempty"`
|
|
// 反垃圾字段
|
|
UserAgent string `gorm:"size:255" json:"-"` // 用户代理
|
|
IsSpam bool `gorm:"default:false" json:"is_spam"` // 是否为垃圾评论
|
|
SpamScore float64 `gorm:"default:0" json:"spam_score"` // 垃圾评分
|
|
}
|
|
|
|
// TableName 指定表名
|
|
func (Comment) TableName() string {
|
|
return "comments"
|
|
}
|
|
|
|
// ==================== 设置模型 (优化) ====================
|
|
|
|
type Option struct {
|
|
Name string `gorm:"column:name;type:varchar(100);primaryKey" json:"name"` // 配置键名
|
|
UserID uint `gorm:"column:user_id;type:int;default:0;primaryKey;index" json:"user_id"` // 用户ID(0=全局配置)
|
|
Value string `gorm:"column:value;type:text" json:"value"` // 配置值
|
|
}
|
|
|
|
// TableName 指定表名
|
|
func (Option) TableName() string {
|
|
return "options"
|
|
}
|
|
|
|
// GetOptionValue 根据name和userID获取配置值
|
|
func GetOptionValue(db *gorm.DB, name string, userID uint) (string, error) {
|
|
var option Option
|
|
result := db.Where("name = ? AND user_id = ?", name, userID).First(&option)
|
|
if result.Error != nil {
|
|
return "", result.Error
|
|
}
|
|
return option.Value, nil
|
|
}
|
|
|
|
// SetOptionValue 根据name和userID设置配置值(存在则更新,不存在则新增)
|
|
func SetOptionValue(db *gorm.DB, name string, userID uint, value string) error {
|
|
// 先尝试查找
|
|
var option Option
|
|
result := db.Where("name = ? AND user_id = ?", name, userID).First(&option)
|
|
|
|
if result.Error == nil {
|
|
// 记录存在,更新
|
|
return db.Model(&option).Update("value", value).Error
|
|
}
|
|
|
|
// 记录不存在,创建新记录
|
|
option = Option{
|
|
Name: name,
|
|
UserID: userID,
|
|
Value: value,
|
|
}
|
|
return db.Create(&option).Error
|
|
}
|
|
|
|
// GetOptionsByUser 获取用户的所有配置
|
|
func GetOptionsByUser(db *gorm.DB, userID uint) (map[string]string, error) {
|
|
var options []Option
|
|
result := db.Where("user_id = ?", userID).Find(&options)
|
|
if result.Error != nil {
|
|
return nil, result.Error
|
|
}
|
|
|
|
optionsMap := make(map[string]string)
|
|
for _, opt := range options {
|
|
optionsMap[opt.Name] = opt.Value
|
|
}
|
|
return optionsMap, nil
|
|
}
|
|
|
|
// BatchSetOptions 批量设置配置
|
|
func BatchSetOptions(db *gorm.DB, userID uint, options map[string]string) error {
|
|
return db.Transaction(func(tx *gorm.DB) error {
|
|
for name, value := range options {
|
|
// 复合主键在 SQLite 旧表上可能缺失唯一约束,Save 会重复插入,
|
|
// 改用查找-更新-不存在才插入的方式保证幂等
|
|
if err := SetOptionValue(tx, name, userID, value); err != nil {
|
|
slog.Error("保存配置失败", "name", name, "error", err)
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// ==================== 页面模型(优化) ====================
|
|
|
|
type Page struct {
|
|
ID uint `gorm:"primaryKey" json:"id"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
|
Title string `gorm:"size:200;not null" json:"title"`
|
|
Slug string `gorm:"uniqueIndex;size:200" json:"slug"`
|
|
Content string `gorm:"type:text" json:"content"`
|
|
AuthorID uint `gorm:"index" json:"author_id"`
|
|
Author User `gorm:"foreignKey:AuthorID" json:"author"`
|
|
Status string `gorm:"index;size:20;default:'draft'" json:"status"` // 增加索引
|
|
Order int `gorm:"default:0" json:"order"`
|
|
Password string `gorm:"size:255" json:"password"` // 访问密码保护
|
|
AllowComment bool `gorm:"default:true" json:"allow_comment"` // 是否允许评论
|
|
ParentID uint `gorm:"default:0" json:"parent_id"` // 父级页面(支持层级页面)
|
|
}
|
|
|
|
// TableName 指定表名
|
|
func (Page) TableName() string {
|
|
return "pages"
|
|
}
|
|
|
|
// ==================== 文件模型 ====================
|
|
|
|
// File 上传文件记录
|
|
type File struct {
|
|
ID uint `gorm:"primaryKey" json:"id"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
|
UserID uint `gorm:"index;not null" json:"user_id"` // 上传者
|
|
User User `gorm:"foreignKey:UserID" json:"user"` // 上传者信息
|
|
FileName string `gorm:"size:255;not null" json:"file_name"` // 存储文件名
|
|
OrigName string `gorm:"size:255" json:"orig_name"` // 原始文件名
|
|
FilePath string `gorm:"size:500;not null" json:"file_path"` // 相对存储路径(含年月目录)
|
|
FileSize int64 `gorm:"default:0" json:"file_size"` // 文件大小(字节)
|
|
MimeType string `gorm:"size:100" json:"mime_type"` // MIME 类型
|
|
}
|
|
|
|
// TableName 指定表名
|
|
func (File) TableName() string {
|
|
return "files"
|
|
}
|