-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgozilla.go
More file actions
387 lines (326 loc) · 13.5 KB
/
gozilla.go
File metadata and controls
387 lines (326 loc) · 13.5 KB
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
376
377
378
379
380
381
382
383
384
385
386
387
// gozilla.go
package main
import (
"fmt"
"net"
"net/http"
// Note: htemplate does HTML-escaping, which prevents against HTML-injection attacks!
// ttemplate does not, is not currently used and should not be used, but could be used for rendering HTML if absolutely necessary.
// To re-enable ttemplate, be sure to enable it everywhere, including in utils.go.
htemplate "html/template"
//ttemplate "text/template"
)
var (
htemplates map[string]*htemplate.Template
//ttemplates map[string]*ttemplate.Template
err error
// NavMenu (constant)
navMenu []string
)
const (
kActivity = "activity"
kArticle = "article"
kContest = "contest"
kCreate = "create"
kCreateBlog = "createBlog"
kCreateLink = "createLink"
kCreatePoll = "createPoll"
kDailyEmail = "dailyEmail"
kEmailPreference = "emailPreference"
kLogin = "login"
kLoginFB = "loginFB"
kLoginRequired = "loginRequired" // Prompt to log in / sign in if required from user action.
kLoginSignup = "loginSignup" // User clicks on log in / sign in button
kMaps = "maps"
kNews = "news"
kNewsSources = "newsSources"
kNuForm = "nuForm"
kNuFormPopup = "nuFormPopup"
kRegister = "register"
kRegisterDetails = "registerDetails"
kTutorial = "tutorial"
kViewPollResults = "viewPollResults"
)
///////////////////////////////////////////////////////////////////////////////
//
// HTML Template Args
//
///////////////////////////////////////////////////////////////////////////////
// Page Args
type PageArgs struct {
Title string
Script string
Metadata map[string]string
}
// title - page title
// oImage - optional image ("" = use default votezilla image)
// oDescription - optional description ("" = use default description)
func makePageArgs(r *http.Request, title, oImage, oDescription string) (pa PageArgs) {
pa.Title = title
// Source: https://ogp.me/#types
// Test: https://developers.facebook.com/tools/debug/?q=votezilla.io
pa.Metadata = make(map[string]string)
pa.Metadata["og:title"] = title
pa.Metadata["og:image"] = ternary_str(oImage != "", oImage, "http://votezilla.io/static/votezilla logo/votezilla FB og image.jpg")
pa.Metadata["og:description"] = ternary_str(oDescription != "", oDescription, `Votezilla:
a social network based on creating polls, ranked voting, sharing news, and fostering positive
political discussion. (Or nerd out on other topics you love.)`)
pa.Metadata["og:type"] = "website"
pa.Metadata["og:site_name"] = "Votezilla"
pa.Metadata["og:image:type"] = "image/jpeg"
pa.Metadata["og:locale"] = "en_US"
pa.Metadata["og:url"] = "http://votezilla.io" + r.URL.Path + "?" + r.URL.RawQuery
pa.Metadata["fb:app_id"] = "759729064806025"
prVal("r.URL", r.URL)
return pa
}
// Form Frame Args
type FormFrameArgs struct {
PageArgs
Form Form
}
func makeFormFrameArgs(r *http.Request, form *Form, title string) FormFrameArgs {
return FormFrameArgs {
PageArgs: makePageArgs(r, title, "", ""),
Form: *form,
}
}
// Frame Args
type FrameArgs struct {
PageArgs
NavMenu []string
UrlPath string
UserId int64
Username string
UpVotes []int64
DownVotes []int64
}
func makeFrameArgs(r *http.Request, title, script, urlPath string, userId int64, username string) FrameArgs {
pa := makePageArgs(r, title, "", "")
pa.Script = script
return FrameArgs {
PageArgs: pa,
NavMenu: navMenu,
UrlPath: urlPath,
UserId: userId,
Username: username,
}
}
func makeFrameArgs2(r *http.Request, title, script, urlPath string, userId int64, username string, upVotes, downVotes []int64) FrameArgs {
pa := makeFrameArgs(r, title, script, urlPath, userId, username)
pa.UpVotes = upVotes
pa.DownVotes = downVotes
return pa
}
///////////////////////////////////////////////////////////////////////////////
//
// TODO: get user's ip address
// 1) To log in the database when user is first created.
// 2) To set their location in registerDetails and save them time.
// USING: https://play.golang.org/p/Z6ATIgo_IM
// https://stackoverflow.com/questions/27234861/correct-way-of-getting-clients-ip-addresses-from-http-request-golang
//
///////////////////////////////////////////////////////////////////////////////
func ipHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<p>remote addr: %s</p>", r.RemoteAddr)
fmt.Fprintf(w, "<p>forwarded for: %s</p>", r.Header.Get("X-Forwarded-For"))
fmt.Fprintf(w, "<br><p>r: %+v</p>", r)
ip, port, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
fmt.Fprintf(w, "userip: %q is not IP:port", r.RemoteAddr)
}
userIP := net.ParseIP(ip)
if userIP == nil {
//return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
fmt.Fprintf(w, "userip: %q is not IP:port", r.RemoteAddr)
}
fmt.Fprintf(w, "<p>User IP: %s</p>", userIP)
// This will only be defined when site is accessed via non-anonymous proxy
// and takes precedence over RemoteAddr
// Header.Get is case-insensitive
forward := r.Header.Get("X-Forwarded-For")
fmt.Fprintf(w, "<p>IP: %s</p>", ip)
fmt.Fprintf(w, "<p>Port: %s</p>", port)
fmt.Fprintf(w, "<p>Forwarded for: %s</p>", forward)
}
func widthHandler(w http.ResponseWriter, r *http.Request) {
serveHtml(w, `
<script>
alert('Your device inner width: ' + window.innerWidth +
'; screen width: ' + screen.width);
</script>
`)
}
///////////////////////////////////////////////////////////////////////////////
//
// handler wrapper - Each request should refresh the session.
//
///////////////////////////////////////////////////////////////////////////////
func hwrap(handler func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
prf("\n Handling request from: %s\n", formatRequest(r))
startTimer("hwrap")
err := CheckAndLogIP(w, r)
if err != nil {
serveError(w, err)
return
}
handler(w, r) // Handle the request.
endTimer("hwrap")
}
}
///////////////////////////////////////////////////////////////////////////////
//
// parse template files - Parses the HTML template files.
//
///////////////////////////////////////////////////////////////////////////////
func parseTemplateFiles() {
// Note: htemplate does HTML-escaping, which prevents against HTML-injection attacks!
// ttemplate does not, but is necessary for rendering HTML, such as auto-generated forms.
htemplates = make(map[string]*htemplate.Template)
//ttemplates = make(map[string]*ttemplate.Template)
getTemplatePath := func(page string) string {
return "templates/" + page + ".html"
}
// We're trying to just use hDefineTemplate, since it prevents against HTML injection.
// Templates make it possible to use hDefineTemplate.
// Do it this way if at all possible!!!
//
//tDefineTemplate := func(handle string, filenames ...string) {
// ttemplates[handle] = ttemplate.Must(ttemplate.ParseFiles(map_str(getTemplatePath, filenames)...))
//}
hDefineTemplate := func(handle string, filenames ...string) {
_, found := htemplates[handle]
assertMsg(!found, fmt.Sprintf("Conflicting hDefineTemplate definition for %s!", handle))
htemplates[handle] = htemplate.Must(htemplate.ParseFiles(map_str(getTemplatePath, filenames)...))
}
hDefineTemplate(kNews, "base", "wide", "defines", "frame", "news")
hDefineTemplate(kNuForm, "base", "narrow", "defines", "frame", "nuField", "nuForm", "defaultForm")
hDefineTemplate(kArticle, "base", "wide", "defines", "frame", "sidebar", "article", "comments")
hDefineTemplate(kNewsSources, "base", "wide", "defines", "frame", "newsSources") // nyi
hDefineTemplate(kActivity, "base", "wide", "defines", "frame", "activity")
hDefineTemplate(kContest, "base", "wide", "defines", "frame", "contest")
hDefineTemplate(kCreate, "base", "narrow", "minFrame", "nuField", "create")
//hDefineTemplate(kCreate, "base", "wide", "defines", "frame", "nuField", "create")
hDefineTemplate(kCreateBlog, "base", "narrow", "minFrame", "nuField", "createBlog")
hDefineTemplate(kCreateLink, "base", "narrow", "minFrame", "nuField", "createLink")
hDefineTemplate(kCreatePoll, "base", "narrowWithSidebar", "minFrame", "nuField", "createPoll")
hDefineTemplate(kLogin, "base", "narrow", "minFrame", "nuField", "login") // Log in
hDefineTemplate(kLoginFB, "base", "narrow", "minFrame", "nuField", "loginFB") // Log in
hDefineTemplate(kLoginSignup, "base", "narrow", "minFrame", "nuField", "loginSignup") // Option to Log in or Sign up
hDefineTemplate(kRegister, "base", "narrow", "minFrame", "nuField", "register") // Sign up
hDefineTemplate(kRegisterDetails, "base", "narrow", "minFrame", "nuField", "registerDetails") // Sign up II: Demographics
hDefineTemplate(kEmailPreference, "base", "narrow", "minFrame", "nuField", "emailPreference")
hDefineTemplate(kViewPollResults, "base", "wide", "defines", "frame", "sidebar", "viewPollResults", "comments")
// Pop-ups:
hDefineTemplate(kTutorial, "tutorial")
hDefineTemplate(kLoginRequired, "loginRequired")
// Email templates:
hDefineTemplate(kDailyEmail, "emailBase", "defines", "dailyEmail")
// Javascript snippets
//tDefineTemplate(kRegisterDetailsScript, "registerDetailsScript") // TODO: find a new home for this. Just add to registerDetails(?)
// Maps
hDefineTemplate(kMaps, "maps")
}
///////////////////////////////////////////////////////////////////////////////
//
// program entry
//
///////////////////////////////////////////////////////////////////////////////
func init() {
pr("init")
parseTemplateFiles()
}
///
type fileServer_Cached struct {
fileServer http.Handler
}
func FileServer_Cached(root http.FileSystem) http.Handler {
return &fileServer_Cached{
fileServer: http.FileServer(root),
}
}
func (f *fileServer_Cached) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "max-age:31536000, public")
f.fileServer.ServeHTTP(w, r)
}
func SetupWebHandlers() *http.ServeMux {
mux := &http.ServeMux{}
mux.HandleFunc("/", hwrap(newsHandler))
mux.HandleFunc("/ajaxCreateComment/", hwrap(ajaxCreateComment))
mux.HandleFunc("/ajaxCheckForNotifications/",hwrap(ajaxCheckForNotifications))
mux.HandleFunc("/ajaxExpandComment/", hwrap(ajaxExpandComment))
mux.HandleFunc("/ajaxPollVote/", hwrap(ajaxPollVote))
mux.HandleFunc("/ajaxScrapeTitle/", hwrap(ajaxScrapeTitle))
mux.HandleFunc("/ajaxScrapeImageURLs/", hwrap(ajaxScrapeImageURLs))
mux.HandleFunc("/ajaxVote/", hwrap(ajaxVote))
mux.HandleFunc("/article/", hwrap(articleHandler))
mux.HandleFunc("/activity/", hwrap(activityHandler))
mux.HandleFunc("/contest/", hwrap(contestHandler))
mux.HandleFunc("/create/", hwrap(createHandler))
mux.HandleFunc("/createBlog/", hwrap(createBlogHandler))
mux.HandleFunc("/createLink/", hwrap(createLinkHandler))
mux.HandleFunc("/createPoll/", hwrap(createPollHandler))
mux.HandleFunc("/emailPreference/", hwrap(emailPreferenceHandler))
mux.HandleFunc("/history/", hwrap(historyHandler))
mux.HandleFunc("/ip/", hwrap(ipHandler))
mux.HandleFunc("/login/", hwrap(loginHandler))
mux.HandleFunc("/loginFB/", hwrap(loginFBHandler))
mux.HandleFunc("/loginRequired/", hwrap(loginRequiredHandler))
mux.HandleFunc("/loginSignup/", hwrap(loginSignupHandler))
mux.HandleFunc("/logout/", hwrap(logoutHandler))
mux.HandleFunc("/maps/", hwrap(mapsHandler))
mux.HandleFunc("/polls/", hwrap(pollsHandler))
mux.HandleFunc("/news/", hwrap(newsHandler))
mux.HandleFunc("/register/", hwrap(registerHandler))
mux.HandleFunc("/registerDetails/", hwrap(registerDetailsHandler))
mux.HandleFunc("/tutorial/" , hwrap(tutorialHandler))
mux.HandleFunc("/updatePassword/", hwrap(updatePasswordHandler))
mux.HandleFunc("/viewPollResults/", hwrap(viewPollResultsHandler))
mux.HandleFunc("/width/", hwrap(widthHandler))
mux.HandleFunc("/exportSubs/", hwrap(exportSubsHandler))
mux.HandleFunc("/importSubs/", hwrap(importSubsHandler))
// For testing the HTML email:
mux.HandleFunc("/welcomeEmail/", hwrap(welcomeEmailHandler))
mux.HandleFunc("/dailyEmail/", hwrap(dailyEmailHandler))
// For testing Facebook widgets:
mux.HandleFunc("/fbHome/", hwrap(fbHome))
mux.HandleFunc("/fbLogin/", hwrap(fbLogin))
// Serve static files.
mux.Handle("/static/", http.StripPrefix("/static/", FileServer_Cached(http.Dir("./static"))))
// Special handling for favicon.ico.
mux.Handle("/favicon.ico", FileServer_Cached(http.Dir("./static")))
return mux
}
func WebServer() {
if flags.separateNewsAndPolls { // false
navMenu = []string{"polls", "news", "create", "activity", "history" }
} else {
navMenu = []string{"news", "activity", "create", "about", "history" }
}
InitSecurity()
InitNewsSources()
InitFirewall()
InitWebServer()
//InitEmail()
}
func main() {
pr("main")
parseCommandLineFlags()
OpenDatabase()
defer CloseDatabase()
prVal("flags.testEmail", flags.testEmail)
if flags.testEmail {
testEmail()
} else if flags.dailyEmail {
dailyEmail()
} else if flags.imageService != "" {
ImageService()
} else if flags.newsService != "" {
NewsService()
} else if flags.cachingService != "" {
CachingService()
} else {
WebServer()
}
}