后台独立登录页面,并加入权限控制。

This commit is contained in:
2026-08-11 18:04:02 +08:00
parent 808f2e7523
commit a1d57d6b44
12 changed files with 638 additions and 178 deletions
+39 -13
View File
@@ -82,22 +82,23 @@ func GetPosts(c *gin.Context) {
db := database.DB.Model(&models.Post{}).Preload("Category").Preload("Tags").Preload("Author")
// 前端只显示已发布的文章
if !isAdmin(c) {
// 管理员可查看全部;登录用户可看到自己的全部文章(含草稿);未登录只能看已发布
if isAdmin(c) {
if query.Status != "" {
db = db.Where("status = ?", query.Status)
}
} else if userId, exists := c.Get("userID"); exists {
// 登录用户:只看自己的,不限状态(后台管理需要看到草稿)
db = db.Where("author_id = ?", userId)
} else {
// 未登录:只看已发布
db = db.Where("status = ?", "published")
} else if query.Status != "" {
db = db.Where("status = ?", query.Status)
}
if query.CategoryID > 0 {
db = db.Where("category_id = ?", query.CategoryID)
}
userId, exists := c.Get("userID")
if exists {
db = db.Where("author_id = ?", userId)
}
if query.TagID > 0 {
db = db.Joins("JOIN post_tags ON post_tags.post_id = posts.id").
Where("post_tags.tag_id = ?", query.TagID)
@@ -141,9 +142,13 @@ func GetPost(c *gin.Context) {
query = query.Where("slug = ?", id)
}
// 非管理员只能查看已发布文章
// 非管理员只能查看已发布文章,但可以查看自己的草稿(编辑用)
if !isAdmin(c) {
query = query.Where("status = ?", "published")
if userId, exists := c.Get("userID"); exists {
query = query.Where("status = ? OR author_id = ?", "published", userId)
} else {
query = query.Where("status = ?", "published")
}
}
if err := query.First(&post).Error; err != nil {
@@ -176,7 +181,7 @@ func CreatePost(c *gin.Context) {
AuthorID: userID.(uint),
CategoryID: req.CategoryID,
Status: req.Status,
IsTop: req.IsTop,
IsTop: req.IsTop && isAdmin(c), // 非管理员不允许置顶
}
if req.Status == "published" {
@@ -216,6 +221,15 @@ func UpdatePost(c *gin.Context) {
return
}
// 非管理员只能编辑自己的文章
if !isAdmin(c) {
userID, _ := c.Get("userID")
if post.AuthorID != userID.(uint) {
c.JSON(http.StatusForbidden, gin.H{"error": "无权编辑他人的文章"})
return
}
}
var req UpdatePostRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
@@ -251,7 +265,10 @@ func UpdatePost(c *gin.Context) {
now := time.Now()
updates["published_at"] = &now
}
updates["is_top"] = req.IsTop
// 非管理员不允许置顶
if isAdmin(c) {
updates["is_top"] = req.IsTop
}
// 处理标签
if len(req.Tags) > 0 {
@@ -288,6 +305,15 @@ func DeletePost(c *gin.Context) {
return
}
// 非管理员只能删除自己的文章
if !isAdmin(c) {
userID, _ := c.Get("userID")
if post.AuthorID != userID.(uint) {
c.JSON(http.StatusForbidden, gin.H{"error": "无权删除他人的文章"})
return
}
}
if err := database.DB.Delete(&post).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "删除文章失败"})
return