-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
236 lines (187 loc) · 5.41 KB
/
handlers.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
package main
import (
"html/template"
"net/http"
"runtime"
"github.com/HEEV/WebServer/api"
"github.com/HEEV/WebServer/chat"
"github.com/gorilla/sessions"
log "github.com/sirupsen/logrus"
)
var (
key = []byte("4KI7AXTDH4VACRRK")
store = sessions.NewCookieStore(key)
)
// InitializeRoutes initializes all the endpoints for the server
func initializeRoutes(hub *chat.Hub) {
log.Info("Initializing routes...")
// Handle all HTTP requests
http.HandleFunc("/", httpHandler)
// Handle websocket connections
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
chat.ServeWs(hub, w, r)
})
// Handle static file requests for javascript
http.Handle("/static/js/",
http.StripPrefix("/static/js/",
http.FileServer(http.Dir("./static/js"))))
// Handle static file requests for CSS
http.Handle("/static/css/",
http.StripPrefix("/static/css/",
http.FileServer(http.Dir("./static/css"))))
// Handle static file requests for images
http.Handle("/static/img/",
http.StripPrefix("/static/img/",
http.FileServer(http.Dir("./static/img"))))
// Handle API endpoint requests
http.HandleFunc("/API/", apiHandler)
// Handle basic authentication
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/auth", authHandler)
}
// httpHandler handles all HTTP requests sent to the server
func httpHandler(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/":
rootHandler(w, r)
break
case "/graph":
graphHandler(w, r)
break
default:
http.Error(w, "Not found", http.StatusNotFound)
return
}
}
// rootHandler handles requests to the server root
func rootHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Validate authentication
// Get storage cookie store
session, _ := store.Get(r, "CUSupermileage")
// Get authenticated session value from cookie
if auth, ok := session.Values["authenticated"].(bool); !auth || !ok {
// Require login
loginHandler(w, r)
return
}
// Values that will be used in the template
vals := map[string]string{
"version": runtime.Version(),
}
// Parse the root page template
t, _ := template.ParseFiles("templates/root.html")
// Respond with the template filled with the values
t.Execute(w, vals)
}
// graphHandler handles requests to the /graph page
func graphHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Values that will be used in the template
vals := map[string]string{
"version": runtime.Version(),
}
// Parse the root page template
t, _ := template.ParseFiles("templates/graph.html")
// Respond with the template filled with the values
t.Execute(w, vals)
}
// apiHandler provides access to data stored in the DB
func apiHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" && r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Response message string
resp := ""
var err error
switch r.URL.Path {
case "/API/carName":
resp, err = api.CarNameHandler(r)
break
case "/API/csv":
resp, _, err = api.CSVHandler(r)
break
case "/API/graph":
resp, err = api.GraphHandler(r)
break
case "/API/latestRunRow":
resp, err = api.LatestRunHandler(r)
break
// NOTE: This endpoint is disabled until more clarification is gained on
// how it is supposed to operate
// case "/API/runIds":
// resp, err = api.RunIdsHandler(r)
// break
default:
w.WriteHeader(http.StatusNotFound)
return
}
if err != nil {
// Default HTTP error code
errCode := http.StatusInternalServerError
// Specifically invalid method
switch err.Error() {
case "Method not allowed":
errCode = http.StatusMethodNotAllowed
break
case "Not found":
errCode = http.StatusNoContent
break
}
// Write HTTP status code
w.WriteHeader(errCode)
// Write error message
w.Write([]byte(err.Error()))
return
}
// No errors!
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte(resp))
}
// loginHandler handles requests to the login page
func loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed "+r.Method, http.StatusMethodNotAllowed)
return
}
// Values that will be used in the template
vals := map[string]string{}
// Parse the root page template
t, _ := template.ParseFiles("templates/login.html")
// Respond with the template filled with the values
t.Execute(w, vals)
}
// authHandler handles authentication
func authHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Get storage cookie store
session, _ := store.Get(r, "CUSupermileage")
// Get authenticated session value from cookie
if auth, ok := session.Values["authenticated"].(bool); ok && auth {
// Already authorized, no need to do anything further
return
}
// Get values from request
username := r.PostFormValue("username")
password := r.PostFormValue("password")
// Simple password validation
if username != "cedarville" || password != "bebold" {
http.Error(w, "Invalid username or password!", http.StatusBadRequest)
return
}
// Passed validation, set session
session.Values["authenticated"] = true
session.Save(r, w)
log.Info("Logged in!")
http.Redirect(w, r, "/", http.StatusFound)
}