Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
211 lines (169 loc) · 5.5 KB
/
Copy pathmain.go
File metadata and controls
211 lines (169 loc) · 5.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package main
import (
"database/sql"
"embed"
"errors"
"fmt"
"io/fs"
"log"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/joho/godotenv"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/plugins/migratecmd"
"github.com/pocketbase/pocketbase/tools/osutils"
_ "pdnode.com/x/cp/migrations"
)
//go:embed all:pb_public
var embeddedFiles embed.FS
var Version = "untracked"
func main() {
app := pocketbase.New()
err := godotenv.Load()
if err != nil {
app.Logger().Warn("Warning: .env file not found, using system environment variables", "err", err)
}
app.RootCmd.Version = Version
migratecmd.MustRegister(app, app.RootCmd, migratecmd.Config{
// enable auto creation of migration files when making collection changes in the Dashboard
// (the IsProbablyGoRun check is to enable it only during development)
Automigrate: osutils.IsProbablyGoRun(),
})
app.OnServe().BindFunc(func(se *core.ServeEvent) error {
Setup(se.App)
se.Router.POST("/api/{type}/{id}/toggle-like", func(e *core.RequestEvent) error {
requestCollection := e.Request.PathValue("type")
targetId := e.Request.PathValue("id") // 被点赞物体的 ID
userId := e.Auth.Id
if requestCollection != "cps" && requestCollection != "characters" {
return e.Error(400, "Invalid request data", map[string]validation.Error{
"type": validation.NewError("validation_collection_type", "Invalid collection type."),
})
}
collection, err := e.App.FindCollectionByNameOrId("likes")
if err != nil {
return e.InternalServerError("Internal Server Error", map[string]any{"message": "Cannot find collection", "err": err})
}
existingRecord, err := e.App.FindFirstRecordByFilter("likes",
fmt.Sprintf("user = '%s' && target_id = '%s'", userId, targetId),
)
if err != nil {
if !errors.Is(err, sql.ErrNoRows) {
return e.InternalServerError("Internal Server Error", map[string]any{
"message": "Cannot find record",
"err": err,
})
}
}
if existingRecord != nil {
err = e.App.Delete(existingRecord)
if err != nil {
return e.InternalServerError("Internal Server Error", map[string]any{
"message": "Cannot delete record",
"err": err,
})
}
return e.JSON(200, map[string]any{
"message": "Success",
"like": false,
"data": existingRecord,
})
}
record := core.NewRecord(collection)
record.Set("target_id", targetId)
record.Set("target_collection", requestCollection)
record.Set("user", e.Auth.Id)
err = e.App.Save(record)
if err != nil {
return e.InternalServerError("Internal Server Error", map[string]any{
"message": "Cannot save record",
"err": err,
})
}
return e.JSON(200, map[string]any{
"message": "Success",
"like": true,
"data": record,
})
}).Bind(apis.RequireAuth())
publicFS, err := fs.Sub(embeddedFiles, "pb_public")
if err != nil {
return err
}
// serves static files from the provided public dir (if exists)
se.Router.GET("/{path...}", apis.Static(publicFS, true))
return se.Next()
})
app.OnRecordCreateRequest("cps").BindFunc(validateCharactersOwnership)
app.OnRecordUpdateRequest("cps").BindFunc(validateCharactersOwnership)
app.OnRecordCreateRequest().BindFunc(validateIdImmutable)
app.OnRecordCreateRequest().BindFunc(restrictToAuth)
app.OnRecordUpdateRequest().BindFunc(restrictToAuth)
app.OnRecordDeleteRequest().BindFunc(restrictToAuth)
if err := app.Start(); err != nil {
log.Fatal(err)
}
}
// 权限校验中间件
func restrictToAuth(e *core.RecordRequestEvent) error {
if e.Auth != nil || e.Record.Collection().IsAuth() {
return e.Next()
}
return apis.NewForbiddenError("Unauthorized", nil)
}
// 阻止自定义IDs
func validateIdImmutable(e *core.RecordRequestEvent) error {
// Superuser 绕过
if e.Auth != nil && e.Auth.IsSuperuser() {
return e.Next()
}
// 检查用户有没有传入id
if e.Record.Id != "" {
return e.BadRequestError("Invalid request data", map[string]validation.Error{
"id": validation.NewError("validation_id_immutable", "Custom record IDs are not allowed."),
})
}
return e.Next()
}
// 校验 CP 中的Characters是否属于当前操作者
func validateCharactersOwnership(e *core.RecordRequestEvent) error {
if e.Auth == nil {
return e.UnauthorizedError("Unauthorized", nil)
}
// Superuser 绕过
if e.Auth != nil && e.Auth.IsSuperuser() {
return e.Next()
}
// 获取当前记录中关联的角色 IDs (假设字段名是 "members")
characterIds := e.Record.GetStringSlice("characters")
if len(characterIds) == 0 {
return e.Next()
}
// 将 slice 转为 interface slice 用于 dbx 查询
vals := make([]any, len(characterIds))
for i, v := range characterIds {
vals[i] = v
}
// 查询这些角色中,是否存在不属于当前用户的记录
var count int
err := e.App.DB().
Select("count(*)").
From("characters").
Where(dbx.And(
dbx.In("id", vals...),
dbx.Not(dbx.HashExp{"owner": e.Auth.Id}), // 找出 owner 不是当前用户的
)).
Row(&count)
if err != nil {
return e.InternalServerError("Database query failed", err)
}
// 如果发现有角色不属于该用户,拦截请求
if count > 0 {
return e.Error(403, "Illegal association", map[string]validation.Error{
"characters": validation.NewError("invalid_character_owner", "One or more selected characters do not belong to you."),
})
}
return e.Next()
}