Implement motion creation mail template
[cacert-boardvoting.git] / boardvoting.go
1 package main
2
3 import (
4 "context"
5 "crypto/tls"
6 "crypto/x509"
7 "encoding/base64"
8 "fmt"
9 "github.com/Masterminds/sprig"
10 "github.com/gorilla/sessions"
11 "github.com/jmoiron/sqlx"
12 _ "github.com/mattn/go-sqlite3"
13 "gopkg.in/yaml.v2"
14 "html/template"
15 "io/ioutil"
16 "log"
17 "net/http"
18 "os"
19 "strconv"
20 "strings"
21 )
22
23 var logger *log.Logger
24 var config *Config
25 var store *sessions.CookieStore
26 var version = "undefined"
27 var build = "undefined"
28
29 const sessionCookieName = "votesession"
30
31 func getTemplateFilenames(templates []string) (result []string) {
32 result = make([]string, len(templates))
33 for i := range templates {
34 result[i] = fmt.Sprintf("templates/%s", templates[i])
35 }
36 return result
37 }
38
39 func renderTemplate(w http.ResponseWriter, templates []string, context interface{}) {
40 t := template.Must(template.New(templates[0]).Funcs(sprig.FuncMap()).ParseFiles(getTemplateFilenames(templates)...))
41 if err := t.Execute(w, context); err != nil {
42 http.Error(w, err.Error(), http.StatusInternalServerError)
43 }
44 }
45
46 type contextKey int
47
48 const (
49 ctxNeedsAuth contextKey = iota
50 ctxVoter contextKey = iota
51 ctxDecision contextKey = iota
52 )
53
54 func authenticateRequest(w http.ResponseWriter, r *http.Request, handler func(http.ResponseWriter, *http.Request)) {
55 for _, cert := range r.TLS.PeerCertificates {
56 for _, extKeyUsage := range cert.ExtKeyUsage {
57 if extKeyUsage == x509.ExtKeyUsageClientAuth {
58 for _, emailAddress := range cert.EmailAddresses {
59 voter, err := FindVoterByAddress(emailAddress)
60 if err != nil {
61 http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
62 return
63 }
64 if voter != nil {
65 handler(w, r.WithContext(context.WithValue(r.Context(), ctxVoter, voter)))
66 return
67 }
68 }
69 }
70 }
71 }
72 needsAuth, ok := r.Context().Value(ctxNeedsAuth).(bool)
73 if ok && needsAuth {
74 w.WriteHeader(http.StatusForbidden)
75 renderTemplate(w, []string{"denied.html"}, nil)
76 return
77 }
78 handler(w, r)
79 }
80
81 type motionParameters struct {
82 ShowVotes bool
83 }
84
85 type motionListParameters struct {
86 Page int64
87 Flags struct {
88 Confirmed, Withdraw, Unvoted bool
89 }
90 }
91
92 func parseMotionParameters(r *http.Request) motionParameters {
93 var m = motionParameters{}
94 m.ShowVotes, _ = strconv.ParseBool(r.URL.Query().Get("showvotes"))
95 return m
96 }
97
98 func parseMotionListParameters(r *http.Request) motionListParameters {
99 var m = motionListParameters{}
100 if page, err := strconv.ParseInt(r.URL.Query().Get("page"), 10, 0); err != nil {
101 m.Page = 1
102 } else {
103 m.Page = page
104 }
105 m.Flags.Withdraw, _ = strconv.ParseBool(r.URL.Query().Get("withdraw"))
106 m.Flags.Unvoted, _ = strconv.ParseBool(r.URL.Query().Get("unvoted"))
107
108 if r.Method == http.MethodPost {
109 m.Flags.Confirmed, _ = strconv.ParseBool(r.PostFormValue("confirm"))
110 }
111 return m
112 }
113
114 func motionListHandler(w http.ResponseWriter, r *http.Request) {
115 params := parseMotionListParameters(r)
116 session, err := store.Get(r, sessionCookieName)
117 if err != nil {
118 http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
119 return
120 }
121
122 var templateContext struct {
123 Decisions []*DecisionForDisplay
124 Voter *Voter
125 Params *motionListParameters
126 PrevPage, NextPage int64
127 PageTitle string
128 Flashes interface{}
129 }
130 if voter, ok := r.Context().Value(ctxVoter).(*Voter); ok {
131 templateContext.Voter = voter
132 }
133 if flashes := session.Flashes(); len(flashes) > 0 {
134 templateContext.Flashes = flashes
135 }
136 session.Save(r, w)
137 templateContext.Params = &params
138
139 if templateContext.Decisions, err = FindDecisionsForDisplayOnPage(params.Page, params.Flags.Unvoted, templateContext.Voter); err != nil {
140 http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
141 return
142 }
143
144 if len(templateContext.Decisions) > 0 {
145 olderExists, err := templateContext.Decisions[len(templateContext.Decisions)-1].OlderExists(params.Flags.Unvoted, templateContext.Voter)
146 if err != nil {
147 http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
148 return
149 }
150 if olderExists {
151 templateContext.NextPage = params.Page + 1
152 }
153 }
154
155 if params.Page > 1 {
156 templateContext.PrevPage = params.Page - 1
157 }
158
159 renderTemplate(w, []string{"motions.html", "motion_fragments.html", "header.html", "footer.html"}, templateContext)
160 }
161
162 func motionHandler(w http.ResponseWriter, r *http.Request) {
163 params := parseMotionParameters(r)
164
165 decision, ok := getDecisionFromRequest(r)
166 if !ok {
167 http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
168 return
169 }
170
171 var templateContext struct {
172 Decision *DecisionForDisplay
173 Voter *Voter
174 Params *motionParameters
175 PrevPage, NextPage int64
176 PageTitle string
177 Flashes interface{}
178 }
179 voter, ok := getVoterFromRequest(r)
180 if ok {
181 templateContext.Voter = voter
182 }
183 templateContext.Params = &params
184 if params.ShowVotes {
185 if err := decision.LoadVotes(); err != nil {
186 http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
187 return
188 }
189 }
190 templateContext.Decision = decision
191 templateContext.PageTitle = fmt.Sprintf("Motion %s: %s", decision.Tag, decision.Title)
192 renderTemplate(w, []string{"motion.html", "motion_fragments.html", "header.html", "footer.html"}, templateContext)
193 }
194
195 func singleDecisionHandler(w http.ResponseWriter, r *http.Request, tag string, handler func(http.ResponseWriter, *http.Request)) {
196 decision, err := FindDecisionForDisplayByTag(tag)
197 if err != nil {
198 http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
199 return
200 }
201 if decision == nil {
202 http.NotFound(w, r)
203 return
204 }
205 handler(w, r.WithContext(context.WithValue(r.Context(), ctxDecision, decision)))
206 }
207
208 type motionActionHandler interface {
209 Handle(w http.ResponseWriter, r *http.Request)
210 NeedsAuth() bool
211 }
212
213 type authenticationRequiredHandler struct{}
214
215 func (authenticationRequiredHandler) NeedsAuth() bool {
216 return true
217 }
218
219 type withDrawMotionAction struct {
220 authenticationRequiredHandler
221 }
222
223 func getVoterFromRequest(r *http.Request) (voter *Voter, ok bool) {
224 voter, ok = r.Context().Value(ctxVoter).(*Voter)
225 return
226 }
227
228 func getDecisionFromRequest(r *http.Request) (decision *DecisionForDisplay, ok bool) {
229 decision, ok = r.Context().Value(ctxDecision).(*DecisionForDisplay)
230 return
231 }
232
233 func (withDrawMotionAction) Handle(w http.ResponseWriter, r *http.Request) {
234 voter, voter_ok := getVoterFromRequest(r)
235 decision, decision_ok := getDecisionFromRequest(r)
236
237 if !voter_ok || !decision_ok || decision.Status != voteStatusPending {
238 http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
239 return
240 }
241
242 switch r.Method {
243 case http.MethodPost:
244 if confirm, err := strconv.ParseBool(r.PostFormValue("confirm")); err != nil {
245 log.Println("could not parse confirm parameter:", err)
246 http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
247 } else if confirm {
248 WithdrawMotion(&decision.Decision, voter)
249 } else {
250 http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
251 }
252 http.Redirect(w, r, "/motions/", http.StatusTemporaryRedirect)
253 return
254 default:
255 fmt.Fprintln(w, "Withdraw motion", decision.Tag)
256 }
257 }
258
259 type editMotionAction struct {
260 authenticationRequiredHandler
261 }
262
263 func (editMotionAction) Handle(w http.ResponseWriter, r *http.Request) {
264 decision, ok := getDecisionFromRequest(r)
265 if !ok || decision.Status != voteStatusPending {
266 http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
267 return
268 }
269 fmt.Fprintln(w, "Edit motion", decision.Tag)
270 // TODO: implement
271 }
272
273 type motionsHandler struct{}
274
275 func (h motionsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
276 if err := db.Ping(); err != nil {
277 logger.Fatal(err)
278 }
279
280 subURL := r.URL.Path
281
282 var motionActionMap = map[string]motionActionHandler{
283 "withdraw": withDrawMotionAction{},
284 "edit": editMotionAction{},
285 }
286
287 switch {
288 case subURL == "":
289 authenticateRequest(w, r.WithContext(context.WithValue(r.Context(), ctxNeedsAuth, false)), motionListHandler)
290 return
291 case strings.Count(subURL, "/") == 1:
292 parts := strings.Split(subURL, "/")
293 logger.Printf("handle %v\n", parts)
294 motionTag := parts[0]
295 action, ok := motionActionMap[parts[1]]
296 if !ok {
297 http.NotFound(w, r)
298 return
299 }
300 authenticateRequest(
301 w, r.WithContext(context.WithValue(r.Context(), ctxNeedsAuth, action.NeedsAuth())),
302 func(w http.ResponseWriter, r *http.Request) {
303 singleDecisionHandler(w, r, motionTag, action.Handle)
304 })
305 logger.Printf("motion: %s, action: %s\n", motionTag, action)
306 return
307 case strings.Count(subURL, "/") == 0:
308 authenticateRequest(w, r.WithContext(context.WithValue(r.Context(), ctxNeedsAuth, false)),
309 func(w http.ResponseWriter, r *http.Request) {
310 singleDecisionHandler(w, r, subURL, motionHandler)
311 })
312 return
313 default:
314 http.NotFound(w, r)
315 return
316 }
317 }
318
319 func newMotionHandler(w http.ResponseWriter, r *http.Request) {
320 voter, ok := getVoterFromRequest(r)
321 if !ok {
322 http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
323 }
324
325 templates := []string{"newmotion_form.html", "header.html", "footer.html"}
326 var templateContext struct {
327 Form NewDecisionForm
328 PageTitle string
329 Voter *Voter
330 Flashes interface{}
331 }
332 switch r.Method {
333 case http.MethodPost:
334 form := NewDecisionForm{
335 Title: r.FormValue("Title"),
336 Content: r.FormValue("Content"),
337 VoteType: r.FormValue("VoteType"),
338 Due: r.FormValue("Due"),
339 }
340
341 if valid, data := form.Validate(); !valid {
342 templateContext.Voter = voter
343 templateContext.Form = form
344 renderTemplate(w, templates, templateContext)
345 } else {
346 if err := CreateMotion(data, voter); err != nil {
347 http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
348 return
349 }
350 session, err := store.Get(r, sessionCookieName)
351 if err != nil {
352 http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
353 return
354 }
355 session.AddFlash("The motion has been proposed!")
356 session.Save(r, w)
357
358 http.Redirect(w, r, "/motions/", http.StatusMovedPermanently)
359 }
360
361 return
362 default:
363 templateContext.Voter = voter
364 templateContext.Form = NewDecisionForm{
365 VoteType: strconv.FormatInt(voteTypeMotion, 10),
366 }
367 renderTemplate(w, templates, templateContext)
368 }
369 }
370
371 type Config struct {
372 BoardMailAddress string `yaml:"board_mail_address"`
373 NoticeSenderAddress string `yaml:"notice_sender_address"`
374 DatabaseFile string `yaml:"database_file"`
375 ClientCACertificates string `yaml:"client_ca_certificates"`
376 ServerCert string `yaml:"server_certificate"`
377 ServerKey string `yaml:"server_key"`
378 CookieSecret string `yaml:"cookie_secret"`
379 BaseURL string `yaml:"base_url"`
380 }
381
382 func init() {
383 logger = log.New(os.Stderr, "boardvoting: ", log.LstdFlags|log.LUTC|log.Lshortfile)
384
385 source, err := ioutil.ReadFile("config.yaml")
386 if err != nil {
387 logger.Fatal(err)
388 }
389 if err := yaml.Unmarshal(source, &config); err != nil {
390 logger.Fatal(err)
391 }
392
393 cookieSecret, err := base64.StdEncoding.DecodeString(config.CookieSecret)
394 if err != nil {
395 logger.Fatal(err)
396 }
397 if len(cookieSecret) < 32 {
398 logger.Fatalln("Cookie secret is less than 32 bytes long")
399 }
400 store = sessions.NewCookieStore(cookieSecret)
401 logger.Println("read configuration")
402
403 db, err = sqlx.Open("sqlite3", config.DatabaseFile)
404 if err != nil {
405 logger.Fatal(err)
406 }
407 logger.Println("opened database connection")
408 }
409
410 func main() {
411 logger.Printf("CAcert Board Voting version %s, build %s\n", version, build)
412
413 defer db.Close()
414
415 http.Handle("/motions/", http.StripPrefix("/motions/", motionsHandler{}))
416 http.HandleFunc("/newmotion/", func(w http.ResponseWriter, r *http.Request) {
417 authenticateRequest(w, r.WithContext(context.WithValue(r.Context(), ctxNeedsAuth, true)), newMotionHandler)
418 })
419 http.Handle("/static/", http.FileServer(http.Dir(".")))
420 http.Handle("/", http.RedirectHandler("/motions/", http.StatusMovedPermanently))
421
422 // load CA certificates for client authentication
423 caCert, err := ioutil.ReadFile(config.ClientCACertificates)
424 if err != nil {
425 logger.Fatal(err)
426 }
427 caCertPool := x509.NewCertPool()
428 if !caCertPool.AppendCertsFromPEM(caCert) {
429 logger.Fatal("could not initialize client CA certificate pool")
430 }
431
432 // setup HTTPS server
433 tlsConfig := &tls.Config{
434 ClientCAs: caCertPool,
435 ClientAuth: tls.VerifyClientCertIfGiven,
436 }
437 tlsConfig.BuildNameToCertificate()
438
439 server := &http.Server{
440 Addr: ":8443",
441 TLSConfig: tlsConfig,
442 }
443
444 logger.Printf("Launching application on https://localhost%s/\n", server.Addr)
445
446 if err = server.ListenAndServeTLS(config.ServerCert, config.ServerKey); err != nil {
447 logger.Fatal("ListenAndServerTLS: ", err)
448 }
449 }