-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
permission.go
286 lines (269 loc) · 6.31 KB
/
permission.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
package main
import (
"bufio"
"fmt"
"io"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"github.com/EduOJ/backend/base"
"github.com/EduOJ/backend/base/log"
"github.com/EduOJ/backend/base/utils"
"github.com/EduOJ/backend/database/models"
"github.com/fatih/color"
"github.com/pkg/errors"
"github.com/xlab/treeprint"
"gorm.io/gorm"
)
// For role granting.
// Implements database/models/HasRole interface.
type dummyHasRole struct {
ID uint
name string
}
func (t *dummyHasRole) GetID() uint {
return t.ID
}
func (t *dummyHasRole) TypeName() string {
return t.name
}
func permission() {
defer func() {
if err := recover(); err != nil {
log.Error(err)
log.Fatal("Edit permission failed.")
}
}()
readConfig()
initGorm()
initLog()
reader := bufio.NewReaderSize(os.Stdin, 0)
if len(args) == 1 {
quit := false
log.Debug(`Entering interactive mode, enter "help" for help.`)
s := make(chan os.Signal, 1)
signal.Notify(s, syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
go func() {
<-s
os.Exit(0)
}()
for !quit {
_, err := color.New(color.Bold).Print("EduOJ Permission> ")
if err != nil {
log.Error(errors.Wrap(err, "fail to print"))
log.Fatal("Edit permission failed.")
return
}
input, err := reader.ReadString('\n')
if err != nil {
log.Error(errors.Wrap(err, "fail to print"))
return
}
if err == io.EOF {
return
}
args = strings.Split(input[:len(input)-1], " ")
quit = doPermission(args)
}
} else {
doPermission(args[1:])
}
}
func doPermission(args []string) (end bool) {
var err error
switch args[0] {
case "help", "h":
fmt.Println(`EduOJ Permission
Usage:
One-line execution: $ EduOJ (permission|perm) (command) <args>...
Enter interactive mode: $ EduOJ (permission|perm)
Command format in interactive mode: (command) <args>...
commands:
(help|h)
(list-roles|lr) [<role_id|role_name>]
(create-role|cr) <name> [<target>]
(grant-role|gr) <user_id|username> <role_id|role_name> [<target_id>]
(delete-role|dr) <role_id|role_name>
(add-permission|ap) <role_id|role_name> <permission>
(quit|q)
Note:
When the search value matches the name and ID at the same time, the system
always selects the object that matches the ID.`)
case "create-role", "cr":
// (create-role|cr) <name> [<target>]
err = validateArgumentsCount(len(args), 2, 3)
if err != nil {
log.Error(err)
break
}
r := models.Role{
Name: args[1],
}
if len(args) == 3 {
r.Target = &args[2]
}
err = base.DB.Create(&r).Error
if err != nil {
log.Error(err)
break
}
case "list-roles", "lr":
// (list-roles|lr) [<role_id|role_name>]
err = validateArgumentsCount(len(args), 1, 2)
if err != nil {
log.Error(err)
break
}
tree := treeprint.New()
tree.SetValue("Roles")
if len(args) == 1 {
var roles []models.Role
err = base.DB.Set("gorm:auto_preload", true).Find(&roles).Error
if err != nil {
log.Error(err)
break
}
for _, role := range roles {
listRole(tree, &role)
}
} else {
var role *models.Role
role, err = findRole(args[1])
if err != nil {
log.Error(err)
break
}
listRole(tree, role)
}
fmt.Println(tree.String())
case "grant-role", "gr":
// (grant-role|gr) <user_id|username> <role_id|role_name> [<target_id>]
err = validateArgumentsCount(len(args), 3, 4)
if err != nil {
log.Error(err)
break
}
var user *models.User
user, err = utils.FindUser(args[1])
if err != nil {
err = errors.Wrap(err, "find user")
log.Error(err)
break
}
var role *models.Role
role, err = findRole(args[2])
if err != nil {
log.Error(err)
break
}
if len(args) == 3 {
user.GrantRole(role.Name)
} else {
var targetId uint64
targetId, err = strconv.ParseUint(args[3], 10, 32)
if err != nil {
log.Error(err)
break
}
target := dummyHasRole{
ID: uint(targetId),
name: *role.Target,
}
user.GrantRole(role.Name, &target)
}
case "delete-role", "dr":
// (delete-role|dr) <role_id|role_name>
err = validateArgumentsCount(len(args), 2, 2)
if err != nil {
log.Error(err)
break
}
var role *models.Role
role, err := findRole(args[1])
if err != nil {
log.Error(err)
break
}
err = base.DB.Delete(&models.Permission{}, "role_id = ?", role.ID).Error
if err != nil {
log.Error(err)
break
}
err = base.DB.Delete(&role).Error
if err != nil {
log.Error(err)
break
}
case "add-permission", "ap":
// (add-permission|ap) <role_id|role_name> <permission>
err = validateArgumentsCount(len(args), 3, 3)
if err != nil {
log.Error(err)
break
}
var role *models.Role
role, err = findRole(args[1])
if err != nil {
log.Error(err)
break
}
if err := role.AddPermission(args[2]); err != nil {
panic(err)
}
case "quit", "q":
return true
default:
log.Debug("Unknown operation \"" + args[0] + "\".")
}
return false
}
func findRole(id string) (*models.Role, error) {
role := models.Role{}
_, err := strconv.Atoi(id)
if err != nil {
err = base.DB.Set("gorm:auto_preload", true).Where("name = ?", id).First(&role).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.New("role record not found")
} else {
return nil, errors.Wrap(err, "could not query role")
}
}
} else {
err = base.DB.Set("gorm:auto_preload", true).Where("id = ?", id).First(&role).Error
if err != nil {
err = base.DB.Set("gorm:auto_preload", true).Where("name = ?", id).First(&role).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.New("role record not found")
} else {
return nil, errors.Wrap(err, "could not query role")
}
}
}
}
return &role, nil
}
func validateArgumentsCount(count int, min int, max int) (err error) {
if count < min {
err = errors.New("Too few command line parameters")
} else if count > max {
err = errors.New("Too many command line parameters")
}
return
}
func listRole(root treeprint.Tree, role *models.Role) {
roleString := role.Name
if role.Target != nil {
roleString += "(" + color.YellowString(*role.Target) + ")"
}
roleNode := root.AddBranch(roleString + "[" + color.MagentaString("%d", role.ID) + "]")
for _, perm := range role.Permissions {
roleNode.AddNode(color.GreenString(perm.Name) + "[" + color.MagentaString("%d", perm.ID) + "]")
}
}