-
Notifications
You must be signed in to change notification settings - Fork 7
/
nb.go
2600 lines (2276 loc) · 76.9 KB
/
nb.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/aes"
"crypto/cipher"
"crypto/md5"
cryptorand "crypto/rand"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"html"
"io"
"log"
"math"
"math/rand"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
sqlite "github.com/mattn/go-sqlite3"
"github.com/shurcooL/github_flavored_markdown"
"golang.org/x/crypto/bcrypt"
)
const ADMIN_ID = 1
const SUBMISSION = 0
const COMMENT = 1
const SETTINGS_LIMIT = 30
type User struct {
Userid int64
Username string
Active bool
Email string
}
type Site struct {
Title string
Desc string
Gravityf float64
}
type Entry struct {
Entryid int64
Thing int
Title string
Url string
Body string
Createdt string
Userid int64
Parentid int64
}
type Cat struct {
Catid int64
Name string
}
type VoteResult struct {
Entryid int64 `json:"entryid"`
Userid int64 `json:"userid"`
TotalVotes int `json:"totalvotes"`
}
type QIndex struct {
Latest string
Username string
Cat int64
Tag string
}
func main() {
os.Args = os.Args[1:]
sw, parms := parseArgs(os.Args)
// [-i new_file] Create and initialize newsboard file
if sw["i"] != "" {
dbfile := sw["i"]
if fileExists(dbfile) {
s := fmt.Sprintf("File '%s' already exists. Can't initialize it.\n", dbfile)
fmt.Printf(s)
os.Exit(1)
}
createAndInitTables(dbfile)
os.Exit(0)
}
// Need to specify a notes file as first parameter.
if len(parms) == 0 {
s := `Usage:
Start webservice using existing newsboard file:
nb <newsboard_file> [port]
Initialize new newsboard file:
nb -i <newsboard_file>
`
fmt.Printf(s)
os.Exit(0)
}
// Exit if specified notes file doesn't exist.
dbfile := parms[0]
if !fileExists(dbfile) {
s := fmt.Sprintf(`Newboard file '%s' doesn't exist. Create one using:
nb -i <newsboard_file>
`, dbfile)
fmt.Printf(s)
os.Exit(1)
}
registerSqliteFuncs()
db, err := sql.Open("sqlite3_custom", dbfile)
if err != nil {
fmt.Printf("Error opening '%s' (%s)\n", dbfile, err)
os.Exit(1)
}
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "./static/news-paper.ico") })
http.HandleFunc("/login/", loginHandler(db))
http.HandleFunc("/logout/", logoutHandler(db))
http.HandleFunc("/createaccount/", createaccountHandler(db))
http.HandleFunc("/adminsetup/", adminsetupHandler(db))
http.HandleFunc("/usersetup/", usersetupHandler(db))
http.HandleFunc("/edituser/", edituserHandler(db))
http.HandleFunc("/activateuser/", activateuserHandler(db))
http.HandleFunc("/createcat/", createcatHandler(db))
http.HandleFunc("/editcat/", editcatHandler(db))
http.HandleFunc("/delcat/", delcatHandler(db))
http.HandleFunc("/", indexHandler(db))
http.HandleFunc("/item/", itemHandler(db))
http.HandleFunc("/submit/", submitHandler(db))
http.HandleFunc("/edit/", editHandler(db))
http.HandleFunc("/del/", delHandler(db))
http.HandleFunc("/vote/", voteHandler(db))
http.HandleFunc("/unvote/", unvoteHandler(db))
port := "8000"
if len(parms) > 1 {
port = parms[1]
}
fmt.Printf("Listening on %s...\n", port)
err = http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
log.Fatal(err)
}
func registerSqliteFuncs() {
rand.Seed(time.Now().UnixNano())
sql.Register("sqlite3_custom", &sqlite.SQLiteDriver{
ConnectHook: func(con *sqlite.SQLiteConn) error {
err := con.RegisterFunc("pow", pow, true)
if err != nil {
return err
}
err = con.RegisterFunc("randint", randint, false)
if err != nil {
return err
}
err = con.RegisterFunc("seconds_since_epoch", seconds_since_epoch, false)
if err != nil {
return err
}
err = con.RegisterFunc("seconds_since_time", seconds_since_time, false)
if err != nil {
return err
}
err = con.RegisterFunc("hours_since_time", hours_since_time, false)
if err != nil {
return err
}
err = con.RegisterFunc("calculate_points", calculate_points, false)
if err != nil {
return err
}
return nil
},
})
}
func pow(n int, p float64) float64 {
return math.Pow(float64(n), p)
}
func randint(n int) int {
return rand.Intn(n)
}
func seconds_since_epoch(dt string) int64 {
t, _ := time.Parse(time.RFC3339, dt)
return t.Unix()
}
func seconds_since_time(dt string) int64 {
return time.Now().Unix() - seconds_since_epoch(dt)
}
func hours_since_time(dt string) int64 {
return seconds_since_time(dt) / 60 / 60
}
func calculate_points(votes int, submitdt string, gravityf float64) float64 {
return float64(votes) / pow((int(hours_since_time(submitdt))+2), gravityf)
}
func parseArgs(args []string) (map[string]string, []string) {
switches := map[string]string{}
parms := []string{}
standaloneSwitches := []string{}
definitionSwitches := []string{"i"}
fNoMoreSwitches := false
curKey := ""
for _, arg := range args {
if fNoMoreSwitches {
// any arg after "--" is a standalone parameter
parms = append(parms, arg)
} else if arg == "--" {
// "--" means no more switches to come
fNoMoreSwitches = true
} else if strings.HasPrefix(arg, "--") {
switches[arg[2:]] = "y"
curKey = ""
} else if strings.HasPrefix(arg, "-") {
if listContains(definitionSwitches, arg[1:]) {
// -a "val"
curKey = arg[1:]
continue
}
for _, ch := range arg[1:] {
// -a, -b, -ab
sch := string(ch)
if listContains(standaloneSwitches, sch) {
switches[sch] = "y"
}
}
} else if curKey != "" {
switches[curKey] = arg
curKey = ""
} else {
// standalone parameter
parms = append(parms, arg)
}
}
return switches, parms
}
func listContains(ss []string, v string) bool {
for _, s := range ss {
if v == s {
return true
}
}
return false
}
func fileExists(file string) bool {
_, err := os.Stat(file)
if err != nil && os.IsNotExist(err) {
return false
}
return true
}
func idtoi(sid string) int64 {
if sid == "" {
return -1
}
n, err := strconv.Atoi(sid)
if err != nil {
return -1
}
return int64(n)
}
func atoi(s string) int {
if s == "" {
return -1
}
n, err := strconv.Atoi(s)
if err != nil {
return -1
}
return n
}
func atof(s string) float64 {
if s == "" {
return -1.0
}
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return -1.0
}
return f
}
func sqlstmt(db *sql.DB, s string) *sql.Stmt {
stmt, err := db.Prepare(s)
if err != nil {
log.Fatalf("db.Prepare() sql: '%s'\nerror: '%s'", s, err)
}
return stmt
}
func sqlexec(db *sql.DB, s string, pp ...interface{}) (sql.Result, error) {
stmt := sqlstmt(db, s)
defer stmt.Close()
return stmt.Exec(pp...)
}
func txstmt(tx *sql.Tx, s string) *sql.Stmt {
stmt, err := tx.Prepare(s)
if err != nil {
log.Fatalf("tx.Prepare() sql: '%s'\nerror: '%s'", s, err)
}
return stmt
}
func txexec(tx *sql.Tx, s string, pp ...interface{}) (sql.Result, error) {
stmt := txstmt(tx, s)
defer stmt.Close()
return stmt.Exec(pp...)
}
func parseMarkdown(s string) string {
s = strings.ReplaceAll(s, "%", "%%")
return string(github_flavored_markdown.Markdown([]byte(s)))
}
func parseTextLinks(body string) string {
sre := `\b(https?://\S+)`
re := regexp.MustCompile(sre)
body = re.ReplaceAllString(body, "<$1>")
return body
}
func parseIsoDate(dt string) string {
tdt, _ := time.Parse(time.RFC3339, dt)
return tdt.Format("2 Jan 2006")
}
func createAndInitTables(newfile string) {
if fileExists(newfile) {
s := fmt.Sprintf("File '%s' already exists. Can't initialize it.\n", newfile)
fmt.Printf(s)
os.Exit(1)
}
db, err := sql.Open("sqlite3", newfile)
if err != nil {
fmt.Printf("Error opening '%s' (%s)\n", newfile, err)
os.Exit(1)
}
ss := []string{
"BEGIN TRANSACTION;",
`CREATE TABLE entry (entry_id INTEGER PRIMARY KEY NOT NULL, thing INTEGER NOT NULL DEFAULT 0, title TEXT NOT NULL DEFAULT '', url TEXT NOT NULL DEFAULT '', body TEXT NOT NULL DEFAULT '', createdt TEXT NOT NULL, user_id INTEGER NOT NULL, parent_id INTEGER DEFAULT 0);`,
`CREATE TABLE user (user_id INTEGER PRIMARY KEY NOT NULL, username TEXT, password TEXT, active INTEGER NOT NULL, email TEXT, CONSTRAINT unique_username UNIQUE (username));`,
`INSERT INTO user (user_id, username, password, active, email) VALUES (1, 'admin', '', 1, 'admin@localhost');`,
`CREATE TABLE entryvote(entry_id INTEGER NOT NULL, user_id INTEGER, PRIMARY KEY (entry_id, user_id));`,
`CREATE TABLE entrytag(entry_id INTEGER NOT NULL, tag TEXT NOT NULL)`,
`CREATE TABLE cat(cat_id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL)`,
`CREATE TABLE entrycat(entry_id INTEGER NOT NULL, cat_id INTEGER NOT NULL)`,
`INSERT INTO cat (cat_id, name) VALUES (1, 'Main');`,
`CREATE TABLE site (site_id INTEGER PRIMARY KEY NOT NULL, title TEXT NOT NULL, desc TEXT NOT NULL, gravityf REAL NOT NULL);`,
`INSERT INTO site (site_id, title, desc, gravityf) VALUES (1, 'newsboard', '', 1.0);`,
`CREATE VIEW totalvotes
AS
SELECT entry_id, COUNT(*) AS votes FROM entryvote GROUP BY entry_id;`,
`INSERT INTO entry (entry_id, thing, title, url, body, createdt, user_id, parent_id) VALUES (1, 0, 'newsboard - a hackernews clone', 'https://github.com/robdelacruz/newsboard', '', strftime('%Y-%m-%dT%H:%M:%SZ', 'now'), 1, 0);`,
`INSERT INTO entrycat (entry_id, cat_id) VALUES (1, 1);`,
"COMMIT;",
}
for _, s := range ss {
_, err := sqlexec(db, s)
if err != nil {
log.Printf("DB error setting up newsboard db on '%s' (%s)\n", newfile, err)
os.Exit(1)
}
}
}
func getLoginUser(r *http.Request, db *sql.DB) *User {
var u User
u.Userid = -1
c, err := r.Cookie("userid")
if err != nil {
return &u
}
userid := idtoi(c.Value)
if userid == -1 {
return &u
}
return queryUser(db, userid)
}
func queryUser(db *sql.DB, userid int64) *User {
var u User
u.Userid = -1
s := "SELECT user_id, username, active, email FROM user WHERE user_id = ?"
row := db.QueryRow(s, userid)
err := row.Scan(&u.Userid, &u.Username, &u.Active, &u.Email)
if err == sql.ErrNoRows {
return &u
}
if err != nil {
fmt.Printf("queryUser() db error (%s)\n", err)
return &u
}
return &u
}
func queryUsername(db *sql.DB, username string) *User {
var u User
u.Userid = -1
s := "SELECT user_id, username, active, email FROM user WHERE username = ?"
row := db.QueryRow(s, username)
err := row.Scan(&u.Userid, &u.Username, &u.Active, &u.Email)
if err == sql.ErrNoRows {
return &u
}
if err != nil {
fmt.Printf("queryUser() db error (%s)\n", err)
return &u
}
return &u
}
func querySite(db *sql.DB) *Site {
var site Site
s := "SELECT title, desc, gravityf FROM site WHERE site_id = 1"
row := db.QueryRow(s)
err := row.Scan(&site.Title, &site.Desc, &site.Gravityf)
if err == sql.ErrNoRows {
// Site settings row not defined yet, just use default Site values.
site.Title = "newsboard"
site.Desc = ""
site.Gravityf = 1.5
} else if err != nil {
// DB error, log then use common site settings.
log.Printf("error reading site settings for siteid %d (%s)\n", 1, err)
site.Title = "newsboard"
site.Gravityf = 1.5
}
if site.Title == "" {
site.Title = "newsboard"
}
return &site
}
func queryCat(db *sql.DB, catid int64) *Cat {
var cat Cat
s := "SELECT cat_id, name FROM cat WHERE cat_id = ?"
row := db.QueryRow(s, catid)
err := row.Scan(&cat.Catid, &cat.Name)
if err == sql.ErrNoRows {
return nil
}
if err != nil {
fmt.Printf("queryCat() db error (%s)\n", err)
return nil
}
return &cat
}
func printPageHead(w io.Writer, jsurls []string, cssurls []string, site *Site) {
fmt.Fprintf(w, "<!DOCTYPE html>\n")
fmt.Fprintf(w, "<html>\n")
fmt.Fprintf(w, "<head>\n")
fmt.Fprintf(w, "<meta charset=\"utf-8\">\n")
fmt.Fprintf(w, "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n")
fmt.Fprintf(w, "<title>%s</title>\n", escape(site.Title))
fmt.Fprintf(w, "<link rel=\"stylesheet\" type=\"text/css\" href=\"/static/style.css\">\n")
fmt.Fprintf(w, "<link rel=\"stylesheet\" type=\"text/css\" href=\"/static/nbstyle.css\">\n")
for _, cssurl := range cssurls {
fmt.Fprintf(w, "<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\">\n", cssurl)
}
for _, jsurl := range jsurls {
fmt.Fprintf(w, "<script src=\"%s\" defer></script>\n", jsurl)
}
fmt.Fprintf(w, "</head>\n")
fmt.Fprintf(w, "<body>\n")
fmt.Fprintf(w, "<section class=\"body\">\n")
}
func printPageFoot(w io.Writer) {
fmt.Fprintf(w, "</section>\n")
fmt.Fprintf(w, "</body>\n")
fmt.Fprintf(w, "</html>\n")
}
func printPageNav(w http.ResponseWriter, db *sql.DB, login *User, site *Site, qq *QIndex) {
fmt.Fprintf(w, "<header class=\"masthead mb-sm\">\n")
// First row nav
fmt.Fprintf(w, "<nav class=\"navbar\">\n")
// Menu section (left part)
fmt.Fprintf(w, "<div>\n")
fmt.Fprintf(w, "<h1 class=\"heading\"><a href=\"/\">%s</a></h1>\n", escape(site.Title))
fmt.Fprintf(w, "<ul class=\"line-menu\">\n")
if qq != nil {
if qq.Latest != "" {
fmt.Fprintf(w, " <li><a href=\"/?username=%s&cat=%d&tag=%s&latest=1\">[latest]</a></li>\n", url.QueryEscape(qq.Username), qq.Cat, url.QueryEscape(qq.Tag))
} else {
fmt.Fprintf(w, " <li><a href=\"/?username=%s&cat=%d&tag=%s&latest=1\">latest</a></li>\n", url.QueryEscape(qq.Username), qq.Cat, url.QueryEscape(qq.Tag))
}
} else {
fmt.Fprintf(w, " <li><a href=\"/?latest=1\">latest</a></li>\n")
}
if login.Userid != -1 && login.Active {
fmt.Fprintf(w, " <li><a href=\"/submit/\">submit</a></li>\n")
}
fmt.Fprintf(w, "</ul>\n")
fmt.Fprintf(w, "</div>\n")
// User section (right part)
fmt.Fprintf(w, "<ul class=\"line-menu right\">\n")
if login.Userid == -1 {
fmt.Fprintf(w, "<li><a href=\"/login\">login</a></li>\n")
} else if login.Userid == ADMIN_ID {
fmt.Fprintf(w, "<li><a href=\"/adminsetup/\">%s</a></li>\n", escape(login.Username))
fmt.Fprintf(w, "<li><a href=\"/logout\">logout</a></li>\n")
} else {
fmt.Fprintf(w, "<li><a href=\"/usersetup/\">%s</a></li>\n", escape(login.Username))
fmt.Fprintf(w, "<li><a href=\"/logout\">logout</a></li>\n")
}
fmt.Fprintf(w, "</ul>\n")
fmt.Fprintf(w, "</nav>\n")
fmt.Fprintf(w, "</header>\n")
}
func isCorrectPassword(inputPassword, hashedpwd string) bool {
if hashedpwd == "" && inputPassword == "" {
return true
}
err := bcrypt.CompareHashAndPassword([]byte(hashedpwd), []byte(inputPassword))
if err != nil {
return false
}
return true
}
func hashPassword(pwd string) string {
hashedpwd, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
if err != nil {
panic(err)
}
return string(hashedpwd)
}
func loginUser(w http.ResponseWriter, userid int64) {
suserid := fmt.Sprintf("%d", userid)
c := http.Cookie{
Name: "userid",
Value: suserid,
Path: "/",
HttpOnly: true,
Expires: time.Now().Add(daysDuration(400)),
}
http.SetCookie(w, &c)
}
func daysDuration(ndays int) time.Duration {
return time.Hour * 24 * time.Duration(ndays)
}
func unescapeUrl(qurl string) string {
returl := "/"
if qurl != "" {
returl, _ = url.QueryUnescape(qurl)
}
return returl
}
func escape(s string) string {
return html.EscapeString(s)
}
func normalizeTitle(title string) string {
if len(title) > 256 {
return title[:256]
}
return title
}
func loginHandler(db *sql.DB) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
var errmsg string
var f struct{ username, password string }
login := getLoginUser(r, db)
qfrom := r.FormValue("from")
if r.Method == "POST" {
f.username = r.FormValue("username")
f.password = r.FormValue("password")
s := "SELECT user_id, password, active FROM user WHERE username = ?"
row := db.QueryRow(s, f.username, f.password)
var userid int64
var hashedpwd string
var active int
err := row.Scan(&userid, &hashedpwd, &active)
for {
if err == sql.ErrNoRows {
errmsg = "Incorrect username or password"
break
}
if err != nil {
errmsg = "A problem occured. Please try again."
break
}
if !isCorrectPassword(f.password, hashedpwd) {
errmsg = "Incorrect username or password"
break
}
if active == 0 {
errmsg = fmt.Sprintf("User '%s' is inactive.", f.username)
break
}
loginUser(w, userid)
http.Redirect(w, r, unescapeUrl(qfrom), http.StatusSeeOther)
return
}
}
w.Header().Set("Content-Type", "text/html")
site := querySite(db)
printPageHead(w, nil, nil, site)
printPageNav(w, db, login, site, nil)
fmt.Fprintf(w, "<section class=\"main\">\n")
fmt.Fprintf(w, "<form class=\"simpleform\" action=\"/login/?from=%s\" method=\"post\">\n", url.QueryEscape(qfrom))
fmt.Fprintf(w, "<h1 class=\"heading\">Login</h1>")
if errmsg != "" {
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<p class=\"error\">%s</p>\n", errmsg)
fmt.Fprintf(w, "</div>\n")
}
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<label for=\"username\">username</label>\n")
fmt.Fprintf(w, "<input id=\"username\" name=\"username\" type=\"text\" size=\"20\" value=\"%s\">\n", f.username)
fmt.Fprintf(w, "</div>\n")
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<label for=\"password\">password</label>\n")
fmt.Fprintf(w, "<input id=\"password\" name=\"password\" type=\"password\" size=\"20\" value=\"%s\">\n", f.password)
fmt.Fprintf(w, "</div>\n")
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<button class=\"submit\">login</button>\n")
fmt.Fprintf(w, "</div>\n")
fmt.Fprintf(w, "</form>\n")
fmt.Fprintf(w, "<p class=\"mt-xl\"><a href=\"/createaccount/?from=%s\">Create New Account</a></p>\n", url.QueryEscape(qfrom))
fmt.Fprintf(w, "</section>\n")
printPageFoot(w)
}
}
func logoutHandler(db *sql.DB) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
c := http.Cookie{
Name: "userid",
Value: "",
Path: "/",
HttpOnly: true,
MaxAge: 0,
}
http.SetCookie(w, &c)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
}
func isUsernameExists(db *sql.DB, username string) bool {
s := "SELECT user_id FROM user WHERE username = ?"
row := db.QueryRow(s, username)
var userid int64
err := row.Scan(&userid)
if err == sql.ErrNoRows {
return false
}
if err != nil {
return false
}
return true
}
func createaccountHandler(db *sql.DB) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
var errmsg string
var f struct{ username, email, password, password2 string }
login := getLoginUser(r, db)
qfrom := r.FormValue("from")
if r.Method == "POST" {
f.username = r.FormValue("username")
f.email = r.FormValue("email")
f.password = r.FormValue("password")
f.password2 = r.FormValue("password2")
for {
if f.password != f.password2 {
errmsg = "re-entered password doesn't match"
f.password = ""
f.password2 = ""
break
}
if isUsernameExists(db, f.username) {
errmsg = fmt.Sprintf("username '%s' already exists", f.username)
break
}
hashedPassword := hashPassword(f.password)
s := "INSERT INTO user (username, password, active, email) VALUES (?, ?, ?, ?);"
result, err := sqlexec(db, s, f.username, hashedPassword, 1, f.email)
if err != nil {
log.Printf("DB error creating user: %s\n", err)
errmsg = "A problem occured. Please try again."
break
}
newid, err := result.LastInsertId()
if err == nil {
loginUser(w, newid)
} else {
// DB doesn't support getting newly added userid, so login manually.
qfrom = "/login/"
}
http.Redirect(w, r, unescapeUrl(qfrom), http.StatusSeeOther)
return
}
}
w.Header().Set("Content-Type", "text/html")
site := querySite(db)
printPageHead(w, nil, nil, site)
printPageNav(w, db, login, site, nil)
fmt.Fprintf(w, "<section class=\"main\">\n")
fmt.Fprintf(w, "<form class=\"simpleform\" action=\"/createaccount/?from=%s\" method=\"post\">\n", url.QueryEscape(qfrom))
fmt.Fprintf(w, "<h1 class=\"heading\">Create Account</h1>")
if errmsg != "" {
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<p class=\"error\">%s</p>\n", errmsg)
fmt.Fprintf(w, "</div>\n")
}
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<label for=\"username\">username</label>\n")
fmt.Fprintf(w, "<input id=\"username\" name=\"username\" type=\"text\" size=\"20\" maxlength=\"20\" value=\"%s\">\n", f.username)
fmt.Fprintf(w, "</div>\n")
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<label for=\"email\">email</label>\n")
fmt.Fprintf(w, "<input id=\"email\" name=\"email\" type=\"email\" size=\"20\" value=\"%s\">\n", f.email)
fmt.Fprintf(w, "</div>\n")
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<label for=\"password\">password</label>\n")
fmt.Fprintf(w, "<input id=\"password\" name=\"password\" type=\"password\" size=\"20\" value=\"%s\">\n", f.password)
fmt.Fprintf(w, "</div>\n")
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<label for=\"password2\">re-enter password</label>\n")
fmt.Fprintf(w, "<input id=\"password2\" name=\"password2\" type=\"password\" size=\"20\" value=\"%s\">\n", f.password2)
fmt.Fprintf(w, "</div>\n")
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<button class=\"submit\">create account</button>\n")
fmt.Fprintf(w, "</div>\n")
fmt.Fprintf(w, "</form>\n")
fmt.Fprintf(w, "</section>\n")
printPageFoot(w)
}
}
func adminsetupHandler(db *sql.DB) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
var errmsg string
var f struct {
title string
gravityf float64
}
login := getLoginUser(r, db)
if login.Userid != ADMIN_ID {
http.Error(w, "admin user required", 401)
return
}
site := querySite(db)
f.title = site.Title
f.gravityf = site.Gravityf
if f.gravityf < 0 {
f.gravityf = 0.0
}
qfrom := r.FormValue("from")
if r.Method == "POST" {
for {
f.title = strings.TrimSpace(r.FormValue("title"))
f.gravityf = atof(r.FormValue("gravityf"))
if f.title == "" {
errmsg = "Enter a site title"
break
}
if f.gravityf < 0 {
errmsg = "Enter a gravity factor (0.0 and above)"
break
}
s := "INSERT OR REPLACE INTO site (site_id, title, desc, gravityf) VALUES (1, ?, ?, ?)"
_, err := sqlexec(db, s, f.title, "", f.gravityf)
if err != nil {
fmt.Printf("adminsetup site update DB error (%s)\n", err)
errmsg = "A problem occured. Please try again."
break
}
http.Redirect(w, r, unescapeUrl(qfrom), http.StatusSeeOther)
return
}
}
w.Header().Set("Content-Type", "text/html")
printPageHead(w, nil, nil, site)
printPageNav(w, db, login, site, nil)
fmt.Fprintf(w, "<section class=\"main\">\n")
fmt.Fprintf(w, "<form class=\"simpleform mb-xl\" action=\"/adminsetup/?from=%s\" method=\"post\">\n", url.QueryEscape(qfrom))
fmt.Fprintf(w, "<h1 class=\"heading\">Site Settings</h1>")
if errmsg != "" {
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<p class=\"error\">%s</p>\n", errmsg)
fmt.Fprintf(w, "</div>\n")
}
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<label for=\"title\">site title</label>\n")
fmt.Fprintf(w, "<input id=\"title\" name=\"title\" type=\"text\" size=\"30\" maxlength=\"50\" value=\"%s\">\n", escape(f.title))
fmt.Fprintf(w, "</div>\n")
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<label for=\"gravityf\">gravity factor</label>\n")
if f.gravityf >= 0 {
fmt.Fprintf(w, "<input id=\"gravityf\" name=\"gravityf\" type=\"number\" step=\"0.001\" min=\"0\" size=\"5\" value=\"%.2f\">\n", f.gravityf)
} else {
fmt.Fprintf(w, "<input id=\"gravityf\" name=\"gravityf\" type=\"number\" step=\"0.001\" min=\"0\" size=\"5\" value=\"\">\n")
}
fmt.Fprintf(w, "<p class=\"text-sm text-fade-2 text-italic mt-xs\">\n")
fmt.Fprintf(w, "points = num_votes / (hours_since_submission + 2) ^ gravity_factor.<br>The gravity_factor determines how quickly points decrease as time passes.\n")
fmt.Fprintf(w, "</p>\n")
fmt.Fprintf(w, "</div>\n")
fmt.Fprintf(w, "<div class=\"control\">\n")
fmt.Fprintf(w, "<button class=\"submit\">submit</button>\n")
fmt.Fprintf(w, "</div>\n")
fmt.Fprintf(w, "</form>\n")
// Categories
fmt.Fprintf(w, "<h1 class=\"heading mb-sm\">Categories</h1>\n")
fmt.Fprintf(w, "<ul class=\"vertical-list mb-xl\">\n")
fmt.Fprintf(w, " <li><a class=\"text-fade-2 text-xs\" href=\"/createcat/?from=%s\">create new category</a></li>\n", url.QueryEscape("/adminsetup/"))
var cat Cat
s := "SELECT cat_id, name FROM cat ORDER BY cat_id"
rows, _ := db.Query(s)
for rows.Next() {
rows.Scan(&cat.Catid, &cat.Name)
fmt.Fprintf(w, "<li>\n")
fmt.Fprintf(w, " <div>%s</div>\n", escape(cat.Name))
fmt.Fprintf(w, " <ul class=\"line-menu text-fade-2 text-xs\">\n")
fmt.Fprintf(w, " <li><a href=\"/editcat?catid=%d&from=%s\">edit</a></li>\n", cat.Catid, url.QueryEscape("/adminsetup/"))
if cat.Catid != 1 {
fmt.Fprintf(w, " <li><a href=\"/delcat?catid=%d&from=%s\">delete</a></li>\n", cat.Catid, url.QueryEscape("/adminsetup/"))
}
fmt.Fprintf(w, " </ul>\n")
fmt.Fprintf(w, "</li>\n")
}
fmt.Fprintf(w, "</ul>\n")
// Users
fmt.Fprintf(w, "<h1 class=\"heading mb-sm\">Users</h1>\n")
s = "SELECT user_id, username, active, email FROM user ORDER BY username"
rows, err := db.Query(s)
if handleDbErr(w, err, "adminsetuphandler") {
return
}
var u User
fmt.Fprintf(w, "<ul class=\"vertical-list mb-xl\">\n")
for rows.Next() {
rows.Scan(&u.Userid, &u.Username, &u.Active, &u.Email)
fmt.Fprintf(w, "<li>\n")
if u.Active {
fmt.Fprintf(w, "<div>%s</div>\n", escape(u.Username))
} else {
fmt.Fprintf(w, "<div class=\"text-fade-2\">(%s)</div>\n", escape(u.Username))
}
fmt.Fprintf(w, "<ul class=\"line-menu text-fade-2 text-xs\">\n")
fmt.Fprintf(w, " <li><a href=\"/edituser?userid=%d&from=%s\">edit</a>\n", u.Userid, url.QueryEscape("/adminsetup/"))
if u.Userid != ADMIN_ID {
if u.Active {
fmt.Fprintf(w, " <li><a href=\"/activateuser?userid=%d&setactive=0&from=%s\">deactivate</a>\n", u.Userid, url.QueryEscape("/adminsetup/"))
} else {
fmt.Fprintf(w, " <li><a href=\"/activateuser?userid=%d&setactive=1&from=%s\">activate</a>\n", u.Userid, url.QueryEscape("/adminsetup/"))
}
}
fmt.Fprintf(w, "</ul>\n")
fmt.Fprintf(w, "</li>\n")
}
fmt.Fprintf(w, "</ul>\n")
fmt.Fprintf(w, "</section>\n")
printPageFoot(w)
}
}
func usersetupHandler(db *sql.DB) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
login := getLoginUser(r, db)
if !validateLogin(w, login) {
return
}
w.Header().Set("Content-Type", "text/html")
site := querySite(db)
printPageHead(w, nil, nil, site)
printPageNav(w, db, login, site, nil)
fmt.Fprintf(w, "<section class=\"main\">\n")
fmt.Fprintf(w, "<p class=\"\"><a href=\"/edituser?userid=%d&from=%s\">Edit Account</a></p>\n", login.Userid, url.QueryEscape("/usersetup/"))
fmt.Fprintf(w, "<p class=\"mt-base\"><a href=\"/edituser?userid=%d&setpwd=1&from=%s\">Set Password</a></p>\n", login.Userid, url.QueryEscape("/usersetup/"))
fmt.Fprintf(w, "</section>\n")
printPageFoot(w)
}
}
func edituserHandler(db *sql.DB) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
var errmsg string
var f struct{ username, email, password, password2 string }
qfrom := r.FormValue("from")
qsetpwd := r.FormValue("setpwd") // ?setpwd=1 to prompt for new password
quserid := idtoi(r.FormValue("userid"))
if quserid == -1 {
log.Printf("edit user: no userid\n")
http.Error(w, "missing userid parameter", 401)
return
}
login := getLoginUser(r, db)
if login.Userid != ADMIN_ID && login.Userid != quserid {
log.Printf("edit user: admin or self user not logged in\n")
http.Error(w, "admin or self user required", 401)
return
}
u := queryUser(db, quserid)
if u.Userid == -1 {
log.Printf("edit user: userid %d doesn't exist\n", quserid)
http.Error(w, "user doesn't exist", 401)
return
}
f.username = u.Username
f.email = u.Email
if r.Method == "POST" {
f.username = strings.TrimSpace(r.FormValue("username"))
f.email = r.FormValue("email")
for {
// If username was changed,
// make sure the new username hasn't been taken yet.
if f.username != u.Username && isUsernameExists(db, f.username) {
errmsg = fmt.Sprintf("username '%s' already exists", f.username)
break