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

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
+38
View File
@@ -30,6 +30,14 @@ func GetComments(c *gin.Context) {
return db.Select("id", "title", "slug")
})
// 非管理员只能查看自己文章上的评论
if !isAdmin(c) {
if userID, exists := c.Get("userID"); exists {
db = db.Where("post_id IN (?)",
database.DB.Model(&models.Post{}).Select("id").Where("author_id = ?", userID))
}
}
if postID != "" {
db = db.Where("post_id = ?", postID)
}
@@ -95,6 +103,21 @@ func CreateComment(c *gin.Context) {
c.JSON(http.StatusCreated, gin.H{"data": comment})
}
// canManageComment 检查当前用户是否有权管理该评论(管理员始终可以,普通用户只能管理自己文章上的评论)
func canManageComment(c *gin.Context, comment *models.Comment) bool {
if isAdmin(c) {
return true
}
if userID, exists := c.Get("userID"); exists {
var post models.Post
if err := database.DB.Select("author_id").First(&post, comment.PostID).Error; err != nil {
return false
}
return post.AuthorID == userID.(uint)
}
return false
}
// 审核评论
func ApproveComment(c *gin.Context) {
id := c.Param("id")
@@ -105,6 +128,11 @@ func ApproveComment(c *gin.Context) {
return
}
if !canManageComment(c, &comment) {
c.JSON(http.StatusForbidden, gin.H{"error": "无权管理该评论"})
return
}
comment.Status = "approved"
if err := database.DB.Save(&comment).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "审核失败"})
@@ -124,6 +152,11 @@ func MarkSpamComment(c *gin.Context) {
return
}
if !canManageComment(c, &comment) {
c.JSON(http.StatusForbidden, gin.H{"error": "无权管理该评论"})
return
}
comment.Status = "spam"
if err := database.DB.Save(&comment).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "操作失败"})
@@ -143,6 +176,11 @@ func DeleteComment(c *gin.Context) {
return
}
if !canManageComment(c, &comment) {
c.JSON(http.StatusForbidden, gin.H{"error": "无权管理该评论"})
return
}
if err := database.DB.Delete(&comment).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "删除评论失败"})
return