diff options
author | Joe Robinson <joe@mumsnet.com> | 2014-07-21 12:16:04 +0100 |
---|---|---|
committer | Joe Robinson <joe@mumsnet.com> | 2014-07-21 12:16:04 +0100 |
commit | 397992465eb0eae75c05779bda1d662129657386 (patch) | |
tree | 8df86e8926da6a290304ffb2e50f53d932420bfe | |
parent | 5b1d414ba23937e7fe1eba74547a7acf33e9c5a6 (diff) |
Only allow users to vote on a poll once
-rw-r--r-- | blavote.go | 31 | ||||
-rw-r--r-- | poll.go | 24 |
2 files changed, 41 insertions, 14 deletions
@@ -14,7 +14,7 @@ var version string func main() { - version = "0.4" + version = "0.5" //Command line arguments var opts struct { @@ -86,9 +86,11 @@ func main() { } } else { - vote(db, opts.Username, opts.Args.Rest) - + err = vote(db, opts.Username, opts.Args.Rest) + if (err != nil) { + fmt.Println(err) + } } } @@ -157,16 +159,21 @@ func vote(db *sqlite3.Conn, nick string, options []string) error { } } - args := sqlite3.NamedArgs{"$a": user.id, "$b": poll.id, "$c": option.id} - sql := "INSERT INTO votes (user_id, poll_id, option_id) VALUES ($a, $b, $c)" + if (!hasUserVotedInPoll(db, poll, user)) { - err = db.Exec(sql, args) + args := sqlite3.NamedArgs{"$a": user.id, "$b": poll.id, "$c": option.id} + sql := "INSERT INTO votes (user_id, poll_id, option_id) VALUES ($a, $b, $c)" + + err = db.Exec(sql, args) + + if (err != nil ) { + return err + } else { + fmt.Println("Vote added") + return nil + } - if (err != nil ) { - fmt.Print("Failed to vote: ") - return err } else { - fmt.Println("Vote added") - return nil + return errors.New("You have already voted in this poll") } -}
\ No newline at end of file +} @@ -85,7 +85,7 @@ func getPollFromId(db *sqlite3.Conn, id int) (Poll, error) { sql := "SELECT * FROM polls WHERE id = $a" s, err := db.Query(sql, args) row := make(sqlite3.RowMap) - + for ; err == nil ; err = s.Next() { var rowid int64 s.Scan(&rowid, row) // Assigns 1st column to rowid, the rest to row @@ -123,5 +123,25 @@ func deletePoll(db *sqlite3.Conn, id int, nick string) error { return errors.New("You do not have permission to delete this poll") } +} + +func hasUserVotedInPoll(db *sqlite3.Conn, poll Poll, user User) bool { -}
\ No newline at end of file + args := sqlite3.NamedArgs{"$a": poll.id, "$b": user.id} + sql := "SELECT count(*) FROM votes WHERE poll_id = $a AND user_id = $b" + s, err := db.Query(sql, args) + + for ; err == nil ; err = s.Next() { + var count int64 + s.Scan(&count) // Assigns 1st column to rowid, the rest to row + + if (count == 0) { + return false + } else { + return true + } + } + + //Not sure why we'd get here, but we probably don't want to record a vote if we did + return true +} |