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
|
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"github.com/jackc/pgx/v5"
)
func handle_index(w http.ResponseWriter, req *http.Request) {
session_cookie, err := req.Cookie("session")
if errors.Is(err, http.ErrNoCookie) {
err = tmpl.ExecuteTemplate(
w,
"index_login",
map[string]string{
"authUrl": generate_authorization_url(),
},
)
if err != nil {
log.Println(err)
return
}
return
} else if err != nil {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(400)
w.Write([]byte(fmt.Sprintf(
"Error\n" +
"Unable to check cookie.",
)))
return
}
var userid string
var expr int
err = db.QueryRow(context.Background(), "SELECT userid, expr FROM sessions WHERE cookie = $1", session_cookie.Value).Scan(&userid, &expr)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
err = tmpl.ExecuteTemplate(
w,
"index_login",
map[string]interface{}{
"authUrl": generate_authorization_url(),
"notes": []string{"Technically you have a session cookie, but it seems invalid."},
},
)
if err != nil {
log.Println(err)
return
}
return
} else {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(500)
w.Write([]byte(fmt.Sprintf(
"Error\nUnexpected database error.\n%s\n",
err,
)))
return
}
}
var name string
err = db.QueryRow(context.Background(), "SELECT name FROM users WHERE id = $1", userid).Scan(&name)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(500)
w.Write([]byte(fmt.Sprintf(
"Error\nYour user doesn't exist. (This looks like a data integrity error.)\n%s\n",
err,
)))
return
} else {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(500)
w.Write([]byte(fmt.Sprintf(
"Error\nUnexpected database error.\n%s\n",
err,
)))
return
}
}
err = tmpl.ExecuteTemplate(
w,
"index",
map[string]interface{}{
"user": map[string]interface{}{
"Name": name,
},
},
)
if err != nil {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(500)
w.Write([]byte(fmt.Sprintf(
"Error\nUnexpected template error.\n%s\n",
err,
)))
}
}
|