Browse Source

feat: 授权策略

runningwater 5 months ago
parent
commit
1342673076
4 changed files with 32 additions and 1 deletions
  1. 6 0
      app/http/controllers/api/v1/topics_controller.go
  2. 14 0
      app/policies/topic_policy.go
  3. 11 0
      gohub.http
  4. 1 1
      routes/api.go

+ 6 - 0
app/http/controllers/api/v1/topics_controller.go

@@ -2,6 +2,7 @@ package v1
 
 import (
 	"github.com/runningwater/gohub/app/models/topic"
+	"github.com/runningwater/gohub/app/policies"
 	"github.com/runningwater/gohub/app/requests"
 	"github.com/runningwater/gohub/pkg/auth"
 	"github.com/runningwater/gohub/pkg/response"
@@ -51,6 +52,11 @@ func (ctrl *TopicsController) Update(c *gin.Context) {
 		return
 	}
 
+	if !policies.CanModifyTopic(c, topicModel) {
+		response.Abort403(c)
+		return
+	}
+
 	topicModel.Title = request.Title
 	topicModel.Body = request.Body
 	topicModel.CategoryID = request.CategoryID

+ 14 - 0
app/policies/topic_policy.go

@@ -0,0 +1,14 @@
+// Package policies 用户授权
+package policies
+
+import (
+	"github.com/gin-gonic/gin"
+
+	"github.com/runningwater/gohub/app/models/topic"
+	"github.com/runningwater/gohub/pkg/auth"
+)
+
+// CanModifyTopic 登陆用户是否可以修改此 topic
+func CanModifyTopic(c *gin.Context, _topic topic.Topic) bool {
+	return _topic.UserID == auth.CurrentUID(c)
+}

+ 11 - 0
gohub.http

@@ -135,3 +135,14 @@ Content-Type: application/json
   "body": "话题1内容, 这里是帖子描述内容帖子描述内容",
   "category_id": "3"
 }
+
+### 更新话题
+PUT {{base_url}}/v1/topics/1 HTTP/1.1
+Authorization: Bearer {{access_token}}
+Content-Type: application/json
+
+{
+  "title": "我的的帖子3",
+  "body": "话题1内容, 这里是帖子描述内容帖子描述内容",
+  "category_id": "3"
+}

+ 1 - 1
routes/api.go

@@ -1,4 +1,4 @@
-// Path: routes 注册路由
+// Package routes Path: routes 注册路由
 package routes
 
 import (