summaryrefslogtreecommitdiff
path: root/boardvoting.go
blob: 68210d9a16e5ec84eed7a5fee94bc25e76a861b1 (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
package main

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

const (
	list_decisions_sql = `
SELECT decisions.id, decisions.tag, decisions.proponent,
       voters.name AS proposer, decisions.proposed, decisions.title,
       decisions.content, decisions.votetype, decisions.status, decisions.due,
       decisions.modified
FROM decisions
JOIN voters ON decisions.proponent=voters.id
ORDER BY proposed DESC
LIMIT 10 OFFSET 10 * ($1 - 1)`
	get_decision_sql = `
SELECT decisions.id, decisions.tag, decisions.proponent,
       voters.name AS proposer, decisions.proposed, decisions.title,
       decisions.content, decisions.votetype, decisions.status, decisions.due,
       decisions.modified
FROM decisions
JOIN voters ON decisions.proponent=voters.id
WHERE decisions.id=$1;`
	get_voter = `
SELECT voters.id, voters.name
FROM voters
JOIN emails ON voters.id=emails.voter
WHERE emails.address=$1 AND voters.enabled=1`
	vote_count_sql = `
SELECT vote, COUNT(vote)
FROM votes
WHERE decision=$1`
)

var db *sqlx.DB
var logger *log.Logger

const (
	voteAye = 1
	voteNaye = -1
	voteAbstain = 0
)

const (
	voteTypeMotion = 0
	voteTypeVeto = 1
)

type VoteType int

func (v VoteType) String() string {
	switch v {
	case voteTypeMotion: return "motion"
	case voteTypeVeto: return "veto"
	default: return "unknown"
	}
}

func (v VoteType) QuorumAndMajority() (int, int) {
	switch v {
	case voteTypeMotion: return 3, 50
	default: return 1, 99
	}
}

type VoteSums struct {
	Ayes     int
	Nayes    int
	Abstains int
}

func (v *VoteSums) voteCount() int {
	return v.Ayes + v.Nayes + v.Abstains
}

type VoteStatus int

func (v VoteStatus) String() string {
	switch v {
	case -1: return "declined"
	case 0: return "pending"
	case 1: return "approved"
	case -2: return "withdrawn"
	default: return "unknown"
	}
}

type VoteKind int

func (v VoteKind) String() string {
	switch v {
	case voteAye: return "Aye"
	case voteNaye: return "Naye"
	case voteAbstain: return "Abstain"
	default: return "unknown"
	}
}

type Vote struct {
	Name string
	Vote VoteKind
}

type Decision struct {
	Id        int
	Tag       string
	Proponent int
	Proposer  string
	Proposed  time.Time
	Title     string
	Content   string
	Majority  int
	Quorum    int
	VoteType  VoteType
	Status    VoteStatus
	Due       time.Time
	Modified  time.Time
	VoteSums
	Votes     []Vote
}

func (d *Decision) parseVote(vote int, count int) {
	switch vote {
	case voteAye:
		d.Ayes = count
	case voteAbstain:
		d.Abstains = count
	case voteNaye:
		d.Nayes = count
	}
}

type Voter struct {
	Id   int
	Name string
}

func authenticateVoter(emailAddress string, voter *Voter) bool {
	err := db.Ping()
	if err != nil {
		logger.Fatal(err)
	}

	auth_stmt, err := db.Preparex(get_voter)
	if err != nil {
		logger.Fatal(err)
	}
	defer auth_stmt.Close()
	var found = false
	err = auth_stmt.Get(voter, emailAddress)
	if err == nil {
		found = true
	} else {
		if err != sql.ErrNoRows {
			logger.Fatal(err)
		}
	}
	return found
}

func redirectToMotionsHandler(w http.ResponseWriter, _ *http.Request) {
	w.Header().Add("Location", "/motions")
	w.WriteHeader(http.StatusMovedPermanently)
}

func renderTemplate(w http.ResponseWriter, tmpl string, context interface{}) {
	t := template.New("motions.html")
	t.Funcs(sprig.FuncMap())
	t, err := t.ParseFiles(fmt.Sprintf("templates/%s.html", tmpl))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	err = t.Execute(w, context)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

func authenticateRequest(
w http.ResponseWriter, r *http.Request,
handler func(http.ResponseWriter, *http.Request, *Voter)) {
	var voter Voter
	var found = false
	authLoop: for _, cert := range r.TLS.PeerCertificates {
		var isClientCert = false
		for _, extKeyUsage := range cert.ExtKeyUsage {
			if extKeyUsage == x509.ExtKeyUsageClientAuth {
				isClientCert = true
				break
			}
		}
		if !isClientCert {
			continue
		}

		for _, emailAddress := range cert.EmailAddresses {
			if authenticateVoter(emailAddress, &voter) {
				found = true
				break authLoop
			}
		}
	}
	if !found {
		w.WriteHeader(http.StatusForbidden)
		renderTemplate(w, "denied", nil)
		return
	}
	handler(w, r, &voter)
}

func motionsHandler(w http.ResponseWriter, _ *http.Request, voter *Voter) {
	err := db.Ping()
	if err != nil {
		logger.Fatal(err)
	}

	// $page = is_numeric($_REQUEST['page'])?$_REQUEST['page']:1;

	motion_stmt, err := db.Preparex(list_decisions_sql)
	votes_stmt, err := db.Preparex(vote_count_sql)
	if err != nil {
		logger.Fatal(err)
	}
	defer motion_stmt.Close()
	defer votes_stmt.Close()

	rows, err := motion_stmt.Queryx(1)
	if err != nil {
		logger.Fatal(err)
	}
	defer rows.Close()

	var page struct {
		Decisions []Decision
		Voter     *Voter
	}
	page.Voter = voter

	for rows.Next() {
		var d Decision
		err := rows.StructScan(&d)
		if err != nil {
			logger.Fatal(err)
		}

		voteRows, err := votes_stmt.Queryx(d.Id)
		if err != nil {
			logger.Fatal(err)
		}

		for voteRows.Next() {
			var vote, count int
			err = voteRows.Scan(&vote, &count)
			if err != nil {
				voteRows.Close()
				logger.Fatal(err)
			}
			d.parseVote(vote, count)
		}
		page.Decisions = append(page.Decisions, d)

		voteRows.Close()
	}

	renderTemplate(w, "motions", page)
}

func votersHandler(w http.ResponseWriter, _ *http.Request, voter *Voter) {
	err := db.Ping()
	if err != nil {
		logger.Fatal(err)
	}

	fmt.Fprintln(w, "Hello", voter.Name)

	sqlStmt := "SELECT name, reminder FROM voters WHERE enabled=1"

	rows, err := db.Query(sqlStmt)
	if err != nil {
		logger.Fatal(err)
	}
	defer rows.Close()

	fmt.Print("Enabled voters\n\n")
	fmt.Printf("%-30s %-30s\n", "Name", "Reminder E-Mail address")
	fmt.Printf("%s %s\n", strings.Repeat("-", 30), strings.Repeat("-", 30))
	for rows.Next() {
		var name string
		var reminder string

		err = rows.Scan(&name, &reminder)
		if err != nil {
			logger.Fatal(err)
		}
		fmt.Printf("%-30s %s\n", name, reminder)
	}
	err = rows.Err()
	if err != nil {
		logger.Fatal(err)
	}
}

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"`
}

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

	var filename = "config.yaml"
	if len(os.Args) == 2 {
		filename = os.Args[1]
	}

	var err error

	var config Config
	var source []byte

	source, err = ioutil.ReadFile(filename)
	if err != nil {
		logger.Fatal(err)
	}
	err = yaml.Unmarshal(source, &config)
	if err != nil {
		logger.Fatal(err)
	}
	logger.Printf("read configuration %v", config)

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

	http.HandleFunc("/motions", func(w http.ResponseWriter, r *http.Request) {
		authenticateRequest(w, r, motionsHandler)
	})
	http.HandleFunc("/voters", func(w http.ResponseWriter, r *http.Request) {
		authenticateRequest(w, r, votersHandler)
	})
	http.HandleFunc("/static/", http.FileServer(http.Dir(".")).ServeHTTP)
	http.HandleFunc("/", redirectToMotionsHandler)

	// 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.RequireAndVerifyClientCert,
	}
	tlsConfig.BuildNameToCertificate()

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

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

	defer db.Close()
}