-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.go
418 lines (362 loc) · 11.8 KB
/
user.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
package main
/*
User Management System
Entry points for handler user functions
*/
import (
"encoding/json"
"net/http"
"strconv"
"strings"
uuid "github.com/satori/go.uuid"
auth "imuslab.com/arozos/mod/auth"
module "imuslab.com/arozos/mod/modules"
prout "imuslab.com/arozos/mod/prouter"
user "imuslab.com/arozos/mod/user"
"imuslab.com/arozos/mod/utils"
)
func UserSystemInit() {
//Create a new User Handler
uh, err := user.NewUserHandler(sysdb, authAgent, permissionHandler, baseStoragePool, &shareEntryTable)
if err != nil {
panic(err)
}
userHandler = uh
/*
router := prout.NewModuleRouter(prout.RouterOption{
ModuleName: "System Settings",
AdminOnly: false,
UserHandler: userHandler,
DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
utils.SendErrorResponse(w, "Permission Denied")
},
})
*/
//Create Endpoint Listeners
http.HandleFunc("/system/users/list", user_handleList)
//Everyone logged in should have permission to view their profile and change their password
http.HandleFunc("/system/users/userinfo", func(w http.ResponseWriter, r *http.Request) {
authAgent.HandleCheckAuth(w, r, user_handleUserInfo)
})
//Interface info should be able to view by everyone logged in
http.HandleFunc("/system/users/interfaceinfo", func(w http.ResponseWriter, r *http.Request) {
authAgent.HandleCheckAuth(w, r, user_getInterfaceInfo)
})
//Register setting interface for module configuration
registerSetting(settingModule{
Name: "My Account",
Desc: "Manage your account and password",
IconPath: "SystemAO/users/img/small_icon.png",
Group: "Users",
StartDir: "SystemAO/users/account.html",
RequireAdmin: false,
})
registerSetting(settingModule{
Name: "User List",
Desc: "A list of users registered on this system",
IconPath: "SystemAO/users/img/small_icon.png",
Group: "Users",
StartDir: "SystemAO/users/userList.html",
RequireAdmin: true,
})
//Register auth management events that requires user handler
adminRouter := prout.NewModuleRouter(prout.RouterOption{
ModuleName: "System Settings",
AdminOnly: true,
UserHandler: userHandler,
DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
utils.SendErrorResponse(w, "Permission Denied")
},
})
//Handle Authentication Unregister Handler
adminRouter.HandleFunc("/system/auth/unregister", authAgent.HandleUnregister)
adminRouter.HandleFunc("/system/users/editUser", user_handleUserEdit)
adminRouter.HandleFunc("/system/users/removeUser", user_handleUserRemove)
}
// Remove a user from the system
func user_handleUserRemove(w http.ResponseWriter, r *http.Request) {
username, err := utils.PostPara(r, "username")
if err != nil {
utils.SendErrorResponse(w, "Username not defined")
return
}
if !authAgent.UserExists(username) {
utils.SendErrorResponse(w, "User not exists")
return
}
userinfo, err := userHandler.GetUserInfoFromUsername(username)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
currentUserinfo, err := userHandler.GetUserInfoFromRequest(w, r)
if err != nil {
//This user has not logged in
utils.SendErrorResponse(w, "User not logged in")
return
}
if currentUserinfo.Username == userinfo.Username {
//This user has not logged in
utils.SendErrorResponse(w, "You can't remove yourself")
return
}
//Clear Core User Data
userinfo.RemoveUser()
//Clearn Up FileSystem preferences
system_fs_removeUserPreferences(username)
utils.SendOK(w)
}
func user_handleUserEdit(w http.ResponseWriter, r *http.Request) {
userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
if err != nil {
//This user has not logged in
utils.SendErrorResponse(w, "User not logged in")
return
}
if userinfo.IsAdmin() == false {
//Require admin access
utils.SendErrorResponse(w, "Permission Denied")
return
}
opr, _ := utils.PostPara(r, "opr")
username, _ := utils.PostPara(r, "username")
if !authAgent.UserExists(username) {
utils.SendErrorResponse(w, "User not exists")
return
}
if opr == "" {
//List this user information
type returnValue struct {
Username string
Icondata string
Usergroup []string
Quota int64
}
iconData := getUserIcon(username)
userGroup, err := permissionHandler.GetUsersPermissionGroup(username)
if err != nil {
utils.SendErrorResponse(w, "Unable to get user group")
return
}
//Parse the user permission groupts
userGroupNames := []string{}
for _, gp := range userGroup {
userGroupNames = append(userGroupNames, gp.Name)
}
//Get the user's storaeg quota
userinfo, _ := userHandler.GetUserInfoFromUsername(username)
jsonString, _ := json.Marshal(returnValue{
Username: username,
Icondata: iconData,
Usergroup: userGroupNames,
Quota: userinfo.StorageQuota.GetUserStorageQuota(),
})
utils.SendJSONResponse(w, string(jsonString))
} else if opr == "updateUserGroup" {
//Update the target user's group
newgroup, err := utils.PostPara(r, "newgroup")
if err != nil {
systemWideLogger.PrintAndLog("User", err.Error(), err)
utils.SendErrorResponse(w, "New Group not defined")
return
}
newQuota, err := utils.PostPara(r, "quota")
if err != nil {
systemWideLogger.PrintAndLog("User", err.Error(), err)
utils.SendErrorResponse(w, "Quota not defined")
return
}
quotaInt, err := strconv.Atoi(newQuota)
if err != nil {
systemWideLogger.PrintAndLog("User", err.Error(), err)
utils.SendErrorResponse(w, "Invalid Quota Value")
return
}
newGroupKeys := []string{}
err = json.Unmarshal([]byte(newgroup), &newGroupKeys)
if err != nil {
systemWideLogger.PrintAndLog("User", err.Error(), err)
utils.SendErrorResponse(w, "Unable to parse new groups")
return
}
if len(newGroupKeys) == 0 {
utils.SendErrorResponse(w, "User must be in at least one user permission group")
return
}
//Check if each group exists
for _, thisgp := range newGroupKeys {
if !permissionHandler.GroupExists(thisgp) {
utils.SendErrorResponse(w, "Group not exists, given: "+thisgp)
return
}
}
//OK to proceed
userinfo, err := userHandler.GetUserInfoFromUsername(username)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
//Check if the current user is the only one admin in the administrator group and he is leaving the group
allAdministratorGroupUsers, err := userHandler.GetUsersInPermissionGroup("administrator")
if err == nil {
//Skip checking if error
if len(allAdministratorGroupUsers) == 1 && userinfo.UserIsInOneOfTheGroupOf([]string{"administrator"}) && !utils.StringInArray(newGroupKeys, "administrator") {
//Current administrator group only contain 1 user
//This user is in the administrator group
//The user want to unset himself from administrator group
//Reject the operation as this will cause system lockdown
utils.SendErrorResponse(w, "You are the only administrator. You cannot remove yourself from the administrator group.")
return
}
}
//Get the permission groups by their ids
newPermissioGroups := userHandler.GetPermissionHandler().GetPermissionGroupByNameList(newGroupKeys)
//Set the user's permission to these groups
userinfo.SetUserPermissionGroup(newPermissioGroups)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
//Write to quota handler
userinfo.StorageQuota.SetUserStorageQuota(int64(quotaInt))
utils.SendOK(w)
} else if opr == "resetPassword" {
//Reset password for this user
//Generate a random password for this user
tmppassword := uuid.NewV4().String()
hashedPassword := auth.Hash(tmppassword)
err := sysdb.Write("auth", "passhash/"+username, hashedPassword)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
//Finish. Send back the reseted password
utils.SendJSONResponse(w, "\""+tmppassword+"\"")
} else {
utils.SendErrorResponse(w, "Not supported opr")
return
}
}
// Get the user interface info for the user to launch into
func user_getInterfaceInfo(w http.ResponseWriter, r *http.Request) {
userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
if err != nil {
//User not logged in
utils.SendErrorResponse(w, "User not logged in")
return
}
interfacingModules := userinfo.GetInterfaceModules()
interfaceModuleInfos := []module.ModuleInfo{}
for _, im := range interfacingModules {
interfaceModuleInfos = append(interfaceModuleInfos, *moduleHandler.GetModuleInfoByID(im))
}
jsonString, _ := json.Marshal(interfaceModuleInfos)
utils.SendJSONResponse(w, string(jsonString))
}
func user_handleUserInfo(w http.ResponseWriter, r *http.Request) {
username, err := authAgent.GetUserName(w, r)
if err != nil {
utils.SendErrorResponse(w, "User not logged in")
return
}
opr, _ := utils.PostPara(r, "opr")
if opr == "" {
//Listing mode
iconData := getUserIcon(username)
userGroup, err := permissionHandler.GetUsersPermissionGroup(username)
if err != nil {
utils.SendErrorResponse(w, "Unable to get user group")
return
}
userGroupNames := []string{}
for _, group := range userGroup {
userGroupNames = append(userGroupNames, group.Name)
}
type returnValue struct {
Username string
Icondata string
Usergroup []string
}
jsonString, _ := json.Marshal(returnValue{
Username: username,
Icondata: iconData,
Usergroup: userGroupNames,
})
utils.SendJSONResponse(w, string(jsonString))
return
} else if opr == "changepw" {
oldpw, _ := utils.PostPara(r, "oldpw")
newpw, _ := utils.PostPara(r, "newpw")
if oldpw == "" || newpw == "" {
utils.SendErrorResponse(w, "Password cannot be empty")
return
}
//valid the old password
hashedPassword := auth.Hash(oldpw)
var passwordInDB string
err = sysdb.Read("auth", "passhash/"+username, &passwordInDB)
if hashedPassword != passwordInDB {
//Old password entry invalid.
utils.SendErrorResponse(w, "Invalid old password.")
return
}
//Logout users from all switchable accounts
authAgent.SwitchableAccountManager.ExpireUserFromAllSwitchableAccountPool(username)
//OK! Change user password
newHashedPassword := auth.Hash(newpw)
sysdb.Write("auth", "passhash/"+username, newHashedPassword)
utils.SendOK(w)
} else if opr == "changeprofilepic" {
picdata, _ := utils.PostPara(r, "picdata")
if picdata != "" {
setUserIcon(username, picdata)
utils.SendOK(w)
} else {
utils.SendErrorResponse(w, "Empty image data received.")
return
}
} else {
utils.SendErrorResponse(w, "Not supported opr")
return
}
}
func user_handleList(w http.ResponseWriter, r *http.Request) {
userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
if err != nil {
//This user has not logged in
utils.SendErrorResponse(w, "User not logged in")
return
}
if authAgent.CheckAuth(r) {
entries, _ := sysdb.ListTable("auth")
var results [][]interface{}
for _, keypairs := range entries {
if strings.Contains(string(keypairs[0]), "group/") {
username := strings.Split(string(keypairs[0]), "/")[1]
group := []string{}
//Get user icon if it exists in the database
userIcon := getUserIcon(username)
json.Unmarshal(keypairs[1], &group)
var thisUserInfo []interface{}
thisUserInfo = append(thisUserInfo, username)
thisUserInfo = append(thisUserInfo, group)
thisUserInfo = append(thisUserInfo, userIcon)
thisUserInfo = append(thisUserInfo, username == userinfo.Username)
results = append(results, thisUserInfo)
}
}
jsonString, _ := json.Marshal(results)
utils.SendJSONResponse(w, string(jsonString))
} else {
utils.SendErrorResponse(w, "Permission Denied")
}
}
func getUserIcon(username string) string {
var userIconpath []byte
sysdb.Read("auth", "profilepic/"+username, &userIconpath)
return string(userIconpath)
}
func setUserIcon(username string, base64data string) {
sysdb.Write("auth", "profilepic/"+username, []byte(base64data))
return
}