/
wrappers.go
457 lines (393 loc) · 12.5 KB
/
wrappers.go
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package route
import (
"fmt"
"log"
"time"
"github.com/gin-gonic/gin"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"github.com/bsinou/vitrnx-goback/auth"
"github.com/bsinou/vitrnx-goback/conf"
"github.com/bsinou/vitrnx-goback/gorm"
"github.com/bsinou/vitrnx-goback/model"
"github.com/bsinou/vitrnx-goback/mongodb"
)
// loggingHandler simply logs every request to stdout
func loggingHandler() gin.HandlerFunc {
return func(c *gin.Context) {
log.Printf("Got a %s request at %s \n", c.Request.Method, c.Request.URL.String())
t1 := time.Now()
c.Next()
t2 := time.Now()
log.Printf("[%s] %q %v\n", c.Request.Method, c.Request.URL.String(), t2.Sub(t1))
}
}
// checkCredentials calls the authentication API to verify the token
func checkCredentials() gin.HandlerFunc {
return func(c *gin.Context) {
// Real check
jwt := c.Request.Header.Get(model.KeyAuth)
if jwt == "" {
// No JWT cannot continue
msg := "No JWT token provided, please log out and back in again"
log.Println(msg)
c.JSON(401, gin.H{"error": msg})
c.Abort()
return
}
err := auth.CheckCredentialAgainstFireBase(c, jwt)
if err != nil {
msg := "Could not validate token: " + err.Error()
c.JSON(401, gin.H{"error": msg})
c.Abort()
return
}
}
}
func addUserMeta() gin.HandlerFunc {
return func(c *gin.Context) {
auth.WithUserMeta(c)
}
}
func cors() gin.HandlerFunc {
return func(c *gin.Context) {
log.Printf("Setting CORS policies on request %s\n", c.Request.Header.Get("origin"))
c.Writer.Header().Add("Access-Control-Allow-Origin", conf.GetAllowedOrigins())
if c.Request.Method == "OPTIONS" {
c.Writer.Header().Set("Access-Control-Allow-Methods", "DELETE, POST, PUT, PATCH")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// Cache preflight request result during 10 minutes
c.Writer.Header().Set("Access-Control-Max-Age", "600")
// Headers have been set, no need to go further
c.Abort()
return
}
// NOTE: this is OK:
// c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// This is *NOT* OK: the second 'Authorization' line erase the first and Content-Type is not an authorized header anymore
// c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type")
// c.Writer.Header().Set("Access-Control-Allow-Headers", "Authorization")
}
}
// connect middleware makes the various `db` objects available for each handler
func connect() gin.HandlerFunc {
return func(c *gin.Context) {
log.Printf("Connecting stores\n")
// User management
db := gorm.GetConnection()
defer db.Close()
c.Set(model.KeyUserDb, db)
// Data
s := mongodb.Session.Clone()
defer s.Close()
c.Set(model.KeyDataDb, s.DB(mongodb.Mongo.Database))
// Next must be explicitely called here
// so that the db session is released *AFTER* next handlers processing
c.Next()
}
}
/* USER */
// TODO Check:
// -> Put simple registered role on creation
// -> explicitly copy editable properties when editing self
// -> double check permission when editing roles
// -> only admin users can change admin & user admin roles
// applyUsersPolicies calls the authentication API to verify the token
func applyUserCreationPolicies() gin.HandlerFunc {
return func(c *gin.Context) {
userID := c.MustGet(model.KeyUserID).(string)
log.Printf("Applying user creation policie\n")
var user model.User
c.Bind(&user)
// TODO enhance this will only be true upon user creation
if userID != user.UserID {
log.Printf("user ID differ: %s vs %s \n", userID, user.UserID)
c.JSON(503, gin.H{"error": "Unauthorized"})
c.Abort()
}
c.Set(model.KeyEditedUser, user)
}
}
func applyUserUpdatePolicies() gin.HandlerFunc {
return func(c *gin.Context) {
log.Printf("Applying user update policies\n")
userID := c.MustGet(model.KeyUserID).(string)
roles := c.MustGet(model.KeyUserRoles).([]string)
editedUserID := c.Param("id")
if userID != editedUserID && !(contains(roles, model.RoleAdmin) || contains(roles, model.RoleUserAdmin)) {
log.Printf("user ID differ: %s vs %s \n", userID, editedUserID)
c.JSON(403, gin.H{"error": "Forbidden"})
c.Abort()
return
}
var receivedUser model.User
c.Bind(&receivedUser)
c.Set(model.KeyEditedUser, receivedUser)
}
}
func applyUserDeletePolicies() gin.HandlerFunc {
return func(c *gin.Context) {
log.Printf("Applying user delete policies\n")
userID := c.MustGet(model.KeyUserID).(string)
roles := c.MustGet(model.KeyUserRoles).([]string)
editedUserID := c.Param("id")
if !(contains(roles, model.RoleAdmin) || contains(roles, model.RoleUserAdmin)) {
msg := fmt.Sprintf("As user with ID %s, you don't have sufficient rights to delete user %s. Incident will be reported.", userID, editedUserID)
c.JSON(403, gin.H{"error": msg})
c.Abort()
return
}
// var receivedUser model.User
// c.Bind(&receivedUser)
// c.Set(model.KeyEditedUser, receivedUser)
}
}
func applyUserRolesUpdatePolicies() gin.HandlerFunc {
return func(c *gin.Context) {
log.Printf("Applying user roles update policies\n")
roles := c.MustGet(model.KeyUserRoles).([]string)
if !(contains(roles, model.RoleAdmin) || contains(roles, model.RoleUserAdmin)) {
c.JSON(403, gin.H{"error": "Forbidden"})
c.Abort()
return
}
log.Printf("About to bind\n")
var receivedRoles []string
c.Bind(&receivedRoles)
c.Set(model.KeyEditedUserRoles, receivedRoles)
log.Printf("Role set: %v\n", receivedRoles)
c.Next()
}
}
func applyUserMetaPolicies() gin.HandlerFunc {
return func(c *gin.Context) {
log.Printf("Applying user meta policies\n")
userID := c.MustGet(model.KeyUserID).(string)
roles := c.MustGet(model.KeyUserRoles).([]string)
editedUserID := c.Param(model.KeyUserID)
if userID != editedUserID && !(contains(roles, model.RoleAdmin) || contains(roles, model.RoleUserAdmin)) {
log.Printf("user ID differ: %s vs %s \n", userID, editedUserID)
c.JSON(403, gin.H{"error": "Forbidden"})
c.Abort()
return
}
}
}
/* POSTS */
// unmarshallPost retrieves the post from the context and store it again as a model.Post, for POST and MOVE requests.
// For delete request we rather use the passed path
// This must be done because the post can be retrieve only once from the request payload
func unmarshallPost() gin.HandlerFunc {
return func(c *gin.Context) {
rm := c.Request.Method
if rm == "POST" || rm == "MOVE" {
post := model.Post{}
err := c.Bind(&post)
if err != nil {
fmt.Printf("Could not bind post %v\n", err)
c.Error(err)
c.Abort()
return
}
if post.Path == "" {
err = fmt.Errorf("path is required, could not proceed")
fmt.Println(err.Error())
c.Error(err)
c.Abort()
return
}
c.Set(model.KeyPost, post)
} else if rm == "DELETE" {
post := model.Post{}
path := c.Param(model.KeyPath)
pathQuery := bson.M{model.KeyPath: path}
db := c.MustGet(model.KeyDataDb).(*mgo.Database)
err := db.C(model.PostCollection).Find(pathQuery).One(&post)
if err != nil {
fmt.Printf("Could not find post to delete with path %s: %s\n", path, err.Error())
c.Error(err)
c.Abort()
return
}
c.Set(model.KeyPost, post)
}
}
}
// applyPostPolicies limit possible actions depending on user role
func applyPostPolicies() gin.HandlerFunc {
return func(c *gin.Context) {
// shortcut
rm := c.Request.Method
// Get requests are filtered A POSTERIORI
// if c.Request.Method == "GET" && !contains(claims, model.PolicyCanRead) {
// c.JSON(503, gin.H{"error": "Unauthorized"})
// c.Abort()
// } else
if rm == "POST" || rm == "DELETE" {
userID := c.MustGet(model.KeyUserID).(string)
roles := c.MustGet(model.KeyUserRoles).([]string)
post := c.MustGet(model.KeyPost).(model.Post)
switch rm {
case "POST":
// creation
if post.ID.Hex() == "" && !(contains(roles, model.RoleModerator) || contains(roles, model.RoleEditor)) {
c.JSON(403, gin.H{"error": "you don't have sufficient permission to create a post"})
c.Abort()
return
}
// update only by the post author or a moderator
if !(contains(roles, model.RoleModerator) || post.AuthorID == userID) {
c.JSON(403, gin.H{"error": "you don't have sufficient permission to update this post"})
c.Abort()
return
}
break
case "DELETE":
// delete only by the post author or a moderator
if !(contains(roles, model.RoleModerator) || post.AuthorID == userID) {
c.JSON(403, gin.H{"error": "you don't have sufficient permission to delete this post"})
c.Abort()
return
}
}
}
}
}
/* COMMENTS */
// unmarshallComment retrieves the comment from the context and store it again as a model.Comment, for POST and MOVE requests.
// For delete request we use the passed id
func unmarshallComment() gin.HandlerFunc {
return func(c *gin.Context) {
rm := c.Request.Method
if rm == "POST" || rm == "MOVE" {
comment := model.Comment{}
err := c.Bind(&comment)
if err != nil {
fmt.Printf("Could not bind comment %v\n", err)
c.Error(err)
c.Abort()
return
}
if comment.ParentID == "" {
err = fmt.Errorf("parentId is required, could not upsert")
fmt.Println(err.Error())
c.Error(err)
return
}
c.Set(model.KeyComment, comment)
} else if rm == "DELETE" {
db := c.MustGet(model.KeyDataDb).(*mgo.Database)
comment := model.Comment{}
id := c.Param(model.KeyMgoID)
idQuery := bson.M{model.KeyMgoID: bson.ObjectIdHex(id)}
err := db.C(model.CommentCollection).Find(idQuery).One(&comment)
if err != nil {
fmt.Printf("Could not find comment to delete with id %s: %s\n", id, err.Error())
c.Error(err)
c.Abort()
return
}
c.Set(model.KeyComment, comment)
}
}
}
// applyCommentPolicies limit possible actions depending on user role
func applyCommentPolicies() gin.HandlerFunc {
return func(c *gin.Context) {
// shortcut
rm := c.Request.Method
// Note: GET requests are filtered A POSTERIORI
if rm == "POST" || rm == "DELETE" {
userID := c.MustGet(model.KeyUserID).(string)
roles := c.MustGet(model.KeyUserRoles).([]string)
comment := c.MustGet(model.KeyComment).(model.Comment)
switch rm {
case "POST":
// creation
if comment.ID.Hex() == "" {
break
// TODO prevent addition when guest
// if len(roles) == 0 || len(roles) == 1 && roles[0] == model.RoleAnonymous){
// // c.JSON(403, gin.H{"error": "you don't have sufficient permission to add a comment "})
// // c.Abort()
// // return
// }
}
// update only by the post author or a moderator
if !(contains(roles, model.RoleModerator) || comment.AuthorID == userID) {
c.JSON(403, gin.H{"error": "you don't have sufficient permission to update this comment"})
c.Abort()
return
}
break
case "DELETE":
// only the comment author or a moderator can delete
if !(contains(roles, model.RoleModerator) || comment.AuthorID == userID) {
c.JSON(403, gin.H{"error": "you don't have sufficient permission to delete this post"})
c.Abort()
return
}
}
}
}
}
/* TASKS */
func unmarshallTask() gin.HandlerFunc {
return func(c *gin.Context) {
rm := c.Request.Method
if rm == "POST" || rm == "MOVE" {
task := model.Task{}
err := c.Bind(&task)
if err != nil {
fmt.Printf("Could not bind task %v\n", err)
c.Error(err)
c.Abort()
return
}
if task.Desc == "" {
err = fmt.Errorf("description is required, could not upsert")
fmt.Println(err.Error())
c.Error(err)
return
}
c.Set(model.KeyTask, task)
} else if rm == "DELETE" {
db := c.MustGet(model.KeyDataDb).(*mgo.Database)
task := model.Task{}
id := c.Param(model.KeyMgoID)
idQuery := bson.M{model.KeyMgoID: bson.ObjectIdHex(id)}
err := db.C(model.TaskCollection).Find(idQuery).One(&task)
if err != nil {
fmt.Printf("Could not find task to delete with id %s: %s\n", id, err.Error())
c.Error(err)
c.Abort()
return
}
c.Set(model.KeyTask, task)
}
}
}
// applyTaskPolicies limit possible actions depending on user role
func applyTaskPolicies() gin.HandlerFunc {
return func(c *gin.Context) {
// shortcut
roles := c.MustGet(model.KeyUserRoles).([]string)
if !(contains(roles, model.RoleAdmin) ||
contains(roles, model.RoleVolunteer) ||
contains(roles, model.RoleUserAdmin)) {
c.JSON(403, gin.H{"error": "you don't have sufficient permission to see tasks"})
c.Abort()
return
}
// TODO enhance policy management
}
}
/* HELPER FUNCTIONS */
func contains(arr []string, val string) bool {
for _, currVal := range arr {
if currVal == val {
return true
}
}
return false
}