-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.go
384 lines (327 loc) · 10.5 KB
/
validation.go
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
package main
import (
"database/sql"
"encoding/json"
"log"
"net/http"
"strconv"
"strings"
"time"
)
type validationResponse struct {
Validation *ValidNomination `json:"validation"`
Office *officeInfo `json:"office"`
Nominator *CMSInfo `json:"nominator"`
}
type ValidNomination struct {
Valid bool `json:"valid"`
Problems Problems `json:"problems,omitempty"`
}
type officeInfo struct {
ID int `json:"id"`
Type string `json:"type"`
Cohorts []string `json:"cohorts"`
}
type nominationInfo struct {
PartialRIN string // last three digits
Name string
RcsID string
ID int
CandidateRCS string
}
type Validator func(*nominationInfo, *CMSInfo, *officeInfo) Problems
type Problem string
type Problems []Problem
// equal returns whether all elements are shared (order doesn't matter)
func (p Problems) equal(other Problems) bool {
if len(p) != len(other) {
return false
}
for _, problem := range p {
found := false
for i, otherProblem := range other {
if problem == otherProblem {
found = true
other = append(other[:i], other[i+1:]...)
break
}
}
if !found {
return false
}
}
return true
}
func studentValidator(nomination *nominationInfo, nominator *CMSInfo, office *officeInfo) Problems {
problems := Problems{}
// check if nominator is student
if nominator.Type != "Student" {
problems = append(problems, "Not a student.")
}
return problems
}
func cohortValidator(nomination *nominationInfo, nominator *CMSInfo, office *officeInfo) Problems {
problems := Problems{}
if nominator == nil || office == nil || nominator.GraduationDate.IsZero() {
return problems
}
// undergrad and grad students
if strings.ToLower(office.Type) == "undergraduate" && !nominator.undergraduate() {
problems = append(problems, "Not an undergraduate student.")
return problems
}
if strings.ToLower(office.Type) == "graduate" && !nominator.graduate() {
problems = append(problems, "Not a graduate student.")
return problems
}
// class year
found := false
for _, cohort := range office.Cohorts {
if cohort == nominator.entryCohort() || cohort == nominator.creditCohort() || (nominator.graduate() && cohort == "graduate") || (nominator.Greek && cohort == "greek") || (!nominator.Greek && cohort == "independent") {
found = true
break
}
}
if !found {
problems = append(problems, "Cohorts not eligible for this office.")
}
return problems
}
func greekIndependentValidator(nomination *nominationInfo, nominator *CMSInfo, office *officeInfo) Problems {
problems := Problems{}
// Greek
if strings.ToLower(office.Type) == "greek" && !nominator.Greek {
problems = append(problems, "Not Greek-affiliated.")
}
// Independent
if strings.ToLower(office.Type) == "independent" && nominator.Greek {
problems = append(problems, "Greek-affiliated.")
}
return problems
}
func rinRCSMatchValidator(nomination *nominationInfo, nominator *CMSInfo, office *officeInfo) Problems {
problems := Problems{}
if nomination == nil || nominator == nil {
return problems
}
if len(nomination.PartialRIN) > 3 {
problems = append(problems, "Partial RIN value contains more than three digits.")
}
if len(nomination.PartialRIN) < 3 {
problems = append(problems, "Partial RIN value contains less than three digits.")
}
// rcs matches rin?
if nominator.RIN[len(nominator.RIN)-3:] != nomination.PartialRIN {
problems = append(problems, "Mismatched RIN digits.")
}
return problems
}
// nameValidator assumes format "Firstname Lastname", which is super limited and does not
// properly handle everyone's names. This is not currently in use, as the site does not
// collect names of nominators.
func nameValidator(nomination *nominationInfo, nominator *CMSInfo, office *officeInfo) Problems {
problems := Problems{}
if nomination == nil || nominator == nil {
return problems
}
if len(nomination.Name) == 0 {
problems = append(problems, "No name provided.")
return problems
}
splitName := strings.Split(nomination.Name, " ")
if len(splitName) != 2 {
problems = append(problems, "Name not in recognized format.")
return problems
}
firstName := strings.ToLower(splitName[0])
lastName := strings.ToLower(splitName[1])
if firstName != strings.ToLower(nominator.FirstName) {
problems = append(problems, "First name does not match Institute records.")
}
if lastName != strings.ToLower(nominator.LastName) {
problems = append(problems, "Last name does not match Institute records.")
}
return problems
}
// uniqueValidator checks for any other nominations that have the same RIN. It returns problems if another
// nomination has a lower ID than this one (and therefore it is not the only one).
// Because it needs database access, this validator needs to be called differently from the others,
// and it can return an error.
func uniqueValidator(nomination *nominationInfo, nominator *CMSInfo, office *officeInfo) (Problems, error) {
problems := Problems{}
if nomination == nil {
return problems, nil
}
db, err := getDB()
if err != nil {
return problems, err
}
defer db.Close()
var count int
row := db.QueryRow("SELECT count(*) FROM nominations WHERE rcs_id = ? AND office_id = ? AND nomination_rcs_id = ? AND nomination_id < ?", nomination.CandidateRCS, office.ID, nomination.RcsID, nomination.ID)
err = row.Scan(&count)
if err != nil {
return problems, err
}
if count > 0 {
problems = append(problems, "Nominator has already nominated this candidate for this office.")
}
return problems, nil
}
// validate uses election-specific info validators to validate the provided information.
// It takes in existing Problems (may be empty), and it returns a ValidNomination struct.
func validate(nomination *nominationInfo, nominator *CMSInfo, office *officeInfo, problems Problems) ValidNomination {
validators := []Validator{
studentValidator,
cohortValidator,
greekIndependentValidator,
rinRCSMatchValidator,
}
for _, validator := range validators {
problems = append(problems, validator(nomination, nominator, office)...)
}
vn := ValidNomination{}
if len(problems) == 0 {
vn.Valid = true
} else {
vn.Valid = false
}
vn.Problems = problems
return vn
}
// validateNomination returns information about whether a nomination is valid or invalid.
// It requires authorization, and only admins have permission to use it.
// TODO: check if the nomination is a duplicate of an existing one
func validateNomination(w http.ResponseWriter, r *http.Request) {
// check if this user has permission to do this
admin := adminFromContext(r.Context())
if !admin {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
// validate provided input
office := r.FormValue("office")
if office == "" {
http.Error(w, "missing office", http.StatusUnprocessableEntity)
return
}
candidateRCS := r.FormValue("candidate_rcs")
if candidateRCS == "" {
http.Error(w, "missing candidate RCS", http.StatusUnprocessableEntity)
return
}
// start filling out nomination info fields
rin := r.FormValue("rin")
nomID, err := strconv.ParseInt(r.FormValue("id"), 10, 64)
if err != nil {
log.Printf("unable to parse int: %s", err.Error())
http.Error(w, http.StatusText(http.StatusUnprocessableEntity), http.StatusUnprocessableEntity)
return
}
nomination := nominationInfo{}
nomination.PartialRIN = rin
nomination.ID = int(nomID)
nomination.RcsID = r.FormValue("rcs")
nomination.CandidateRCS = candidateRCS
// get office info
db, err := getDB()
if err != nil {
log.Printf("unable to get database: %s", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
defer db.Close()
row := db.QueryRow("SELECT type FROM offices WHERE office_id = ? AND election_id = "+activeElectionQuery, office)
if err != nil {
log.Printf("unable to query database: %s", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
var officeType string
err = row.Scan(&officeType)
if err == sql.ErrNoRows {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
} else if err != nil {
log.Printf("unable to scan: %s", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
officeInfo := officeInfoFromType(officeType)
officeID, err := strconv.ParseInt(office, 10, 64)
if err != nil {
log.Printf("unable to parse int: %s", err.Error())
http.Error(w, http.StatusText(http.StatusUnprocessableEntity), http.StatusUnprocessableEntity)
return
}
officeInfo.ID = int(officeID)
nominator, err := cmsInfoRCS(nomination.RcsID)
if err == errInfoNotFound {
vn := ValidNomination{Valid: false, Problems: Problems{"Invalid RCS."}}
resp := validationResponse{
Validation: &vn,
Office: &officeInfo,
Nominator: nil,
}
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
err = enc.Encode(resp)
if err != nil {
log.Printf("unable to encode JSON: %s", err.Error())
return
}
return
}
if err != nil {
log.Printf("unable to get CMS info: %s", err.Error())
http.Error(w, "unable to get CMS info", http.StatusInternalServerError)
return
}
// special handling of uniqueValidator
uniqueProblems, err := uniqueValidator(&nomination, &nominator, &officeInfo)
if err != nil {
log.Printf("unable to get CMS info: %s", err.Error())
http.Error(w, "unable to get CMS info", http.StatusInternalServerError)
return
}
// validate the nomination
vn := validate(&nomination, &nominator, &officeInfo, uniqueProblems)
resp := validationResponse{
Validation: &vn,
Office: &officeInfo,
Nominator: &nominator,
}
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
err = enc.Encode(resp)
if err != nil {
log.Printf("unable to encode JSON: %s", err.Error())
return
}
}
func officeInfoFromType(officeType string) officeInfo {
o := officeInfo{Type: strings.ToLower(officeType)}
year := time.Now().Year()
if o.Type == "all" {
o.Cohorts = []string{"graduate"}
for i := 0; i < 4; i++ {
cohort := strconv.FormatInt(int64(year+i), 10)
o.Cohorts = append(o.Cohorts, cohort)
}
} else if o.Type == "greek" {
o.Cohorts = []string{"greek"}
} else if o.Type == "independent" {
o.Cohorts = []string{"independent"}
} else if o.Type == "graduate" {
o.Cohorts = []string{"graduate"}
} else if o.Type == "undergraduate" {
for i := 0; i < 4; i++ {
cohort := strconv.FormatInt(int64(year+i), 10)
o.Cohorts = append(o.Cohorts, cohort)
}
} else {
o.Cohorts = []string{o.Type}
return o
}
return o
}