-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
184 lines (157 loc) · 4.46 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
package main
import (
"errors"
"flag"
"fmt"
"log"
"net/http"
"strings"
"text/template"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"golang.org/x/crypto/bcrypt"
"github.com/saaste/shopping-list/shopping_list"
"github.com/saaste/shopping-list/websocket"
)
var requiredPassword string
func main() {
port := flag.String("port", "8000", "Port")
flag.Parse()
appConfig, err := shopping_list.LoadAppConfig()
if err != nil {
log.Fatalf("failed to load app config: %v", err)
}
requiredPassword = appConfig.Password
hub := websocket.NewHub()
go hub.Run()
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Get("/", handleRoot)
r.Get("/login", handleLogin)
r.Post("/login", handleLogin)
r.Get("/logout", handleLogout)
r.Get("/ws", func(w http.ResponseWriter, r *http.Request) {
if !appConfig.IsValidOrigin(r) || !isValidAuthCookie(r) {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
websocket.ServeWs(hub, w, r)
})
fileServer(r, "/static", http.Dir("ui/static"))
err = http.ListenAndServe(fmt.Sprintf(":%s", *port), r)
if errors.Is(err, http.ErrServerClosed) {
log.Println("Server closed")
} else if err != nil {
log.Fatalf("Error starting server: %v\n", err)
}
}
func handleRoot(w http.ResponseWriter, r *http.Request) {
isAuthenticated := isValidAuthCookie(r)
if !isAuthenticated {
http.Redirect(w, r, "/login", http.StatusMovedPermanently)
return
}
t, err := template.ParseFiles("ui/templates/base.html", "ui/templates/home.html")
if err != nil {
log.Printf("Failed to parse home templates: %s", err)
http.Error(w, "Internal Server Error", 500)
}
err = t.ExecuteTemplate(w, "base", nil)
if err != nil {
log.Printf("Failed to execute home template: %s", err)
http.Error(w, "Internal Server Error", 500)
}
}
func handleLogin(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Method: %s\n", r.Method)
if r.Method == "POST" {
r.ParseForm()
password := r.FormValue("password")
if password == requiredPassword {
setAuthCookie(w)
http.Redirect(w, r, "/", http.StatusMovedPermanently)
return
}
}
t, err := template.ParseFiles("ui/templates/base.html", "ui/templates/login.html")
if err != nil {
log.Printf("Failed to parse login templates: %s", err)
http.Error(w, "Internal Server Error", 500)
}
err = t.ExecuteTemplate(w, "base", nil)
if err != nil {
log.Printf("Failed to execute login template: %s", err)
http.Error(w, "Internal Server Error", 500)
}
}
func handleLogout(w http.ResponseWriter, r *http.Request) {
cookie := http.Cookie{
Name: "auth",
Value: "",
Path: "/",
MaxAge: 0,
Expires: time.Unix(0, 0),
HttpOnly: true,
Secure: false,
SameSite: http.SameSiteLaxMode,
}
http.SetCookie(w, &cookie)
http.Redirect(w, r, "/login", http.StatusMovedPermanently)
}
func fileServer(r chi.Router, path string, root http.FileSystem) {
if strings.ContainsAny(path, "{}*") {
panic("FileServer does not permit any URL parameters.")
}
if path != "/" && path[len(path)-1] != '/' {
r.Get(path, http.RedirectHandler(path+"/", http.StatusMovedPermanently).ServeHTTP)
path += "/"
}
path += "*"
r.Get(path, func(w http.ResponseWriter, r *http.Request) {
rctx := chi.RouteContext(r.Context())
pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*")
fs := http.StripPrefix(pathPrefix, http.FileServer(root))
fs.ServeHTTP(w, r)
})
}
func isValidAuthCookie(r *http.Request) bool {
cookie, err := r.Cookie("auth")
if err != nil {
switch {
case errors.Is(err, http.ErrNoCookie):
log.Printf("Warning: auth cookie not found.\n")
default:
log.Printf("Warning: failed to get auth cookie: %v", err)
}
return false
}
isValid := isValidPassword(requiredPassword, cookie.Value)
if !isValid {
fmt.Printf("Warning: invalid auth cookie from %s: %s", r.RemoteAddr, cookie.Value)
}
return cookie != nil && isValid
}
func setAuthCookie(w http.ResponseWriter) {
cookie := http.Cookie{
Name: "auth",
Value: hashPassword(requiredPassword),
Path: "/",
MaxAge: 3600 * 24 * 365 * 5,
HttpOnly: true,
Secure: false,
SameSite: http.SameSiteLaxMode,
}
http.SetCookie(w, &cookie)
}
func hashPassword(plainText string) string {
bytes, err := bcrypt.GenerateFromPassword([]byte(plainText), 4)
if err != nil {
log.Fatalf("failed to encrypt password: %v", err)
}
return string(bytes)
}
func isValidPassword(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}