-
Notifications
You must be signed in to change notification settings - Fork 39
/
main.go
5501 lines (4924 loc) · 174 KB
/
main.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
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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"crypto/tls"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"html"
"html/template"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
gz "github.com/NYTimes/gziphandler"
"github.com/bradfitz/gomemcache/memcache"
gsm "github.com/bradleypeabody/gorilla-sessions-memcache"
sqlite "github.com/gwenn/gosqlite"
"github.com/segmentio/ksuid"
com "github.com/sqlitebrowser/dbhub.io/common"
gfm "github.com/sqlitebrowser/github_flavored_markdown"
"golang.org/x/oauth2"
)
var (
// Log file for incoming HTTPS requests
reqLog *os.File
// Our parsed HTML templates
tmpl *template.Template
// Session cookie storage
store *gsm.MemcacheStore
)
// apiKeyGenHandler generates a new API key, stores it in the PG database, and returns the details to the caller
func apiKeyGenHandler(w http.ResponseWriter, r *http.Request) {
// Retrieve session data (if any)
loggedInUser, validSession, err := checkLogin(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Ensure we have a valid logged in user
if validSession != true {
w.WriteHeader(http.StatusUnauthorized)
return
}
// Generate new API key
creationTime := time.Now()
keyRaw, err := ksuid.NewRandom()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
key := keyRaw.String()
// Save the API key in PG database
err = com.APIKeySave(key, loggedInUser, creationTime)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Log the key creation
log.Printf("New API key created for user '%s', key: '%s'\n", loggedInUser, key)
// Return the API key to the caller
d := com.APIKey{
Key: key,
DateCreated: creationTime,
}
data, err := json.Marshal(d)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprint(w, string(data))
}
// auth0CallbackHandler is called at the end of the Auth0 authentication process, whether successful or not.
// If the authentication process was successful:
// - if the user already has an account on our system then this function creates a login session for them.
// - if the user doesn't yet have an account on our system, they're bounced to the username selection page.
//
// If the authentication process wasn't successful, an error message is displayed.
func auth0CallbackHandler(w http.ResponseWriter, r *http.Request) {
// Auth0 login part, mostly copied from https://github.com/auth0-samples/auth0-golang-web-app (MIT License)
conf := &oauth2.Config{
ClientID: com.Conf.Auth0.ClientID,
ClientSecret: com.Conf.Auth0.ClientSecret,
RedirectURL: "https://" + com.Conf.Web.ServerName + "/x/callback",
Scopes: []string{"openid", "profile"},
Endpoint: oauth2.Endpoint{
AuthURL: "https://" + com.Conf.Auth0.Domain + "/authorize",
TokenURL: "https://" + com.Conf.Auth0.Domain + "/oauth/token",
},
}
code := r.URL.Query().Get("code")
if code == "" {
log.Printf("Login failure from '%v', probably due to blocked 3rd party cookies\n", r.RemoteAddr)
errorPage(w, r, http.StatusInternalServerError,
"Login failure. Please allow 3rd party cookies from https://dbhub.eu.auth0.com then try again (it should then work).")
return
}
token, err := conf.Exchange(oauth2.NoContext, code)
if err != nil {
log.Printf("Login failure: %s\n", err.Error())
errorPage(w, r, http.StatusInternalServerError, "Login failed")
return
}
// Retrieve the user info (JSON format)
conn := conf.Client(oauth2.NoContext, token)
userInfo, err := conn.Get("https://" + com.Conf.Auth0.Domain + "/userinfo")
if err != nil {
errorPage(w, r, http.StatusInternalServerError, err.Error())
return
}
raw, err := io.ReadAll(userInfo.Body)
defer userInfo.Body.Close()
if err != nil {
errorPage(w, r, http.StatusInternalServerError, err.Error())
return
}
// Convert the JSON into something usable
var profile map[string]interface{}
if err = json.Unmarshal(raw, &profile); err != nil {
errorPage(w, r, http.StatusInternalServerError, err.Error())
return
}
// Extract the basic user info we use
var auth0Conn, auth0ID, avatarURL, email, nickName string
em := profile["email"]
if em != nil {
email = em.(string)
}
au := profile["user_id"]
if au != nil {
auth0ID = au.(string)
}
if auth0ID == "" {
log.Printf("Auth0 callback error: Auth0 ID string was empty. Email: %s\n", email)
errorPage(w, r, http.StatusInternalServerError, "Error: Auth0 ID string was empty")
return
}
ni := profile["nickname"]
if ni != nil {
nickName = ni.(string)
}
// Determine if the user has a profile pic we can use
var i map[string]interface{}
if profile["identities"] != nil {
i = profile["identities"].([]interface{})[0].(map[string]interface{})
}
co, ok := i["connection"]
if ok {
auth0Conn = co.(string)
}
if auth0Conn != "Test2DB" { // The Auth0 fallback profile pic's seem pretty lousy, so avoid those
p, ok := profile["picture"]
if ok && p.(string) != "" {
avatarURL = p.(string)
}
}
// If the user has an unverified email address, tell them to verify it before proceeding
ve := profile["email_verified"]
if ve != nil && ve.(bool) != true {
// TODO: Create a nicer notice page for this, as errorPage() doesn't look friendly
errorPage(w, r, http.StatusUnauthorized, "Please check your email. You need to verify your "+
"email address before logging in will work.")
return
}
// Determine the DBHub.io username matching the given Auth0 ID
userName, err := com.UserNameFromAuth0ID(auth0ID)
if err != nil {
errorPage(w, r, http.StatusInternalServerError, err.Error())
return
}
// If the user doesn't already exist, we need to create an account for them
if userName == "" {
if email != "" {
// Check if the email address is already in our system
exists, err := com.CheckEmailExists(email)
if err != nil {
errorPage(w, r, http.StatusInternalServerError, "Email check failed. Can't continue.")
return
}
if exists {
errorPage(w, r, http.StatusConflict,
"Can't create new account: Your email address is already associated "+
"with a different account in our system.")
return
}
}
// Create a special session cookie, purely for the registration page
sess, err := store.Get(r, "user-reg")
if err != nil {
if err == memcache.ErrCacheMiss {
// Seems like a stale session token, so delete the session and reload the page
sess.Options.MaxAge = -1
err = sess.Save(r, w)
if err != nil {
errorPage(w, r, http.StatusInternalServerError, err.Error())
return
}
http.Redirect(w, r, "/selectusername", http.StatusTemporaryRedirect)
return
}
errorPage(w, r, http.StatusBadRequest, err.Error())
return
}
sess.Values["registrationinprogress"] = true
sess.Values["auth0id"] = auth0ID
sess.Values["avatar"] = avatarURL
sess.Values["email"] = email
sess.Values["nickname"] = nickName
err = sess.Save(r, w)
if err != nil {
errorPage(w, r, http.StatusInternalServerError, err.Error())
return
}
// Bounce to a new page, for the user to select their preferred username
http.Redirect(w, r, "/selectusername", http.StatusSeeOther)
return
}
// If Auth0 provided a picture URL for the user, check if it's different to what we already have (eg it may have
// been updated)
if avatarURL != "" {
usr, err := com.User(userName)
if err != nil {
errorPage(w, r, http.StatusBadRequest, err.Error())
return
}
if usr.AvatarURL != avatarURL {
// The Auth0 provided pic URL is different to what we have already, so we update the database with the new
// value
err = com.UpdateAvatarURL(userName, avatarURL)
if err != nil {
errorPage(w, r, http.StatusBadRequest, err.Error())
return
}
}
}
// Create a session cookie for the user
sess, err := store.Get(r, "dbhub-user")
if err != nil {
errorPage(w, r, http.StatusBadRequest, err.Error())
return
}
sess.Values["UserName"] = userName
sess.Save(r, w)
if err != nil {
errorPage(w, r, http.StatusInternalServerError, err.Error())
return
}
// Login completed, so bounce to the users' profile page
http.Redirect(w, r, "/"+userName, http.StatusSeeOther)
}
// Returns a list of the branches present in a database
func branchNamesHandler(w http.ResponseWriter, r *http.Request) {
// Retrieve session data (if any)
loggedInUser, validSession, err := checkLogin(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Ensure we have a valid logged in user
if validSession != true {
w.WriteHeader(http.StatusUnauthorized)
return
}
// Extract the required form variables
usr, dbFolder, dbName, err := com.GetUFD(r, true)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
dbOwner := strings.ToLower(usr)
// If any of the required values were empty, indicate failure
if dbOwner == "" || dbFolder == "" || dbName == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
// Make sure the database exists in the system
exists, err := com.CheckDBPermissions(loggedInUser, dbOwner, dbFolder, dbName, false)
if err != err {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
if !exists {
log.Printf("%s: Validation failed for database name: %s", com.GetCurrentFunctionName(), err)
w.WriteHeader(http.StatusNotFound)
return
}
// Retrieve the branch info for the database
branchList, err := com.GetBranches(dbOwner, dbFolder, dbName)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
defBranch, err := com.GetDefaultBranchName(dbOwner, dbFolder, dbName)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
// Prepare the branch list for sending
var b struct {
Branches []string `json:"branches"`
DefaultBranch string `json:"default_branch"`
}
for name := range branchList {
b.Branches = append(b.Branches, name)
}
b.DefaultBranch = defBranch
data, err := json.MarshalIndent(b, "", " ")
if err != nil {
log.Println(err)
return
}
// Return the branch list
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, string(data))
}
func checkLogin(r *http.Request) (loggedInUser string, validSession bool, err error) {
// Retrieve session data (if any)
var u interface{}
if com.Conf.Environment.Environment == "production" {
sess, err := store.Get(r, "dbhub-user")
if err != nil {
return "", false, err
}
u = sess.Values["UserName"]
} else {
// Non-production environments (eg dev, test) can directly set the logged in user
u = com.Conf.Environment.UserOverride
if u == "" {
u = nil
}
}
if u != nil {
loggedInUser = u.(string)
validSession = true
}
return
}
func collectPageAuth0Info() (auth0 com.Auth0Set) {
auth0.CallbackURL = "https://" + com.Conf.Web.ServerName + "/x/callback"
auth0.ClientID = com.Conf.Auth0.ClientID
auth0.Domain = com.Conf.Auth0.Domain
return
}
func collectPageMetaInfo(r *http.Request, meta *com.MetaInfo, requireLogin bool, getOwnerAndDatabaseFromUrl bool, getOwnerAndDatabaseFromData bool) (errCode int, err error) {
// Server name
meta.Server = com.Conf.Web.ServerName
// Retrieve session data (if any)
loggedInUser, validSession, err := checkLogin(r)
if err != nil {
return http.StatusBadRequest, err
}
if validSession {
meta.LoggedInUser = loggedInUser
}
// Ensure we have a valid logged in user
if requireLogin && !validSession {
return http.StatusUnauthorized, fmt.Errorf("You need to be logged in")
}
// Retrieve the details and status updates count for the logged in user
if validSession {
ur, err := com.User(loggedInUser)
if err != nil {
return http.StatusBadRequest, err
}
if ur.AvatarURL != "" {
meta.AvatarURL = ur.AvatarURL + "&s=48"
}
meta.NumStatusUpdates, err = com.UserStatusUpdates(loggedInUser)
if err != nil {
return http.StatusBadRequest, err
}
}
// Retrieve the database owner & name
if getOwnerAndDatabaseFromUrl || getOwnerAndDatabaseFromData {
// TODO: Add folder and branch name support
var dbOwner, dbName string
if getOwnerAndDatabaseFromUrl {
dbOwner, dbName, err = com.GetOD(1, r) // 1 = Ignore "/xxx/" at the start of the URL
if err != nil {
return http.StatusBadRequest, err
}
} else {
// Get owner + dbname combination from post data
dbOwner, _, dbName, err = com.GetUFD(r, true)
if dbOwner == "" || dbName == "" {
err = nil
return
}
if err != nil {
return http.StatusBadRequest, err
}
}
// Validate the supplied information
if dbOwner == "" || dbName == "" {
return http.StatusBadRequest, fmt.Errorf("Missing database owner or database name")
}
// Check if the database exists
exists, err := com.CheckDBPermissions(loggedInUser, dbOwner, "/", dbName, false)
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("Database failure when looking up database details")
}
if !exists {
return http.StatusNotFound, fmt.Errorf("That database doesn't seem to exist")
}
// Retrieve correctly capitalised username for the database owner
usr, err := com.User(dbOwner)
if err != nil {
return http.StatusBadRequest, err
}
// Store information
meta.Database = dbName
meta.Owner = usr.Username
meta.Folder = "/"
// Retrieve the "forked from" information
meta.ForkOwner, meta.ForkFolder, meta.ForkDatabase, meta.ForkDeleted, err = com.ForkedFrom(meta.Owner, meta.Folder, meta.Database)
if err != nil {
return http.StatusBadRequest, err
}
}
// Pass along the environment setting
meta.Environment = com.Conf.Environment.Environment
return
}
func createBranchHandler(w http.ResponseWriter, r *http.Request) {
// Retrieve session data (if any)
loggedInUser, validSession, err := checkLogin(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Ensure we have a valid logged in user
if validSession != true {
errorPage(w, r, http.StatusUnauthorized, "You need to be logged in")
return
}
// Extract and validate the form variables
dbOwner, dbName, commit, err := com.GetFormUDC(r)
if err != nil {
errorPage(w, r, http.StatusBadRequest, "Missing or incorrect data supplied")
return
}
branchName, err := com.GetFormBranch(r)
if err != nil {
errorPage(w, r, http.StatusBadRequest, "Missing or incorrect branch name")
return
}
bd := r.PostFormValue("branchdesc") // Optional
// If given, validate the branch description field
var branchDesc string
if bd != "" {
err = com.Validate.Var(bd, "markdownsource")
if err != nil {
errorPage(w, r, http.StatusBadRequest, "Invalid characters in branch description")
return
}
branchDesc = bd
}
// Check if the requested database exists
dbFolder := "/"
exists, err := com.CheckDBPermissions(loggedInUser, dbOwner, dbFolder, dbName, true)
if err != nil {
errorPage(w, r, http.StatusInternalServerError, err.Error())
return
}
if !exists {
errorPage(w, r, http.StatusNotFound, fmt.Sprintf("Database '%s%s%s' doesn't exist", dbOwner, dbFolder,
dbName))
return
}
// Read the branch heads list from the database
branches, err := com.GetBranches(dbOwner, dbFolder, dbName)
if err != nil {
errorPage(w, r, http.StatusInternalServerError, err.Error())
return
}
// Make sure the branch name doesn't already exist
_, ok := branches[branchName]
if ok {
errorPage(w, r, http.StatusConflict, "A branch of that name already exists!")
return
}
// Count the number of commits in the new branch
commitList, err := com.GetCommitList(dbOwner, dbFolder, dbName)
if err != nil {
errorPage(w, r, http.StatusInternalServerError, err.Error())
return
}
c, ok := commitList[commit]
if !ok {
errorPage(w, r, http.StatusBadRequest, fmt.Sprint("The given commit ID doesn't exist"))
return
}
commitCount := 1
for c.Parent != "" {
commitCount++
c, ok = commitList[c.Parent]
if !ok {
log.Printf("Error when counting commits in new branch '%s' of database '%s%s%s'\n", com.SanitiseLogString(branchName),
com.SanitiseLogString(dbOwner), com.SanitiseLogString(dbFolder), com.SanitiseLogString(dbName))
return
}
}
// Create the branch
newBranch := com.BranchEntry{
Commit: commit,
CommitCount: commitCount,
Description: branchDesc,
}
branches[branchName] = newBranch
err = com.StoreBranches(dbOwner, dbFolder, dbName, branches)
if err != nil {
errorPage(w, r, http.StatusInternalServerError, err.Error())
return
}
// Invalidate the memcache data for the database, so the new branch count gets picked up
err = com.InvalidateCacheEntry(loggedInUser, dbOwner, dbFolder, dbName, "") // Empty string indicates "for all versions"
if err != nil {
// Something went wrong when invalidating memcached entries for the database
log.Printf("Error when invalidating memcache entries: %s\n", err.Error())
return
}
// Bounce to the branches page
http.Redirect(w, r, fmt.Sprintf("/branches/%s%s%s", loggedInUser, dbFolder, dbName), http.StatusSeeOther)
}
// Receives incoming info for adding a comment to an existing discussion
func createCommentHandler(w http.ResponseWriter, r *http.Request) {
// Retrieve session data (if any)
loggedInUser, validSession, err := checkLogin(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Ensure we have a valid logged in user
if validSession != true {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, "You need to be logged in")
return
}
// Extract and validate the form variables
dbOwner, dbFolder, dbName, err := com.GetUFD(r, false)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Missing or incorrect data supplied")
return
}
// Ensure a discussion ID was given
a := r.PostFormValue("discid")
if a == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Missing discussion id")
return
}
discID, err := strconv.Atoi(a)
if err != nil {
log.Printf("Error converting string '%s' to integer in function '%s': %s\n", com.SanitiseLogString(a),
com.GetCurrentFunctionName(), err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Error when parsing discussion id value")
return
}
// Check if the discussion should also be closed or reopened
discClose := false
c := r.PostFormValue("close")
if c == "true" {
discClose = true
}
// If comment text was provided, then validate it. Note that if the flag for closing/reopening the discussion has
// been set, then comment text isn't required. In all other situations it is
rawTxt := r.PostFormValue("comtext")
if rawTxt == "" && discClose == false {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Comment can't be empty!")
return
}
var comText string
if discClose == false || (discClose == true && rawTxt != "") {
// Unescape and validate the comment text
t, err := url.QueryUnescape(rawTxt)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "Error when unescaping comment field value")
return
}
err = com.Validate.Var(t, "markdownsource")
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Invalid characters in the new discussions' main text field")
return
}
comText = t
}
// Check if the requested database exists
exists, err := com.CheckDBPermissions(loggedInUser, dbOwner, dbFolder, dbName, false) // We don't require write access since discussions are considered public
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
if !exists {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Database '%s%s%s' doesn't exist", dbOwner, dbFolder, dbName)
return
}
// Add the comment to PostgreSQL
err = com.StoreComment(dbOwner, dbFolder, dbName, loggedInUser, discID, comText, discClose,
com.CLOSED_WITHOUT_MERGE) // com.CLOSED_WITHOUT_MERGE is ignored for discussions. It's only used for MRs
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
// Invalidate the memcache data for the database, so if the discussion counter for the database was changed it
// gets picked up
if discClose {
err = com.InvalidateCacheEntry(loggedInUser, dbOwner, dbFolder, dbName, "") // Empty string indicates "for all versions"
if err != nil {
// Something went wrong when invalidating memcached entries for the database
log.Printf("Error when invalidating memcache entries: %s\n", err.Error())
return
}
}
// Send a success message
w.WriteHeader(http.StatusOK)
}
// Receives incoming info from the "Create a new discussion" page, adds the discussion to PostgreSQL,
// then bounces to the discussion page
func createDiscussHandler(w http.ResponseWriter, r *http.Request) {
// Retrieve session data (if any)
loggedInUser, validSession, err := checkLogin(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Ensure we have a valid logged in user
if validSession != true {
errorPage(w, r, http.StatusUnauthorized, "You need to be logged in")
return
}
// Extract and validate the form variables
dbOwner, dbFolder, dbName, err := com.GetUFD(r, false)
if err != nil {
errorPage(w, r, http.StatusBadRequest, "Missing or incorrect data supplied")
return
}
// Validate the discussions' title
tl := r.PostFormValue("title")
err = com.ValidateDiscussionTitle(tl)
if err != nil {
errorPage(w, r, http.StatusBadRequest, "Invalid characters in the new discussions' title")
return
}
discTitle := tl
// Validate the discussions' text
txt := r.PostFormValue("disctxt")
if txt == "" {
errorPage(w, r, http.StatusBadRequest, "Discussion body can't be empty!")
return
}
err = com.Validate.Var(txt, "markdownsource")
if err != nil {
errorPage(w, r, http.StatusBadRequest, "Invalid characters in the new discussions' main text field")
return
}
discText := txt
// Check if the requested database exists
exists, err := com.CheckDBPermissions(loggedInUser, dbOwner, dbFolder, dbName, false) // We don't require write access since discussions are considered public
if err != nil {
errorPage(w, r, http.StatusInternalServerError, err.Error())
return
}
if !exists {
errorPage(w, r, http.StatusNotFound, fmt.Sprintf("Database '%s%s%s' doesn't exist", dbOwner, dbFolder,
dbName))
return
}
// Add the discussion detail to PostgreSQL
id, err := com.StoreDiscussion(dbOwner, dbFolder, dbName, loggedInUser, discTitle, discText, com.DISCUSSION,
com.MergeRequestEntry{})
if err != nil {
errorPage(w, r, http.StatusInternalServerError, err.Error())
return
}
// Generate an event about the new discussion
details := com.EventDetails{
DBName: dbName,
DiscID: id,
Folder: dbFolder,
Owner: dbOwner,
Title: discTitle,
Type: com.EVENT_NEW_DISCUSSION,
URL: fmt.Sprintf("/discuss/%s%s%s?id=%d", url.PathEscape(dbOwner), dbFolder, url.PathEscape(dbName), id),
UserName: loggedInUser,
}
err = com.NewEvent(details)
if err != nil {
log.Printf("Error when creating a new event: %s\n", err.Error())
return
}
// Invalidate the memcache data for the database, so the new discussion count gets picked up
err = com.InvalidateCacheEntry(loggedInUser, dbOwner, dbFolder, dbName, "") // Empty string indicates "for all versions"
if err != nil {
// Something went wrong when invalidating memcached entries for the database
log.Printf("Error when invalidating memcache entries: %s\n", err.Error())
return
}
// Bounce to the discussions page
http.Redirect(w, r, fmt.Sprintf("/discuss/%s%s%s?id=%d", dbOwner, dbFolder, dbName, id), http.StatusSeeOther)
}
// Receives incoming requests from the merge request creation page, creating them if the info is correct
func createMergeHandler(w http.ResponseWriter, r *http.Request) {
// Retrieve session data (if any)
loggedInUser, validSession, err := checkLogin(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Ensure we have a valid logged in user
if validSession != true {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, "You need to be logged in")
return
}
// Extract and validate the form variables
userName, err := com.GetUsername(r, false)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, err.Error())
return
}
if userName == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Missing username in supplied fields")
return
}
// Retrieve source owner
o := r.PostFormValue("sourceowner")
srcOwner, err := url.QueryUnescape(o)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
err = com.ValidateUser(srcOwner)
if err != nil {
log.Printf("Validation failed for username: '%s'- %s", com.SanitiseLogString(srcOwner), err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
// Retrieve source folder
f := r.PostFormValue("sourcefolder")
srcFolder, err := url.QueryUnescape(f)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
err = com.ValidateFolder(srcFolder)
if err != nil {
log.Printf("Validation failed for folder: '%s' - %s", com.SanitiseLogString(srcFolder), err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
// Retrieve source database name
d := r.PostFormValue("sourcedbname")
srcDBName, err := url.QueryUnescape(d)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
err = com.ValidateDB(srcDBName)
if err != nil {
log.Printf("Validation failed for database name '%s': %s", com.SanitiseLogString(srcDBName), err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
// Retrieve source branch name
a := r.PostFormValue("sourcebranch")
srcBranch, err := url.QueryUnescape(a)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
err = com.ValidateBranchName(srcBranch)
if err != nil {
log.Printf("Validation failed for branch name '%s': %s", com.SanitiseLogString(srcBranch), err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
// Retrieve destination owner
o = r.PostFormValue("destowner")
destOwner, err := url.QueryUnescape(o)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
err = com.ValidateUser(destOwner)
if err != nil {
log.Printf("Validation failed for username: '%s'- %s", com.SanitiseLogString(destOwner), err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
// Retrieve destination folder
f = r.PostFormValue("destfolder")
destFolder, err := url.QueryUnescape(f)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
err = com.ValidateFolder(destFolder)
if err != nil {
log.Printf("Validation failed for folder: '%s' - %s", com.SanitiseLogString(destFolder), err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
// Retrieve destination database name
d = r.PostFormValue("destdbname")
destDBName, err := url.QueryUnescape(d)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
err = com.ValidateDB(destDBName)
if err != nil {
log.Printf("Validation failed for database name '%s': %s", com.SanitiseLogString(destDBName), err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
// Retrieve destination branch name
a = r.PostFormValue("destbranch")
destBranch, err := url.QueryUnescape(a)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
err = com.ValidateBranchName(destBranch)
if err != nil {
log.Printf("Validation failed for branch name '%s': %s", com.SanitiseLogString(destBranch), err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
// Validate the MR title
tl := r.PostFormValue("title")
if tl == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Title can't be blank")
return
}
title, err := url.QueryUnescape(tl)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
err = com.ValidateDiscussionTitle(title)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Invalid characters in the merge request title")
return
}
// Validate the MR description
t := r.PostFormValue("desc")
if t == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Merge request description can't be empty")
return
}
descrip, err := url.QueryUnescape(t)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
err = com.Validate.Var(title, "markdownsource")
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, "Invalid characters in the description field")
return
}
// Make sure none of the required fields is empty
if srcOwner == "" || srcFolder == "" || srcDBName == "" || srcBranch == "" || destOwner == "" || destFolder ==
"" || destDBName == "" || destBranch == "" || title == "" || descrip == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Some of the (required) supplied fields are empty")
return
}