cacert-boardvoting/boardvoting.go

502 lines
14 KiB
Go
Raw Normal View History

2017-04-15 17:23:40 +00:00
package main
import (
2017-04-17 20:56:20 +00:00
"context"
"crypto/tls"
"crypto/x509"
2017-04-18 00:34:21 +00:00
"encoding/base64"
2017-04-15 17:23:40 +00:00
"fmt"
"github.com/Masterminds/sprig"
2017-04-18 00:34:21 +00:00
"github.com/gorilla/sessions"
"github.com/jmoiron/sqlx"
2017-04-15 17:23:40 +00:00
_ "github.com/mattn/go-sqlite3"
"gopkg.in/yaml.v2"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
2017-04-15 17:23:40 +00:00
)
var logger *log.Logger
var config *Config
2017-04-18 00:34:21 +00:00
var store *sessions.CookieStore
2017-04-18 14:07:54 +00:00
var version = "undefined"
var build = "undefined"
2017-04-15 17:23:40 +00:00
2017-04-18 00:34:21 +00:00
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
}
2017-04-18 00:34:21 +00:00
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 {
2017-04-15 17:23:40 +00:00
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
2017-04-17 20:56:20 +00:00
type contextKey int
const (
ctxNeedsAuth contextKey = iota
2017-04-18 22:05:42 +00:00
ctxVoter
ctxDecision
2017-04-17 20:56:20 +00:00
)
func authenticateRequest(w http.ResponseWriter, r *http.Request, handler func(http.ResponseWriter, *http.Request)) {
for _, cert := range r.TLS.PeerCertificates {
2017-04-15 17:23:40 +00:00
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 {
2017-04-17 20:56:20 +00:00
handler(w, r.WithContext(context.WithValue(r.Context(), ctxVoter, voter)))
return
}
}
2017-04-15 17:23:40 +00:00
}
}
}
2017-04-17 20:56:20 +00:00
needsAuth, ok := r.Context().Value(ctxNeedsAuth).(bool)
if ok && needsAuth {
2017-04-15 17:23:40 +00:00
w.WriteHeader(http.StatusForbidden)
renderTemplate(w, []string{"denied.html"}, nil)
2017-04-15 17:23:40 +00:00
return
}
2017-04-17 20:56:20 +00:00
handler(w, r)
2017-04-15 17:23:40 +00:00
}
type motionParameters struct {
ShowVotes bool
}
type motionListParameters struct {
Page int64
Flags struct {
Confirmed, Withdraw, Unvoted bool
2017-04-15 17:23:40 +00:00
}
}
2017-04-15 17:23:40 +00:00
func parseMotionParameters(r *http.Request) motionParameters {
var m = motionParameters{}
m.ShowVotes, _ = strconv.ParseBool(r.URL.Query().Get("showvotes"))
return m
}
2017-04-15 17:23:40 +00:00
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
}
2017-04-17 20:56:20 +00:00
func motionListHandler(w http.ResponseWriter, r *http.Request) {
params := parseMotionListParameters(r)
2017-04-18 00:34:21 +00:00
session, err := store.Get(r, sessionCookieName)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
2017-04-17 20:56:20 +00:00
var templateContext struct {
Decisions []*DecisionForDisplay
Voter *Voter
Params *motionListParameters
PrevPage, NextPage int64
PageTitle string
2017-04-18 00:34:21 +00:00
Flashes interface{}
2017-04-15 17:23:40 +00:00
}
2017-04-17 20:56:20 +00:00
if voter, ok := r.Context().Value(ctxVoter).(*Voter); ok {
templateContext.Voter = voter
}
2017-04-18 00:34:21 +00:00
if flashes := session.Flashes(); len(flashes) > 0 {
templateContext.Flashes = flashes
}
session.Save(r, w)
2017-04-17 20:56:20 +00:00
templateContext.Params = &params
2017-04-15 17:23:40 +00:00
if templateContext.Decisions, err = FindDecisionsForDisplayOnPage(params.Page, params.Flags.Unvoted, templateContext.Voter); err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
2017-04-15 17:23:40 +00:00
}
2017-04-17 20:56:20 +00:00
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 {
2017-04-17 20:56:20 +00:00
templateContext.NextPage = params.Page + 1
}
}
if params.Page > 1 {
2017-04-17 20:56:20 +00:00
templateContext.PrevPage = params.Page - 1
}
2017-04-15 17:23:40 +00:00
2017-04-17 20:56:20 +00:00
renderTemplate(w, []string{"motions.html", "motion_fragments.html", "header.html", "footer.html"}, templateContext)
}
2017-04-17 20:56:20 +00:00
func motionHandler(w http.ResponseWriter, r *http.Request) {
params := parseMotionParameters(r)
2017-04-17 20:56:20 +00:00
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
2017-04-18 00:34:21 +00:00
Flashes interface{}
}
2017-04-17 20:56:20 +00:00
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
}
}
2017-04-17 20:56:20 +00:00
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)
}
2017-04-17 20:56:20 +00:00
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
}
2017-04-17 20:56:20 +00:00
handler(w, r.WithContext(context.WithValue(r.Context(), ctxDecision, decision)))
}
type motionActionHandler interface {
2017-04-17 20:56:20 +00:00
Handle(w http.ResponseWriter, r *http.Request)
NeedsAuth() bool
}
2017-04-17 20:56:20 +00:00
type authenticationRequiredHandler struct{}
2017-04-17 20:56:20 +00:00
func (authenticationRequiredHandler) NeedsAuth() bool {
return true
}
type withDrawMotionAction struct {
authenticationRequiredHandler
}
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
}
func (withDrawMotionAction) Handle(w http.ResponseWriter, r *http.Request) {
voter, voter_ok := getVoterFromRequest(r)
decision, decision_ok := getDecisionFromRequest(r)
if !voter_ok || !decision_ok || decision.Status != voteStatusPending {
http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
return
}
switch r.Method {
case http.MethodPost:
if confirm, err := strconv.ParseBool(r.PostFormValue("confirm")); err != nil {
log.Println("could not parse confirm parameter:", err)
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
} else if confirm {
WithdrawMotion(&decision.Decision, voter)
} else {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
}
2017-04-17 20:56:20 +00:00
http.Redirect(w, r, "/motions/", http.StatusTemporaryRedirect)
return
default:
fmt.Fprintln(w, "Withdraw motion", decision.Tag)
}
}
2017-04-17 20:56:20 +00:00
type editMotionAction struct {
authenticationRequiredHandler
}
2017-04-18 22:05:42 +00:00
func newMotionHandler(w http.ResponseWriter, r *http.Request) {
voter, ok := getVoterFromRequest(r)
if !ok {
2017-04-17 20:56:20 +00:00
http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
}
2017-04-18 22:05:42 +00:00
templates := []string{"create_motion_form.html", "header.html", "footer.html"}
var templateContext struct {
Form NewDecisionForm
PageTitle string
Voter *Voter
Flashes interface{}
}
2017-04-18 22:05:42 +00:00
switch r.Method {
case http.MethodPost:
form := NewDecisionForm{
Title: r.FormValue("Title"),
Content: r.FormValue("Content"),
VoteType: r.FormValue("VoteType"),
Due: r.FormValue("Due"),
}
2017-04-18 22:05:42 +00:00
if valid, data := form.Validate(); !valid {
templateContext.Voter = voter
templateContext.Form = form
renderTemplate(w, templates, templateContext)
} else {
if err := CreateMotion(data, voter); err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
session, err := store.Get(r, sessionCookieName)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
session.AddFlash("The motion has been proposed!")
session.Save(r, w)
2017-04-18 22:05:42 +00:00
http.Redirect(w, r, "/motions/", http.StatusMovedPermanently)
}
2017-04-18 22:05:42 +00:00
return
default:
2017-04-18 22:05:42 +00:00
templateContext.Voter = voter
templateContext.Form = NewDecisionForm{
VoteType: strconv.FormatInt(voteTypeMotion, 10),
}
renderTemplate(w, templates, templateContext)
}
2017-04-15 17:23:40 +00:00
}
2017-04-18 22:05:42 +00:00
func (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
}
2017-04-18 00:34:21 +00:00
voter, ok := getVoterFromRequest(r)
if !ok {
http.Error(w, http.StatusText(http.StatusPreconditionFailed), http.StatusPreconditionFailed)
}
2017-04-18 22:05:42 +00:00
templates := []string{"edit_motion_form.html", "header.html", "footer.html"}
2017-04-18 00:34:21 +00:00
var templateContext struct {
2017-04-18 22:05:42 +00:00
Form EditDecisionForm
2017-04-18 00:34:21 +00:00
PageTitle string
Voter *Voter
Flashes interface{}
}
switch r.Method {
case http.MethodPost:
2017-04-18 22:05:42 +00:00
form := EditDecisionForm{
2017-04-18 00:34:21 +00:00
Title: r.FormValue("Title"),
Content: r.FormValue("Content"),
VoteType: r.FormValue("VoteType"),
Due: r.FormValue("Due"),
2017-04-18 22:05:42 +00:00
Decision: &decision.Decision,
2017-04-18 00:34:21 +00:00
}
if valid, data := form.Validate(); !valid {
templateContext.Voter = voter
templateContext.Form = form
renderTemplate(w, templates, templateContext)
} else {
2017-04-18 22:05:42 +00:00
if err := UpdateMotion(data, voter); err != nil {
2017-04-18 00:34:21 +00:00
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
session, err := store.Get(r, sessionCookieName)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
2017-04-18 22:05:42 +00:00
session.AddFlash("The motion has been modified!")
2017-04-18 00:34:21 +00:00
session.Save(r, w)
http.Redirect(w, r, "/motions/", http.StatusMovedPermanently)
2017-04-18 00:34:21 +00:00
}
return
default:
templateContext.Voter = voter
2017-04-18 22:05:42 +00:00
templateContext.Form = EditDecisionForm{
Title: decision.Title,
Content: decision.Content,
VoteType: fmt.Sprintf("%d", decision.VoteType),
Decision: &decision.Decision,
2017-04-18 00:34:21 +00:00
}
renderTemplate(w, templates, templateContext)
}
2017-04-15 17:23:40 +00:00
}
2017-04-18 22:05:42 +00:00
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 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
}
}
2017-04-15 17:23:40 +00:00
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"`
2017-04-18 00:34:21 +00:00
CookieSecret string `yaml:"cookie_secret"`
BaseURL string `yaml:"base_url"`
2017-04-18 22:05:42 +00:00
MailServer struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
} `yaml:"mail_server"`
2017-04-15 17:23:40 +00:00
}
2017-04-18 00:34:21 +00:00
func init() {
logger = log.New(os.Stderr, "boardvoting: ", log.LstdFlags|log.LUTC|log.Lshortfile)
2017-04-15 17:23:40 +00:00
2017-04-18 00:34:21 +00:00
source, err := ioutil.ReadFile("config.yaml")
2017-04-15 17:23:40 +00:00
if err != nil {
logger.Fatal(err)
}
2017-04-18 00:34:21 +00:00
if err := yaml.Unmarshal(source, &config); err != nil {
logger.Fatal(err)
}
cookieSecret, err := base64.StdEncoding.DecodeString(config.CookieSecret)
2017-04-15 17:23:40 +00:00
if err != nil {
logger.Fatal(err)
}
2017-04-18 00:34:21 +00:00
if len(cookieSecret) < 32 {
logger.Fatalln("Cookie secret is less than 32 bytes long")
}
store = sessions.NewCookieStore(cookieSecret)
logger.Println("read configuration")
2017-04-15 17:23:40 +00:00
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()
2017-04-15 17:23:40 +00:00
http.Handle("/motions/", http.StripPrefix("/motions/", motionsHandler{}))
http.HandleFunc("/newmotion/", func(w http.ResponseWriter, r *http.Request) {
2017-04-17 20:56:20 +00:00
authenticateRequest(w, r.WithContext(context.WithValue(r.Context(), ctxNeedsAuth, true)), newMotionHandler)
2017-04-15 17:23:40 +00:00
})
http.Handle("/static/", http.FileServer(http.Dir(".")))
http.Handle("/", http.RedirectHandler("/motions/", http.StatusMovedPermanently))
2017-04-15 17:23:40 +00:00
// 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,
2017-04-17 20:56:20 +00:00
ClientAuth: tls.VerifyClientCertIfGiven,
2017-04-15 17:23:40 +00:00
}
tlsConfig.BuildNameToCertificate()
server := &http.Server{
Addr: ":8443",
TLSConfig: tlsConfig,
2017-04-15 17:23:40 +00:00
}
logger.Printf("Launching application on https://localhost%s/\n", server.Addr)
if err = server.ListenAndServeTLS(config.ServerCert, config.ServerKey); err != nil {
2017-04-15 17:23:40 +00:00
logger.Fatal("ListenAndServerTLS: ", err)
}
}