summaryrefslogtreecommitdiff
path: root/boardvoting.go
blob: 3b03f22f894486e42121c4f7d5d9a775d7f41628 (plain)
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"encoding/base64"
	"fmt"
	"github.com/Masterminds/sprig"
	"github.com/gorilla/sessions"
	"github.com/jmoiron/sqlx"
	_ "github.com/mattn/go-sqlite3"
	"gopkg.in/yaml.v2"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

var logger *log.Logger
var config *Config
var store *sessions.CookieStore
var version = "undefined"
var build = "undefined"

const sessionCookieName = "votesession"

func getTemplateFilenames(templates []string) (result []string) {
	result = make([]string, len(templates))
	for i := range templates {
		result[i] = fmt.Sprintf("templates/%s", templates[i])
	}
	return result
}

func renderTemplate(w http.ResponseWriter, templates []string, context interface{}) {
	t := template.Must(template.New(templates[0]).Funcs(sprig.FuncMap()).ParseFiles(getTemplateFilenames(templates)...))
	if err := t.Execute(w, context); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

type contextKey int

const (
	ctxNeedsAuth contextKey = iota
	ctxVoter
	ctxDecision
)

func authenticateRequest(w http.ResponseWriter, r *http.Request, handler func(http.ResponseWriter, *http.Request)) {
	for _, cert := range r.TLS.PeerCertificates {
		for _, extKeyUsage := range cert.ExtKeyUsage {
			if extKeyUsage == x509.ExtKeyUsageClientAuth {
				for _, emailAddress := range cert.EmailAddresses {
					voter, err := FindVoterByAddress(emailAddress)
					if err != nil {
						http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
						return
					}
					if voter != nil {
						handler(w, r.WithContext(context.WithValue(r.Context(), ctxVoter, voter)))
						return
					}
				}
			}
		}
	}
	needsAuth, ok := r.Context().Value(ctxNeedsAuth).(bool)
	if ok && needsAuth {
		w.WriteHeader(http.StatusForbidden)
		renderTemplate(w, []string{"denied.html"}, nil)
		return
	}
	handler(w, r)
}

type motionParameters struct {
	ShowVotes bool
}

type motionListParameters struct {
	Page  int64
	Flags struct {
		Confirmed, Withdraw, Unvoted bool
	}
}

func parseMotionParameters(r *http.Request) motionParameters {
	var m = motionParameters{}
	m.ShowVotes, _ = strconv.ParseBool(r.URL.Query().Get("showvotes"))
	return m
}

func parseMotionListParameters(r *http.Request) motionListParameters {
	var m = motionListParameters{}
	if page, err := strconv.ParseInt(r.URL.Query().Get("page"), 10, 0); err != nil {
		m.Page = 1
	} else {
		m.Page = page
	}
	m.Flags.Withdraw, _ = strconv.ParseBool(r.URL.Query().Get("withdraw"))
	m.Flags.Unvoted, _ = strconv.ParseBool(r.URL.Query().Get("unvoted"))

	if r.Method == http.MethodPost {
		m.Flags.Confirmed, _ = strconv.ParseBool(r.PostFormValue("confirm"))
	}
	return m
}

func motionListHandler(w http.ResponseWriter, r *http.Request) {
	params := parseMotionListParameters(r)
	session, err := store.Get(r, sessionCookieName)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	var templateContext struct {
		Decisions          []*DecisionForDisplay
		Voter              *Voter
		Params             *motionListParameters
		PrevPage, NextPage int64
		PageTitle          string
		Flashes            interface{}
	}
	if voter, ok := r.Context().Value(ctxVoter).(*Voter); ok {
		templateContext.Voter = voter
	}
	if flashes := session.Flashes(); len(flashes) > 0 {
		templateContext.Flashes = flashes
	}
	session.Save(r, w)
	templateContext.Params = &params

	if templateContext.Decisions, err = FindDecisionsForDisplayOnPage(params.Page, params.Flags.Unvoted, templateContext.Voter); err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	if len(templateContext.Decisions) > 0 {
		olderExists, err := templateContext.Decisions[len(templateContext.Decisions)-1].OlderExists(params.Flags.Unvoted, templateContext.Voter)
		if err != nil {
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		if olderExists {
			templateContext.NextPage = params.Page + 1
		}
	}

	if params.Page > 1 {
		templateContext.PrevPage = params.Page - 1
	}

	renderTemplate(w, []string{"motions.html", "motion_fragments.html", "header.html", "footer.html"}, templateContext)
}

func motionHandler(w http.ResponseWriter, r *http.Request) {
	params := parseMotionParameters(r)

	decision, ok := getDecisionFromRequest(r)
	if !ok {
		http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
		return
	}

	var templateContext struct {
		Decision           *DecisionForDisplay
		Voter              *Voter
		Params             *motionParameters
		PrevPage, NextPage int64
		PageTitle          string
		Flashes            interface{}
	}
	voter, ok := getVoterFromRequest(r)
	if ok {
		templateContext.Voter = voter
	}
	templateContext.Params = &params
	if params.ShowVotes {
		if err := decision.LoadVotes(); err != nil {
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
	}
	templateContext.Decision = decision
	templateContext.PageTitle = fmt.Sprintf("Motion %s: %s", decision.Tag, decision.Title)
	renderTemplate(w, []string{"motion.html", "motion_fragments.html", "header.html", "footer.html"}, templateContext)
}

func singleDecisionHandler(w http.ResponseWriter, r *http.Request, tag string, handler func(http.ResponseWriter, *http.Request)) {
	decision, err := FindDecisionForDisplayByTag(tag)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if decision == nil {
		http.NotFound(w, r)
		return
	}
	handler(w, r.WithContext(context.WithValue(r.Context(), ctxDecision, decision)))
}

type motionActionHandler interface {
	Handle(w http.ResponseWriter, r *http.Request)
	NeedsAuth() bool
}

type authenticationRequiredHandler struct{}

func (authenticationRequiredHandler) NeedsAuth() bool {
	return true
}

func getVoterFromRequest(r *http.Request) (voter *Voter, ok bool) {
	voter, ok = r.Context().Value(ctxVoter).(*Voter)
	return
}

func getDecisionFromRequest(r *http.Request) (decision *DecisionForDisplay, ok bool) {
	decision, ok = r.Context().Value(ctxDecision).(*DecisionForDisplay)
	return
}

type FlashMessageAction struct{}

func (a *FlashMessageAction) AddFlash(w http.ResponseWriter, r *http.Request, message interface{}, tags ...string) (err error) {
	session, err := store.Get(r, sessionCookieName)
	if err != nil {
		logger.Println("ERROR getting session:", err)
		return
	}
	session.AddFlash(message, tags...)
	session.Save(r, w)
	if err != nil {
		logger.Println("ERROR saving session:", err)
		return
	}
	return
}

type withDrawMotionAction struct {
	FlashMessageAction
	authenticationRequiredHandler
}

func (a *withDrawMotionAction) Handle(w http.ResponseWriter, r *http.Request) {
	decision, ok := getDecisionFromRequest(r)
	if !ok || decision.Status != voteStatusPending {
		http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
		return
	}
	voter, ok := getVoterFromRequest(r)
	if !ok {
		http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
		return
	}
	templates := []string{"withdraw_motion_form.html", "header.html", "footer.html", "motion_fragments.html"}
	var templateContext struct {
		PageTitle string
		Decision  *DecisionForDisplay
		Flashes   interface{}
	}

	switch r.Method {
	case http.MethodPost:
		decision.Status = voteStatusWithdrawn
		decision.Modified = time.Now().UTC()
		if err := decision.UpdateStatus(); err != nil {
			logger.Println("Error withdrawing motion:", err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}

		notifyMail <- &NotificationWithDrawMotion{decision: decision.Decision, voter: *voter}

		if err := a.AddFlash(w, r, fmt.Sprintf("Motion %s has been withdrawn!", decision.Tag)); err != nil {
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}

		http.Redirect(w, r, "/motions/", http.StatusTemporaryRedirect)
	default:
		templateContext.Decision = decision
		renderTemplate(w, templates, templateContext)
	}
}

type newMotionHandler struct {
	FlashMessageAction
}

func (h *newMotionHandler) Handle(w http.ResponseWriter, r *http.Request) {
	voter, ok := getVoterFromRequest(r)
	if !ok {
		http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
	}

	templates := []string{"create_motion_form.html", "header.html", "footer.html"}
	var templateContext struct {
		Form      NewDecisionForm
		PageTitle string
		Voter     *Voter
		Flashes   interface{}
	}
	switch r.Method {
	case http.MethodPost:
		form := NewDecisionForm{
			Title:    r.FormValue("Title"),
			Content:  r.FormValue("Content"),
			VoteType: r.FormValue("VoteType"),
			Due:      r.FormValue("Due"),
		}

		if valid, data := form.Validate(); !valid {
			templateContext.Voter = voter
			templateContext.Form = form
			renderTemplate(w, templates, templateContext)
		} else {
			data.Proposed = time.Now().UTC()
			data.ProponentId = voter.Id
			if err := data.Create(); err != nil {
				logger.Println("Error saving motion:", err)
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
				return
			}

			notifyMail <- &NotificationCreateMotion{decision: *data, voter: *voter}

			if err := h.AddFlash(w, r, "The motion has been proposed!"); err != nil {
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
				return
			}

			http.Redirect(w, r, "/motions/", http.StatusMovedPermanently)
		}

		return
	default:
		templateContext.Voter = voter
		templateContext.Form = NewDecisionForm{
			VoteType: strconv.FormatInt(voteTypeMotion, 10),
		}
		renderTemplate(w, templates, templateContext)
	}
}

type editMotionAction struct {
	FlashMessageAction
	authenticationRequiredHandler
}

func (a editMotionAction) Handle(w http.ResponseWriter, r *http.Request) {
	decision, ok := getDecisionFromRequest(r)
	if !ok || decision.Status != voteStatusPending {
		http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
		return
	}
	voter, ok := getVoterFromRequest(r)
	if !ok {
		http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
		return
	}
	templates := []string{"edit_motion_form.html", "header.html", "footer.html"}
	var templateContext struct {
		Form      EditDecisionForm
		PageTitle string
		Voter     *Voter
		Flashes   interface{}
	}
	switch r.Method {
	case http.MethodPost:
		form := EditDecisionForm{
			Title:    r.FormValue("Title"),
			Content:  r.FormValue("Content"),
			VoteType: r.FormValue("VoteType"),
			Due:      r.FormValue("Due"),
			Decision: &decision.Decision,
		}

		if valid, data := form.Validate(); !valid {
			templateContext.Voter = voter
			templateContext.Form = form
			renderTemplate(w, templates, templateContext)
		} else {
			data.Modified = time.Now().UTC()
			if err := data.Update(); err != nil {
				logger.Println("Error updating motion:", err)
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
				return
			}

			notifyMail <- &NotificationUpdateMotion{decision: *data, voter: *voter}

			if err := a.AddFlash(w, r, "The motion has been modified!"); err != nil {
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
				return
			}

			http.Redirect(w, r, "/motions/", http.StatusMovedPermanently)
		}
		return
	default:
		templateContext.Voter = voter
		templateContext.Form = EditDecisionForm{
			Title:    decision.Title,
			Content:  decision.Content,
			VoteType: fmt.Sprintf("%d", decision.VoteType),
			Decision: &decision.Decision,
		}
		renderTemplate(w, templates, templateContext)
	}
}

type motionsHandler struct{}

func (h motionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if err := db.Ping(); err != nil {
		logger.Fatal(err)
	}

	subURL := r.URL.Path

	var motionActionMap = map[string]motionActionHandler{
		"withdraw": &withDrawMotionAction{},
		"edit":     &editMotionAction{},
	}

	switch {
	case subURL == "":
		authenticateRequest(w, r.WithContext(context.WithValue(r.Context(), ctxNeedsAuth, false)), motionListHandler)
		return
	case subURL == "/newmotion/":
		handler := &newMotionHandler{}
		authenticateRequest(
			w, r.WithContext(context.WithValue(r.Context(), ctxNeedsAuth, true)),
			handler.Handle)
		return
	case strings.Count(subURL, "/") == 1:
		parts := strings.Split(subURL, "/")
		motionTag := parts[0]
		action, ok := motionActionMap[parts[1]]
		if !ok {
			http.NotFound(w, r)
			return
		}
		authenticateRequest(
			w, r.WithContext(context.WithValue(r.Context(), ctxNeedsAuth, action.NeedsAuth())),
			func(w http.ResponseWriter, r *http.Request) {
				singleDecisionHandler(w, r, motionTag, action.Handle)
			})
		return
	case strings.Count(subURL, "/") == 0:
		authenticateRequest(w, r.WithContext(context.WithValue(r.Context(), ctxNeedsAuth, false)),
			func(w http.ResponseWriter, r *http.Request) {
				singleDecisionHandler(w, r, subURL, motionHandler)
			})
		return
	default:
		http.NotFound(w, r)
		return
	}
}

type Config struct {
	BoardMailAddress     string `yaml:"board_mail_address"`
	NoticeSenderAddress  string `yaml:"notice_sender_address"`
	DatabaseFile         string `yaml:"database_file"`
	ClientCACertificates string `yaml:"client_ca_certificates"`
	ServerCert           string `yaml:"server_certificate"`
	ServerKey            string `yaml:"server_key"`
	CookieSecret         string `yaml:"cookie_secret"`
	BaseURL              string `yaml:"base_url"`
	MailServer           struct {
		Host string `yaml:"host"`
		Port int    `yaml:"port"`
	} `yaml:"mail_server"`
}

func init() {
	logger = log.New(os.Stderr, "boardvoting: ", log.LstdFlags|log.LUTC|log.Lshortfile)

	source, err := ioutil.ReadFile("config.yaml")
	if err != nil {
		logger.Fatal(err)
	}
	if err := yaml.Unmarshal(source, &config); err != nil {
		logger.Fatal(err)
	}

	cookieSecret, err := base64.StdEncoding.DecodeString(config.CookieSecret)
	if err != nil {
		logger.Fatal(err)
	}
	if len(cookieSecret) < 32 {
		logger.Fatalln("Cookie secret is less than 32 bytes long")
	}
	store = sessions.NewCookieStore(cookieSecret)
	logger.Println("read configuration")

	db, err = sqlx.Open("sqlite3", config.DatabaseFile)
	if err != nil {
		logger.Fatal(err)
	}
	logger.Println("opened database connection")
}

func main() {
	logger.Printf("CAcert Board Voting version %s, build %s\n", version, build)

	defer db.Close()

	go MailNotifier()
	defer CloseMailNotifier()

	quitChannel := make(chan int)
	go JobScheduler(quitChannel)
	defer func() { quitChannel <- 1 }()

	http.Handle("/motions/", http.StripPrefix("/motions/", motionsHandler{}))
	http.Handle("/newmotion/", motionsHandler{})
	http.Handle("/static/", http.FileServer(http.Dir(".")))
	http.Handle("/", http.RedirectHandler("/motions/", http.StatusMovedPermanently))

	// load CA certificates for client authentication
	caCert, err := ioutil.ReadFile(config.ClientCACertificates)
	if err != nil {
		logger.Fatal(err)
	}
	caCertPool := x509.NewCertPool()
	if !caCertPool.AppendCertsFromPEM(caCert) {
		logger.Fatal("could not initialize client CA certificate pool")
	}

	// setup HTTPS server
	tlsConfig := &tls.Config{
		ClientCAs:  caCertPool,
		ClientAuth: tls.VerifyClientCertIfGiven,
	}
	tlsConfig.BuildNameToCertificate()

	server := &http.Server{
		Addr:      ":8443",
		TLSConfig: tlsConfig,
	}

	logger.Printf("Launching application on https://localhost%s/\n", server.Addr)

	errs := make(chan error, 1)
	go func() {
		if err := http.ListenAndServe(":8080", http.RedirectHandler(config.BaseURL, http.StatusMovedPermanently)); err != nil {
			errs <- err
		}
		close(errs)
	}()

	if err = server.ListenAndServeTLS(config.ServerCert, config.ServerKey); err != nil {
		logger.Fatal("ListenAndServerTLS: ", err)
	}
	if err := <-errs; err != nil {
		logger.Fatal("ListenAndServe: ", err)
	}
}