-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathendpoints-system.go
More file actions
99 lines (70 loc) · 2.43 KB
/
Copy pathendpoints-system.go
File metadata and controls
99 lines (70 loc) · 2.43 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
package main
import (
"fmt"
"net/http"
"github.com/caTUstrophy/backend/db"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator"
"github.com/leebenson/conform"
)
func (app *App) PromoteToSystemAdmin(c *gin.Context) {
// Check authorization for this function.
ok, User, message := app.Authorize(c.Request)
if !ok {
// Signal client an error and expect authorization.
c.Header("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"CaTUstrophy\", error=\"invalid_token\", error_description=\"%s\"", message))
c.Status(http.StatusUnauthorized)
return
}
// Check if user permissions are sufficient (user is admin).
if ok := app.CheckScope(User, db.Region{}, "superadmin"); !ok {
// Signal client that the provided authorization was not sufficient.
c.Header("WWW-Authenticate", "Bearer realm=\"CaTUstrophy\", error=\"authentication_failed\", error_description=\"Could not authenticate the request\"")
c.Status(http.StatusUnauthorized)
return
}
// Parse the JSON and check for errors
var Payload PromoteUserPayload
// Expect offer struct fields for creation in JSON request body.
err := c.BindJSON(&Payload)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"Error": "Couldn't marshal JSON",
})
return
}
// Validate sent offer creation data.
conform.Strings(&Payload)
errs := app.Validator.Struct(&Payload)
if errs != nil {
errResp := make(map[string]string)
// Iterate over all validation errors.
for _, err := range errs.(validator.ValidationErrors) {
if err.Tag == "required" {
errResp[err.Field] = "Is required"
} else if err.Tag == "excludesall" {
errResp[err.Field] = "Contains unallowed characters"
}
}
// Send prepared error message to client.
c.JSON(http.StatusBadRequest, errResp)
return
}
// Everything seems fine, promote that user.
var group db.Group
app.DB.First(&group, "access_right = ?", "superadmin")
// Find the user who is to be promoted and add the group to his or her groups.
var promotedUser db.User
app.DB.Preload("Groups").First(&promotedUser, "mail = ?", Payload.Mail)
if promotedUser.Mail != Payload.Mail {
c.JSON(http.StatusBadRequest, gin.H{
"Error": "Email unkown to system",
})
return
}
promotedUser.Groups = append(promotedUser.Groups, group)
// app.DB.Model(&promotedUser).Updates(db.User{Groups: promotedUser.Groups})
app.DB.Save(promotedUser)
model := CopyNestedModel(promotedUser, fieldsUser)
c.JSON(http.StatusOK, model)
}