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
|
package main
import (
"context"
"database/sql"
"errors"
"log"
"net/http"
"net/url"
"golang.org/x/crypto/bcrypt"
)
type userContextKey struct{}
const (
sessionDuration = 86400 * 7 // 7 days
loginQueryMarker = "next"
)
func RequireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s := session(r)
if !s.s.IsNew && s.Authenticated {
u, err := Q.GetUserById(r.Context(), s.UserID)
if err == nil {
// authenticated --> done
ctx := context.WithValue(r.Context(), userContextKey{}, u.ID)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
s.Invalidate()
s.Save(w, r)
}
// redirect to login with next-param
v := url.Values{}
v.Set(loginQueryMarker, r.URL.Path)
redirPath := "/login?" + v.Encode()
http.Redirect(w, r, redirPath, http.StatusFound)
})
}
func checkLogin(ctx context.Context, user User) (bool, int32) {
dbUser, err := Q.GetUserByName(ctx, user.Name)
if err == nil {
hash := []byte(dbUser.Pwd)
pwd := []byte(user.Password)
if bcrypt.CompareHashAndPassword(hash, pwd) != nil {
return false, 0
}
} else if errors.Is(err, sql.ErrNoRows) {
return false, 0
} else {
log.Panicf("Could not load user '%s': %v", user.Name, err)
}
return true, dbUser.ID
}
func handleLogin(w http.ResponseWriter, r *http.Request) {
u := User{}
parseForm(r, &u)
ok, userId := checkLogin(r.Context(), u)
if !ok {
u.Errors = []error{fieldError{"Password", "Invalid"}}
showLoginPage(w, u)
return
}
s := session(r)
if u.RememberMe {
s.MaxAge(sessionDuration) // 1 week
} else {
s.MaxAge(0)
}
s.UserID = userId
s.Authenticated = true
s.Save(w, r)
// redirect
next := r.URL.Query().Get(loginQueryMarker)
if next == "" {
next = "/"
}
http.Redirect(w, r, next, http.StatusFound)
}
func handleLogout() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s := session(r)
s.Invalidate()
s.Save(w, r)
http.Redirect(w, r, "/", http.StatusFound)
}
}
type User struct {
Name string `form:"options=required,autofocus"`
Password string `form:"type=password;options=required"`
RememberMe bool `form:"type=checkbox;value=y;options=checked"`
Errors []error `form:"-"`
Csrf
}
func showLoginPage(w http.ResponseWriter, u User) {
showTemplate(w, "login", u)
}
func loginPage() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if session(r).Authenticated {
http.Redirect(w, r, "/", http.StatusFound)
}
u := User{}
u.SetCsrfField(r)
showLoginPage(w, u)
}
}
func userId(r *http.Request) int32 {
return r.Context().Value(userContextKey{}).(int32)
}
|