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
|
package main
import (
"errors"
"fmt"
"log"
"net/http"
"net/url"
"time"
jwt "github.com/golang-jwt/jwt/v4"
"riedstra.dev/mitch/go-website/page"
"riedstra.dev/mitch/go-website/users"
)
var ErrInvalidJWTToken = errors.New("invalid JWT token")
func (a *App) Err5xx(w http.ResponseWriter, r *http.Request,
statusCode int, title, desc string) {
page.Render5xx(w, r, map[string]interface{}{
"Error": title,
"Description": desc,
}, statusCode)
}
func (a *App) Err500Default(w http.ResponseWriter, r *http.Request) {
a.Err5xx(w, r, http.StatusInternalServerError, "Internal server error",
"Internal server error.")
}
func (a *App) LogoutHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: "Auth",
HttpOnly: a.auth.HTTPOnly,
SameSite: a.auth.SameSiteStrict,
Secure: a.auth.Secure,
Value: "logout",
Expires: time.Now().Add(time.Second),
})
http.Redirect(w, r, "/", http.StatusFound)
})
}
func (a *App) LoginHandler() http.Handler { //nolint
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
loggedIn := a.IsLoggedIn(r)
next, _ := url.Parse(r.URL.Query().Get("next"))
if r.Method == "GET" && !loggedIn {
page.RenderForPath(w, r, "login")
return
}
if r.Method == "GET" && loggedIn {
if next.Path != "" {
http.Redirect(w, r, next.Path, http.StatusFound)
return
}
http.Redirect(w, r, "/dashboard", http.StatusFound)
return
}
if r.Method != "POST" {
a.Err500Default(w, r)
return
}
username := r.FormValue("username")
password := r.FormValue("password")
var (
err error
u *users.SiteUser
found = false
)
for _, u = range a.auth.Users {
if u.Username == username {
err = u.CheckPassword(password)
found = true
}
}
if err != nil || !found {
page.Render(w, r, "login", map[string]interface{}{
"Error": "Invalid username or password",
"Username": username,
}, http.StatusUnauthorized)
return
}
token := jwt.NewWithClaims(jwt.SigningMethodHS512, &jwt.StandardClaims{
ExpiresAt: time.Now().Add(
time.Hour * time.Duration(a.auth.LoginHours)).Unix(),
Id: u.Username,
})
ss, err := token.SignedString([]byte(a.auth.TokenKey))
if err != nil {
log.Println("login: encountered while setting up JWT: ", err)
a.Err500Default(w, r)
return
}
http.SetCookie(w, &http.Cookie{
Name: "Auth",
HttpOnly: a.auth.HTTPOnly,
SameSite: a.auth.SameSiteStrict,
Secure: a.auth.Secure,
Value: ss,
})
http.Redirect(w, r, "/login", http.StatusFound)
})
}
func (a *App) IsLoggedIn(r *http.Request) bool {
_, err := a.GetAuthToken(r)
if err != nil {
log.Printf("%s IsLoggedIn: false", r.URL.Path)
return false
}
log.Printf("%s IsLoggedIn: true", r.URL.Path)
return true
}
func (a *App) GetAuthToken(r *http.Request) (*jwt.Token, error) {
c, err := r.Cookie("Auth")
if err != nil {
return nil, fmt.Errorf("getting auth token: %w", err)
}
token, err := jwt.Parse(c.Value,
func(token *jwt.Token) (interface{}, error) {
return []byte(a.auth.TokenKey), nil
},
)
if err != nil {
return nil, fmt.Errorf("while parsing jwt %w", err)
}
if !token.Valid {
return token, ErrInvalidJWTToken
}
return token, nil
}
func (a *App) RequiresLogin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !a.IsLoggedIn(r) {
log.Printf("Unauthorized request %s %s", r.Method, r.URL.Path)
page.Render(w, r, "login", map[string]interface{}{
"Error": "You must login to view this page",
}, http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
|