This repository has been archived by the owner on Oct 6, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserv.go
375 lines (318 loc) · 10.7 KB
/
webserv.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
//--------------------------------------------
// web/webserv.go
//
// Handles serving and authenticating for all
// the webpages.
//
// All the handler functions are declared in
// this file.
//--------------------------------------------
package web
import (
"crypto/sha256"
"html/template"
"net/http"
"strconv"
"strings"
"time"
auth "github.com/darwinfroese/networkobserver/pkg/auth"
"github.com/darwinfroese/networkobserver/pkg/configuration"
logger "github.com/darwinfroese/networkobserver/pkg/logging"
reporter "github.com/darwinfroese/networkobserver/pkg/reporting"
settings "github.com/darwinfroese/networkobserver/pkg/settings"
tools "github.com/darwinfroese/networkobserver/pkg/tools"
)
//--------------------------------------------
// Variables
//--------------------------------------------
var errMsg = ""
var loc = settings.AppLocation
//--------------------------------------------
// Structs for Pages
//--------------------------------------------
type configPage struct {
DeviceIP string
Port string
InternalAddr string
ExternalAddr string
ExternalURL string
SpeedFileLoc string
ReportFileLoc string
PingDelay string
SpeedDelay string
}
type testPage struct {
ErrorMessage
SpeedTestFileLocation string
PingDelay string
SpeedTestDelay string
}
type createAccount struct {
ErrorMessage
Username string
}
// ErrorMessage - contains an error message to display to the user
type ErrorMessage struct {
Msg string
}
// Root - All URLs default to this function
func Root(w http.ResponseWriter, r *http.Request) {
valid := auth.CheckSessionID(r)
if valid {
http.Redirect(w, r, "/dashboard", http.StatusFound)
} else {
servePageStatic(w, r, loc+"/html/login.html")
}
}
// Dashboard - Handles URLs referencing dashboard
func Dashboard(w http.ResponseWriter, r *http.Request) {
valid := auth.CheckSessionID(r)
if valid {
servePageStatic(w, r, loc+"/html/dashboard.html")
} else {
http.Redirect(w, r, "/", http.StatusFound)
}
}
// CheckLogin - Validates a login attempt or redirects the user to
// an error page which redirects them to "Root"
func CheckLogin(w http.ResponseWriter, r *http.Request) {
uname := r.FormValue("username")
pword := r.FormValue("password")
// Authenticate user credentials
// Hash password
hash := sha256.Sum256([]byte(pword))
authenticated := auth.CheckCredentials(uname, hash)
if authenticated == true {
logger.WriteString("User \"" + uname + "\" authenticated successfully.")
auth.SetSessionID(w)
http.Redirect(w, r, "/dashboard", http.StatusFound)
} else {
logger.WriteString("User \"" + uname + "\" did not authenticate successfully.")
servePageStatic(w, r, loc+"/html/error.html")
}
}
// CreateAccount - Create a new account by comparing both of the passwords
// entered and then hashing and storing the password
func CreateAccount(w http.ResponseWriter, r *http.Request) {
servePageStatic(w, r, loc+"/html/createaccount.html")
}
// HandleAccount - Serve the webpage for creating an account
func HandleAccount(w http.ResponseWriter, r *http.Request) {
un := r.FormValue("username")
pw := r.FormValue("password")
pwv := r.FormValue("password-verify")
if auth.UsernameInUse(un) {
ca := createAccount{}
ca.Msg = "The username " + un + " is currently in use."
ca.Username = ""
servePageDynamic(w, r, loc+"/html/createaccount.html", ca)
} else if un == "" {
ca := createAccount{}
ca.Msg = "You must enter a username."
ca.Username = ""
servePageDynamic(w, r, loc+"/html/createaccount.html", ca)
} else if pw != pwv || pw == "" || pwv == "" {
ca := createAccount{}
ca.Msg = "The passwords do not match."
ca.Username = un
servePageDynamic(w, r, loc+"/html/createaccount.html", ca)
} else if pw == pwv {
h := sha256.Sum256([]byte(pw))
auth.SavePassword(un, h)
servePageStatic(w, r, loc+"/html/success.html")
}
}
// SaveConfig - Save the configuration settings and then reload the configuration
// page (which will automatically reload the new settings)
func SaveConfig(w http.ResponseWriter, r *http.Request) {
valid := auth.CheckSessionID(r)
if valid {
// Save Configuration Settings
saveConfigToStruct(r)
http.Redirect(w, r, "/dashboard/configure", http.StatusFound)
} else {
http.Redirect(w, r, "/", http.StatusFound)
}
}
// SaveTest - The test has had it's "test specific settings "
func SaveTest(w http.ResponseWriter, r *http.Request) {
valid := auth.CheckSessionID(r)
if valid {
if r.FormValue("runlength") == "" || r.FormValue("location") == "" {
errMsg = "You need to enter a run length and a location!"
http.Redirect(w, r, "/dashboard/start_test", http.StatusFound)
} else {
td := tools.TestData{}
td.Runlen = r.FormValue("runlength")
td.Ext_ip = r.FormValue("externalIP")
td.Ext_url = r.FormValue("externalURL")
td.Location = r.FormValue("location")
td.Ping_delay = r.FormValue("pingdelay")
td.Speedtest_delay = r.FormValue("speedtestedelay")
td.Speedtestfile = r.FormValue("stestfileloc")
pi, err := tools.SetupTest(td)
if err != nil {
errMsg = "No ip associated with the key could be found."
http.Redirect(w, r, "/dashboard/start_test", http.StatusFound)
}
reporter.SetStartTime(time.Now().Format("Jan 02, 2006 - 15:04"))
reporter.SetLocation(td.Location)
runlen, _ := strconv.Atoi(td.Runlen)
logger.WriteString("Running test for: " + td.Runlen)
// go tools.RunTest(pi, runlen)
tools.RunTest(pi, runlen)
http.Redirect(w, r, "/dashboard/reports", http.StatusFound)
}
} else {
http.Redirect(w, r, "/", http.StatusFound)
}
}
// TestStarted - A redirection page to notify the user that the test has been started
func TestStarted(w http.ResponseWriter, r *http.Request) {
valid := auth.CheckSessionID(r)
if valid {
servePageStatic(w, r, "../html/dashboard/testnotify.html")
} else {
http.Redirect(w, r, "/", http.StatusFound)
}
}
// Logout - Logs the user out of the system
func Logout(w http.ResponseWriter, r *http.Request) {
auth.RemoveCookie(w, r)
http.Redirect(w, r, "/", http.StatusFound)
}
//--------------------------------------------
// Dashboard page handler functions
// The following four functions serve dynamic
// pages needed for the dashboard.
//
// Note: Currently static pages, will be dynamic
// later.
//--------------------------------------------
// Settings - Servers the settings web page
func Settings(w http.ResponseWriter, r *http.Request) {
valid := auth.CheckSessionID(r)
if valid {
servePageStatic(w, r, loc+"/html/dashboard/settings.html")
} else {
http.Redirect(w, r, "/", http.StatusFound)
}
}
// Configure - serves the configuration page
func Configure(w http.ResponseWriter, r *http.Request) {
valid := auth.CheckSessionID(r)
// Build struct to serve page with:
configStruct := configPage{}
buildConfigStruct(&configStruct)
if valid {
servePageDynamic(w, r, loc+"/html/dashboard/config.html", configStruct)
} else {
http.Redirect(w, r, "/", http.StatusFound)
}
}
// StartTest - serves the start test web page
func StartTest(w http.ResponseWriter, r *http.Request) {
valid := auth.CheckSessionID(r)
ts := testPage{}
buildTestStruct(&ts)
// Copy the error message over and display it and then erase it
// this way the message will only be displayed when there is an
// actual error
if errMsg != "" {
ts.Msg = errMsg
errMsg = ""
}
if valid {
servePageDynamic(w, r, loc+"/html/dashboard/starttest.html", ts)
} else {
http.Redirect(w, r, "/", http.StatusFound)
}
}
// Reports - serves the reports web page
func Reports(w http.ResponseWriter, r *http.Request) {
valid := auth.CheckSessionID(r)
if valid {
rd := reporter.ReportData{}
buildReport(&rd)
servePageDynamic(w, r, loc+"/html/dashboard/reports.html", rd)
} else {
http.Redirect(w, r, "/", http.StatusFound)
}
}
// Serves a static page
func servePageStatic(w http.ResponseWriter, r *http.Request, pageName string) {
t, _ := template.ParseFiles(pageName)
t.Execute(w, nil)
}
// Serves a page after gathering data needed
func servePageDynamic(w http.ResponseWriter, r *http.Request, pageName string, data interface{}) {
t, _ := template.ParseFiles(pageName)
t.Execute(w, data)
}
//----------------------------------------
// Configuration Handling Functions
//----------------------------------------
// Saves the settings to the config file
func saveConfigToStruct(r *http.Request) {
// Turn this into JSON
configuration.SetDeviceIP(r.FormValue("deviceip"))
configuration.SetInternalIP(ipToMap(r.FormValue("internalip")))
configuration.SetReportLocations(r.FormValue("reportfileloc"))
configuration.SetPortNumber(r.FormValue("portnumber"))
configuration.SetExternalIPs(lineToSlice(r.FormValue("externalip")))
configuration.SetExternalURLs(lineToSlice(r.FormValue("externalurl")))
configuration.SetSpeedTestFileLocation(r.FormValue("stestfileloc"))
configuration.SetPingDelay(r.FormValue("pingdelay"))
configuration.SetSpeedTestDelay(r.FormValue("speedtestdelay"))
configuration.WriteToFile()
}
// Loads the settings from the config file
func buildConfigStruct(cp *configPage) {
cp.DeviceIP = configuration.GetDeviceIP()
cp.Port = configuration.GetPortNumber()
cp.InternalAddr = configuration.GetInternalIPs()
cp.ExternalAddr = configuration.GetExternalIPs()
cp.ExternalURL = configuration.GetExternalURLs()
cp.SpeedFileLoc = configuration.GetSpeedFileLocation()
cp.ReportFileLoc = configuration.GetReportsLocation()
cp.PingDelay = configuration.GetPingDelay()
cp.SpeedDelay = configuration.GetSpeedDelay()
}
func buildTestStruct(ts *testPage) {
ts.PingDelay = configuration.GetPingDelay()
ts.SpeedTestDelay = configuration.GetSpeedDelay()
ts.SpeedTestFileLocation = configuration.GetSpeedFileLocation()
}
func buildReport(r *reporter.ReportData) {
r.Uptime = reporter.GetUptime()
r.LastConnect = reporter.GetLastConnect()
r.DisconnectCount = reporter.GetDisconnectCount()
r.Timeline = reporter.GetTimeline()
r.Status = reporter.GetStatus()
r.Location = reporter.GetLocation()
r.StartTime = reporter.GetStartTime()
}
// Converts a textarea into a slice with one
// line per slice index
func lineToSlice(text string) []string {
// Newlines are considered "whitespace" in Go so this will remove the trailing
// newline characters. Any number of blank lines can be inserted at the end of
// the text area and they will be removed
text = strings.TrimSpace(text)
slice := strings.Split(text, "\n")
return slice
}
// Converts the textarea text into a map of
// id=address for storing in the config struct
func ipToMap(text string) map[string]string {
text = strings.TrimSpace(text)
strmap := make(map[string]string)
nlsplit := strings.Split(text, "\n")
for _, v := range nlsplit {
if v != "" {
ls := strings.Split(v, "=")
strmap[strings.ToLower(ls[0])] = ls[1]
}
}
return strmap
}