forked from Forceu/Gokapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApi.go
More file actions
846 lines (794 loc) · 25.1 KB
/
Api.go
File metadata and controls
846 lines (794 loc) · 25.1 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
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
package api
import (
"encoding/json"
"errors"
"github.com/forceu/gokapi/internal/configuration"
"github.com/forceu/gokapi/internal/configuration/database"
"github.com/forceu/gokapi/internal/encryption"
"github.com/forceu/gokapi/internal/helper"
"github.com/forceu/gokapi/internal/logging"
"github.com/forceu/gokapi/internal/models"
"github.com/forceu/gokapi/internal/storage"
"github.com/forceu/gokapi/internal/webserver/fileupload"
"io"
"net/http"
"strings"
"time"
)
const lengthPublicId = 35
const lengthApiKey = 30
const minLengthUser = 2
// Process parses the request and executes the API call or returns an error message to the sender
func Process(w http.ResponseWriter, r *http.Request) {
w.Header().Set("cache-control", "no-store")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
requestUrl := parseRequestUrl(r)
routing, ok := getRouting(requestUrl)
if !ok {
sendError(w, http.StatusBadRequest, "Invalid request")
return
}
var user models.User
user, ok = isAuthorisedForApi(r, routing)
if !ok {
sendError(w, http.StatusUnauthorized, "Unauthorized")
return
}
if routing.RequestParser == nil {
routing.Continue(w, nil, user)
return
}
parser := routing.RequestParser.New()
err := parser.ParseRequest(r)
if err != nil {
sendError(w, http.StatusBadRequest, err.Error())
return
}
routing.Continue(w, parser, user)
}
func parseRequestUrl(r *http.Request) string {
return strings.Replace(r.URL.String(), "/api", "", 1)
}
func apiEditFile(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramFilesModify)
if !ok {
panic("invalid parameter passed")
}
file, ok := database.GetMetaDataById(request.Id)
if !ok {
sendError(w, http.StatusNotFound, "Invalid file ID provided.")
return
}
if file.UserId != user.Id && !user.HasPermission(models.UserPermEditOtherUploads) {
sendError(w, http.StatusUnauthorized, "No permission to edit file.")
return
}
if request.UnlimitedDownloads {
file.UnlimitedDownloads = true
} else {
if request.AllowedDownloads != 0 {
file.DownloadsRemaining = request.AllowedDownloads
file.UnlimitedDownloads = false
}
}
if request.UnlimitedExpiry {
file.UnlimitedTime = true
} else {
if request.ExpiryTimestamp != 0 {
file.ExpireAt = request.ExpiryTimestamp
file.ExpireAtString = storage.FormatTimestamp(request.ExpiryTimestamp)
file.UnlimitedTime = false
}
}
if !request.KeepPassword {
file.PasswordHash = configuration.HashPassword(request.Password, true)
}
if file.HotlinkId != "" && !storage.IsAbleHotlink(file) {
database.DeleteHotlink(file.HotlinkId)
file.HotlinkId = ""
} else if file.HotlinkId == "" && storage.IsAbleHotlink(file) {
storage.AddHotlink(&file)
}
database.SaveMetaData(file)
logging.LogEdit(file, user)
outputFileApiInfo(w, file)
}
// generateNewKey generates and saves a new API key
func generateNewKey(defaultPermissions bool, userId int, friendlyName string) models.ApiKey {
if friendlyName == "" {
friendlyName = "Unnamed key"
}
newKey := models.ApiKey{
Id: helper.GenerateRandomString(lengthApiKey),
PublicId: helper.GenerateRandomString(lengthPublicId),
FriendlyName: friendlyName,
Permissions: models.ApiPermDefault,
IsSystemKey: false,
UserId: userId,
}
if !defaultPermissions {
newKey.Permissions = models.ApiPermNone
}
database.SaveApiKey(newKey)
return newKey
}
// newSystemKey generates a new API key that is only used internally for the GUI
// and will be valid for 48 hours
func newSystemKey(userId int) string {
user, ok := database.GetUser(userId)
if !ok {
panic("user not found")
}
tempKey := models.ApiKey{
Permissions: models.ApiPermAll,
}
if !user.HasPermissionReplace() {
tempKey.RemovePermission(models.ApiPermReplace)
}
if !user.HasPermissionManageUsers() {
tempKey.RemovePermission(models.ApiPermManageUsers)
}
if !user.HasPermissionManageLogs() {
tempKey.RemovePermission(models.ApiPermManageLogs)
}
newKey := models.ApiKey{
Id: helper.GenerateRandomString(lengthApiKey),
PublicId: helper.GenerateRandomString(lengthPublicId),
FriendlyName: "Internal System Key",
Permissions: tempKey.Permissions,
Expiry: time.Now().Add(time.Hour * 48).Unix(),
IsSystemKey: true,
UserId: userId,
}
database.SaveApiKey(newKey)
return newKey.Id
}
// GetSystemKey returns the latest System API key or generates a new one, if none exists or the current one expires
// within the next 24 hours
func GetSystemKey(userId int) string {
key, ok := database.GetSystemKey(userId)
if !ok || key.Expiry < time.Now().Add(time.Hour*24).Unix() {
return newSystemKey(userId)
}
return key.Id
}
func apiDeleteKey(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramAuthDelete)
if !ok {
panic("invalid parameter passed")
}
apiKeyOwner, apiKey, ok := isValidKeyForEditing(request.KeyId)
if !ok {
sendError(w, http.StatusNotFound, "Invalid key ID provided.")
return
}
if apiKeyOwner.Id != user.Id && !user.HasPermission(models.UserPermManageApiKeys) {
sendError(w, http.StatusUnauthorized, "No permission to delete this API key")
return
}
database.DeleteApiKey(apiKey.Id)
}
func apiModifyApiKey(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramAuthModify)
if !ok {
panic("invalid parameter passed")
}
apiKeyOwner, apiKey, ok := isValidKeyForEditing(request.KeyId)
if !ok {
sendError(w, http.StatusNotFound, "Invalid key ID provided.")
return
}
if apiKeyOwner.Id != user.Id && !user.HasPermission(models.UserPermManageApiKeys) {
sendError(w, http.StatusUnauthorized, "No permission to delete this API key")
return
}
switch request.Permission {
case models.ApiPermReplace:
if !apiKeyOwner.HasPermissionReplace() {
sendError(w, http.StatusUnauthorized, "Insufficient user permission for owner to set this API permission")
return
}
case models.ApiPermManageUsers:
if !apiKeyOwner.HasPermissionManageUsers() {
sendError(w, http.StatusUnauthorized, "Insufficient user permission for owner to set this API permission")
return
}
case models.ApiPermManageLogs:
if !apiKeyOwner.HasPermissionManageLogs() {
sendError(w, http.StatusUnauthorized, "Insufficient user permission for owner to set this API permission")
return
}
default:
// do nothing
}
if request.GrantPermission && !apiKey.HasPermission(request.Permission) {
apiKey.GrantPermission(request.Permission)
database.SaveApiKey(apiKey)
return
}
if !request.GrantPermission && apiKey.HasPermission(request.Permission) {
apiKey.RemovePermission(request.Permission)
database.SaveApiKey(apiKey)
}
}
// isValidKeyForEditing checks if the provided API key is either a public or private ID and returns the user and API
// key model (including the private ID)
func isValidKeyForEditing(apiKey string) (models.User, models.ApiKey, bool) {
apiKey = publicKeyToApiKey(apiKey)
user, fullApiKey, ok := isValidApiKey(apiKey, false, models.ApiPermNone)
if !ok {
return models.User{}, models.ApiKey{}, false
}
return user, fullApiKey, true
}
func isValidUserForEditing(w http.ResponseWriter, userId int) (models.User, bool) {
user, ok := database.GetUser(userId)
if !ok {
sendError(w, http.StatusNotFound, "Invalid user id provided.")
return models.User{}, false
}
return user, true
}
func apiCreateApiKey(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramAuthCreate)
if !ok {
panic("invalid parameter passed")
}
key := generateNewKey(request.BasicPermissions, user.Id, request.FriendlyName)
output := models.ApiKeyOutput{
Result: "OK",
Id: key.Id,
PublicId: key.PublicId,
}
result, err := json.Marshal(output)
helper.Check(err)
_, _ = w.Write(result)
}
func apiCreateUser(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramUserCreate)
if !ok {
panic("invalid parameter passed")
}
if len(request.Username) < minLengthUser {
sendError(w, http.StatusBadRequest, "Invalid username provided.")
return
}
_, ok = database.GetUserByName(request.Username)
if ok {
sendError(w, http.StatusConflict, "User already exists.")
return
}
newUser := models.User{
Name: request.Username,
UserLevel: models.UserLevelUser,
}
database.SaveUser(newUser, true)
newUser, ok = database.GetUserByName(request.Username)
if !ok {
sendError(w, http.StatusInternalServerError, "Could not save user")
return
}
logging.LogUserCreation(newUser, user)
_, _ = w.Write([]byte(newUser.ToJson()))
}
func apiChangeFriendlyName(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramAuthFriendlyName)
if !ok {
panic("invalid parameter passed")
}
ownerApiKey, apiKey, ok := isValidKeyForEditing(request.KeyId)
if !ok {
sendError(w, http.StatusNotFound, "Invalid key ID provided.")
return
}
if ownerApiKey.Id != user.Id && !user.HasPermission(models.UserPermManageApiKeys) {
sendError(w, http.StatusUnauthorized, "No permission to edit this key")
return
}
err := renameApiKeyFriendlyName(apiKey.Id, request.FriendlyName)
if err != nil {
sendError(w, http.StatusInternalServerError, err.Error())
return
}
}
func renameApiKeyFriendlyName(id string, newName string) error {
if newName == "" {
newName = "Unnamed key"
}
key, ok := database.GetApiKey(id)
if !ok {
return errors.New("could not modify API key")
}
if key.FriendlyName != newName {
key.FriendlyName = newName
database.SaveApiKey(key)
}
return nil
}
func apiDeleteFile(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramFilesDelete)
if !ok {
panic("invalid parameter passed")
}
file, ok := database.GetMetaDataById(request.Id)
if !ok {
sendError(w, http.StatusNotFound, "Invalid file ID provided.")
return
}
if file.UserId != user.Id && !user.HasPermission(models.UserPermDeleteOtherUploads) {
sendError(w, http.StatusUnauthorized, "No permission to delete this file")
return
}
logging.LogDelete(file, user)
if request.DelaySeconds == 0 {
_ = storage.DeleteFile(request.Id, true)
} else {
_ = storage.DeleteFileSchedule(request.Id, request.DelaySeconds*1000, true)
}
}
func apiRestoreFile(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramFilesRestore)
if !ok {
panic("invalid parameter passed")
}
file, ok := database.GetMetaDataById(request.Id)
if !ok {
sendError(w, http.StatusNotFound, "Invalid file ID provided or file has already been deleted.")
return
}
if file.UserId != user.Id && !user.HasPermission(models.UserPermDeleteOtherUploads) {
sendError(w, http.StatusUnauthorized, "No permission to restore this file")
return
}
file, ok = storage.CancelPendingFileDeletion(file.Id)
if !ok {
sendError(w, http.StatusNotFound, "Invalid file ID provided or file has already been deleted.")
return
}
logging.LogRestore(file, user)
outputFileJson(w, file)
}
func apiChunkAdd(w http.ResponseWriter, r requestParser, _ models.User) {
request, ok := r.(*paramChunkAdd)
if !ok {
panic("invalid parameter passed")
}
maxUpload := int64(configuration.Get().MaxFileSizeMB) * 1024 * 1024
if request.Request.ContentLength > maxUpload {
sendError(w, http.StatusBadRequest, storage.ErrorFileTooLarge.Error())
return
}
request.Request.Body = http.MaxBytesReader(w, request.Request.Body, maxUpload)
err := fileupload.ProcessNewChunk(w, request.Request, true)
if err != nil {
sendError(w, http.StatusBadRequest, err.Error())
return
}
}
func apiChunkComplete(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramChunkComplete)
if !ok {
panic("invalid parameter passed")
}
if request.IsNonBlocking {
go doBlockingPartCompleteChunk(nil, request, user)
_, _ = io.WriteString(w, "{\"result\":\"OK\"}")
return
}
doBlockingPartCompleteChunk(w, request, user)
}
func doBlockingPartCompleteChunk(w http.ResponseWriter, request *paramChunkComplete, user models.User) {
uploadRequest := fileupload.CreateUploadConfig(request.AllowedDownloads,
request.ExpiryDays,
request.Password,
request.UnlimitedTime,
request.UnlimitedDownloads,
request.IsE2E,
request.FileSize)
file, err := fileupload.CompleteChunk(request.Uuid, request.FileHeader, user.Id, uploadRequest)
if err != nil {
sendError(w, http.StatusBadRequest, err.Error())
return
}
logging.LogUpload(file, user)
outputFileJson(w, file)
}
func apiVersionInfo(w http.ResponseWriter, _ requestParser, _ models.User) {
type versionInfo struct {
Version string
VersionInt int
}
result, err := json.Marshal(versionInfo{versionReadable, versionInt})
helper.Check(err)
_, _ = w.Write(result)
}
func apiConfigInfo(w http.ResponseWriter, _ requestParser, _ models.User) {
type configInfo struct {
MaxFilesize int
MaxChunksize int
EndToEndEncryptionEnabled bool
}
config := configuration.Get()
result, err := json.Marshal(configInfo{
MaxFilesize: config.MaxFileSizeMB,
MaxChunksize: config.ChunkSize,
EndToEndEncryptionEnabled: config.Encryption.Level == encryption.EndToEndEncryption,
})
helper.Check(err)
_, _ = w.Write(result)
}
func apiList(w http.ResponseWriter, _ requestParser, user models.User) {
validFiles := getFilesForUser(user)
result, err := json.Marshal(validFiles)
helper.Check(err)
_, _ = w.Write(result)
}
func getFilesForUser(user models.User) []models.FileApiOutput {
var validFiles []models.FileApiOutput
timeNow := time.Now().Unix()
config := configuration.Get()
for _, element := range database.GetAllMetadata() {
if element.UserId == user.Id || user.HasPermission(models.UserPermListOtherUploads) {
if !storage.IsExpiredFile(element, timeNow) {
file, err := element.ToFileApiOutput(config.ServerUrl, config.IncludeFilename)
helper.Check(err)
validFiles = append(validFiles, file)
}
}
}
return validFiles
}
func apiListSingle(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramFilesListSingle)
if !ok {
panic("invalid parameter passed")
}
id := strings.TrimPrefix(request.RequestUrl, "/files/list/")
file, ok := storage.GetFile(id)
if !ok {
sendError(w, http.StatusNotFound, "File not found")
return
}
if file.UserId != user.Id && !user.HasPermission(models.UserPermListOtherUploads) {
sendError(w, http.StatusUnauthorized, "No permission to view file")
return
}
config := configuration.Get()
output, err := file.ToFileApiOutput(config.ServerUrl, config.IncludeFilename)
helper.Check(err)
result, err := json.Marshal(output)
helper.Check(err)
_, _ = w.Write(result)
}
func apiUploadFile(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramFilesAdd)
if !ok {
panic("invalid parameter passed")
}
maxUpload := int64(configuration.Get().MaxFileSizeMB) * 1024 * 1024
if request.Request.ContentLength > maxUpload {
sendError(w, http.StatusBadRequest, storage.ErrorFileTooLarge.Error())
return
}
request.Request.Body = http.MaxBytesReader(w, request.Request.Body, maxUpload)
err := fileupload.ProcessCompleteFile(w, request.Request, user.Id, configuration.Get().MaxMemory)
if err != nil {
sendError(w, http.StatusBadRequest, err.Error())
return
}
}
func apiDuplicateFile(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramFilesDuplicate)
if !ok {
panic("invalid parameter passed")
}
file, ok := storage.GetFile(request.Id)
if !ok {
sendError(w, http.StatusNotFound, "Invalid id provided.")
return
}
if file.UserId != user.Id && !user.HasPermission(models.UserPermListOtherUploads) {
sendError(w, http.StatusUnauthorized, "No permission to duplicate this file")
return
}
uploadRequest := fileupload.CreateUploadConfig(request.AllowedDownloads,
request.ExpiryDays,
request.Password,
request.UnlimitedTime,
request.UnlimitedDownloads,
false, // is not being used by storage.DuplicateFile
0) // is not being used by storage.DuplicateFile
newFile, err := storage.DuplicateFile(file, request.RequestedChanges, request.FileName, uploadRequest)
if err != nil {
sendError(w, http.StatusInternalServerError, err.Error())
return
}
outputFileApiInfo(w, newFile)
}
func apiReplaceFile(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramFilesReplace)
if !ok {
panic("invalid parameter passed")
}
fileOriginal, ok := storage.GetFile(request.Id)
if !ok {
sendError(w, http.StatusNotFound, "Invalid id provided.")
return
}
if fileOriginal.UserId != user.Id && !user.HasPermission(models.UserPermReplaceOtherUploads) {
sendError(w, http.StatusUnauthorized, "No permission to replace this file")
return
}
fileNewContent, ok := storage.GetFile(request.IdNewContent)
if !ok {
sendError(w, http.StatusNotFound, "Invalid id provided.")
return
}
if fileNewContent.UserId != user.Id && !user.HasPermission(models.UserPermListOtherUploads) {
sendError(w, http.StatusUnauthorized, "No permission to duplicate this file")
return
}
modifiedFile, err := storage.ReplaceFile(request.Id, request.IdNewContent, request.Delete)
if err != nil {
switch {
case errors.Is(err, storage.ErrorReplaceE2EFile):
sendError(w, http.StatusBadRequest, "End-to-End encrypted files cannot be replaced")
case errors.Is(err, storage.ErrorFileNotFound):
sendError(w, http.StatusNotFound, "A file with such an ID could not be found")
default:
sendError(w, http.StatusBadRequest, err.Error())
}
return
}
logging.LogReplace(fileOriginal, modifiedFile, user)
outputFileApiInfo(w, modifiedFile)
}
func outputFileApiInfo(w http.ResponseWriter, file models.File) {
config := configuration.Get()
publicOutput, err := file.ToFileApiOutput(config.ServerUrl, config.IncludeFilename)
helper.Check(err)
result, err := json.Marshal(publicOutput)
helper.Check(err)
_, _ = w.Write(result)
}
func outputFileJson(w http.ResponseWriter, file models.File) {
if w == nil {
return
}
config := configuration.Get()
_, _ = io.WriteString(w, file.ToJsonResult(config.ServerUrl, config.IncludeFilename))
}
func apiModifyUser(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramUserModify)
if !ok {
panic("invalid parameter passed")
}
userEdit, ok := isValidUserForEditing(w, request.Id)
if !ok {
return
}
if userEdit.IsSuperAdmin() {
sendError(w, http.StatusBadRequest, "Cannot modify super admin")
return
}
if userEdit.IsSameUser(user.Id) {
sendError(w, http.StatusBadRequest, "Cannot modify yourself")
return
}
logging.LogUserEdit(userEdit, user)
if request.GrantPermission {
if !userEdit.HasPermission(request.Permission) {
userEdit.GrantPermission(request.Permission)
database.SaveUser(userEdit, false)
updateApiKeyPermsOnUserPermChange(userEdit.Id, request.Permission, true)
}
return
}
if userEdit.HasPermission(request.Permission) {
userEdit.RemovePermission(request.Permission)
database.SaveUser(userEdit, false)
updateApiKeyPermsOnUserPermChange(userEdit.Id, request.Permission, false)
}
}
func apiChangeUserRank(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramUserChangeRank)
if !ok {
panic("invalid parameter passed")
}
userEdit, ok := isValidUserForEditing(w, request.Id)
if !ok {
return
}
if userEdit.IsSameUser(user.Id) {
sendError(w, http.StatusBadRequest, "Cannot modify yourself")
return
}
if userEdit.IsSuperAdmin() {
sendError(w, http.StatusBadRequest, "Cannot modify super admin")
return
}
userEdit.UserLevel = request.NewRank
switch request.NewRank {
case models.UserLevelAdmin:
userEdit.Permissions = models.UserPermissionAll
updateApiKeyPermsOnUserPermChange(userEdit.Id, models.UserPermReplaceUploads, true)
updateApiKeyPermsOnUserPermChange(userEdit.Id, models.UserPermManageUsers, true)
case models.UserLevelUser:
userEdit.Permissions = models.UserPermissionNone
updateApiKeyPermsOnUserPermChange(userEdit.Id, models.UserPermReplaceUploads, false)
updateApiKeyPermsOnUserPermChange(userEdit.Id, models.UserPermManageUsers, false)
default:
sendError(w, http.StatusBadRequest, "invalid rank sent")
return
}
logging.LogUserEdit(userEdit, user)
database.SaveUser(userEdit, false)
}
func updateApiKeyPermsOnUserPermChange(userId int, userPerm models.UserPermission, isNewlyGranted bool) {
var affectedPermission models.ApiPermission
switch userPerm {
case models.UserPermManageUsers:
affectedPermission = models.ApiPermManageUsers
case models.UserPermReplaceUploads:
affectedPermission = models.ApiPermReplace
case models.UserPermManageLogs:
affectedPermission = models.ApiPermManageLogs
default:
return
}
for _, apiKey := range database.GetAllApiKeys() {
if apiKey.UserId != userId {
continue
}
if isNewlyGranted {
if apiKey.IsSystemKey {
apiKey.GrantPermission(affectedPermission)
database.SaveApiKey(apiKey)
}
} else if apiKey.HasPermission(affectedPermission) {
apiKey.RemovePermission(affectedPermission)
database.SaveApiKey(apiKey)
}
}
}
func apiResetPassword(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramUserResetPw)
if !ok {
panic("invalid parameter passed")
}
userToEdit, ok := isValidUserForEditing(w, request.Id)
if !ok {
return
}
if userToEdit.IsSuperAdmin() {
sendError(w, http.StatusBadRequest, "Cannot reset pw of super admin")
return
}
if userToEdit.IsSameUser(user.Id) {
sendError(w, http.StatusBadRequest, "Cannot reset password of yourself")
return
}
userToEdit.ResetPassword = true
password := ""
if request.NewPassword {
password = helper.GenerateRandomString(configuration.Environment.MinLengthPassword + 2)
userToEdit.Password = configuration.HashPassword(password, false)
}
database.DeleteAllSessionsByUser(userToEdit.Id)
database.SaveUser(userToEdit, false)
_, _ = w.Write([]byte("{\"Result\":\"ok\",\"password\":\"" + password + "\"}"))
}
func apiDeleteUser(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramUserDelete)
if !ok {
panic("invalid parameter passed")
}
userToDelete, ok := isValidUserForEditing(w, request.Id)
if !ok {
return
}
if userToDelete.IsSuperAdmin() {
sendError(w, http.StatusBadRequest, "Cannot delete super admin")
return
}
if userToDelete.IsSameUser(user.Id) {
sendError(w, http.StatusBadRequest, "Cannot delete yourself")
return
}
logging.LogUserDeletion(userToDelete, user)
database.DeleteUser(userToDelete.Id)
for _, file := range database.GetAllMetadata() {
if file.UserId == userToDelete.Id {
if request.DeleteFiles {
database.DeleteMetaData(file.Id)
} else {
file.UserId = user.Id
database.SaveMetaData(file)
}
}
}
for _, apiKey := range database.GetAllApiKeys() {
if apiKey.UserId == userToDelete.Id {
database.DeleteApiKey(apiKey.Id)
}
}
database.DeleteAllSessionsByUser(userToDelete.Id)
database.DeleteEnd2EndInfo(userToDelete.Id)
}
func apiLogsDelete(_ http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramLogsDelete)
if !ok {
panic("invalid parameter passed")
}
logging.DeleteLogs(user.Name, user.Id, request.Timestamp, request.Request)
}
func apiE2eGet(w http.ResponseWriter, _ requestParser, user models.User) {
info := database.GetEnd2EndInfo(user.Id)
files := getFilesForUser(user)
ids := make([]string, len(files))
for i, file := range files {
ids[i] = file.Id
}
info.AvailableFiles = ids
bytesE2e, err := json.Marshal(info)
helper.Check(err)
_, _ = w.Write(bytesE2e)
}
func apiE2eSet(w http.ResponseWriter, r requestParser, user models.User) {
request, ok := r.(*paramE2eStore)
if !ok {
panic("invalid parameter passed")
}
database.SaveEnd2EndInfo(request.EncryptedInfo, user.Id)
_, _ = w.Write([]byte("\"result\":\"OK\""))
}
func isAuthorisedForApi(r *http.Request, routing apiRoute) (models.User, bool) {
apiKey := r.Header.Get("apikey")
user, _, ok := isValidApiKey(apiKey, true, routing.ApiPerm)
if !ok {
return models.User{}, false
}
return user, true
}
// Probably from new API permission system
func sendError(w http.ResponseWriter, errorInt int, errorMessage string) {
if w == nil {
return
}
w.WriteHeader(errorInt)
_, _ = w.Write([]byte("{\"Result\":\"error\",\"ErrorMessage\":\"" + errorMessage + "\"}"))
}
// publicKeyToApiKey tries to convert a (possible) public key to a private key
// If not a public key or if invalid, the original value is returned
func publicKeyToApiKey(publicKey string) string {
if len(publicKey) == lengthPublicId {
privateApiKey, ok := database.GetApiKeyByPublicKey(publicKey)
if ok {
return privateApiKey
}
}
return publicKey
}
// isValidApiKey checks if the API key provides is valid. If modifyTime is true, it also automatically updates
// the lastUsed timestamp
func isValidApiKey(key string, modifyTime bool, requiredPermissionApiKey models.ApiPermission) (models.User, models.ApiKey, bool) {
if key == "" {
return models.User{}, models.ApiKey{}, false
}
savedKey, ok := database.GetApiKey(key)
if ok && savedKey.Id != "" && (savedKey.Expiry == 0 || savedKey.Expiry > time.Now().Unix()) {
if modifyTime {
savedKey.LastUsed = time.Now().Unix()
database.UpdateTimeApiKey(savedKey)
}
if !savedKey.HasPermission(requiredPermissionApiKey) {
return models.User{}, models.ApiKey{}, false
}
user, ok := database.GetUser(savedKey.UserId)
if !ok {
return models.User{}, models.ApiKey{}, false
}
return user, savedKey, true
}
return models.User{}, models.ApiKey{}, false
}