Skip to content
Snippets Groups Projects
Commit a676d712 authored by Ben Adida's avatar Ben Adida
Browse files

re-added helios django app as part of the same git project

parent 1a650466
No related branches found
No related tags found
No related merge requests found
Showing
with 4078 additions and 0 deletions
The Helios Django App
=====================
LICENSE: this code is released under the GPL v3 or later.
NOTE: this used to be a separate git submodule, but now it's not.
from django.conf import settings
TEMPLATE_BASE = settings.HELIOS_TEMPLATE_BASE or "helios/templates/base.html"
# a setting to ensure that only admins can create an election
ADMIN_ONLY = settings.HELIOS_ADMIN_ONLY
# allow upload of voters via CSV?
VOTERS_UPLOAD = settings.HELIOS_VOTERS_UPLOAD
# allow emailing of voters?
VOTERS_EMAIL = settings.HELIOS_VOTERS_EMAIL
from django.core.urlresolvers import reverse
# get the short path for the URL
def get_election_url(election):
from views import election_shortcut
return settings.URL_HOST + reverse(election_shortcut, args=[election.short_name])
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.api.datastore import _CurrentTransactionKey
import random
class GeneralCounterShardConfig(db.Model):
"""Tracks the number of shards for each named counter."""
name = db.StringProperty(required=True)
num_shards = db.IntegerProperty(required=True, default=20)
class GeneralCounterShard(db.Model):
"""Shards for each named counter"""
name = db.StringProperty(required=True)
count = db.IntegerProperty(required=True, default=0)
def get_config(name):
if _CurrentTransactionKey():
config = GeneralCounterShardConfig.get_by_key_name(name)
if not config:
config = GeneralCounterShardConfig(name=name)
config.put()
return config
else:
return GeneralCounterShardConfig.get_or_insert(name, name=name)
def get_count(name):
"""Retrieve the value for a given sharded counter.
Parameters:
name - The name of the counter
"""
total = memcache.get(name)
if total is None:
total = 0
for counter in GeneralCounterShard.all().filter('name = ', name):
total += counter.count
memcache.add(name, str(total), 60)
return total
def increment(name):
"""Increment the value for a given sharded counter.
Parameters:
name - The name of the counter
"""
config = get_config(name)
def txn():
index = random.randint(0, config.num_shards - 1)
shard_name = name + str(index)
counter = GeneralCounterShard.get_by_key_name(shard_name)
if counter is None:
counter = GeneralCounterShard(key_name=shard_name, name=name)
counter.count += 1
counter.put()
if _CurrentTransactionKey():
txn()
else:
db.run_in_transaction(txn)
memcache.incr(name)
def increase_shards(name, num):
"""Increase the number of shards for a given sharded counter.
Will never decrease the number of shards.
Parameters:
name - The name of the counter
num - How many shards to use
"""
config = get_config(name)
def txn():
if config.num_shards < num:
config.num_shards = num
config.put()
if _CurrentTransactionKey():
txn()
else:
db.run_in_transaction(txn)
This diff is collapsed.
This diff is collapsed.
#
# number.py : Number-theoretic functions
#
# Part of the Python Cryptography Toolkit
#
# Distribute and use freely; there are no restrictions on further
# dissemination and usage except those imposed by the laws of your
# country of residence. This software is provided "as is" without
# warranty of fitness for use or suitability for any purpose, express
# or implied. Use at your own risk or not at all.
#
__revision__ = "$Id: number.py,v 1.13 2003/04/04 18:21:07 akuchling Exp $"
bignum = long
try:
from Crypto.PublicKey import _fastmath
except ImportError:
_fastmath = None
# Commented out and replaced with faster versions below
## def long2str(n):
## s=''
## while n>0:
## s=chr(n & 255)+s
## n=n>>8
## return s
## import types
## def str2long(s):
## if type(s)!=types.StringType: return s # Integers will be left alone
## return reduce(lambda x,y : x*256+ord(y), s, 0L)
def size (N):
"""size(N:long) : int
Returns the size of the number N in bits.
"""
bits, power = 0,1L
while N >= power:
bits += 1
power = power << 1
return bits
def getRandomNumber(N, randfunc):
"""getRandomNumber(N:int, randfunc:callable):long
Return an N-bit random number."""
S = randfunc(N/8)
odd_bits = N % 8
if odd_bits != 0:
char = ord(randfunc(1)) >> (8-odd_bits)
S = chr(char) + S
value = bytes_to_long(S)
value |= 2L ** (N-1) # Ensure high bit is set
assert size(value) >= N
return value
def GCD(x,y):
"""GCD(x:long, y:long): long
Return the GCD of x and y.
"""
x = abs(x) ; y = abs(y)
while x > 0:
x, y = y % x, x
return y
def inverse(u, v):
"""inverse(u:long, u:long):long
Return the inverse of u mod v.
"""
u3, v3 = long(u), long(v)
u1, v1 = 1L, 0L
while v3 > 0:
q=u3 / v3
u1, v1 = v1, u1 - v1*q
u3, v3 = v3, u3 - v3*q
while u1<0:
u1 = u1 + v
return u1
# Given a number of bits to generate and a random generation function,
# find a prime number of the appropriate size.
def getPrime(N, randfunc):
"""getPrime(N:int, randfunc:callable):long
Return a random N-bit prime number.
"""
number=getRandomNumber(N, randfunc) | 1
while (not isPrime(number)):
number=number+2
return number
def isPrime(N):
"""isPrime(N:long):bool
Return true if N is prime.
"""
if N == 1:
return 0
if N in sieve:
return 1
for i in sieve:
if (N % i)==0:
return 0
# Use the accelerator if available
if _fastmath is not None:
return _fastmath.isPrime(N)
# Compute the highest bit that's set in N
N1 = N - 1L
n = 1L
while (n<N):
n=n<<1L
n = n >> 1L
# Rabin-Miller test
for c in sieve[:7]:
a=long(c) ; d=1L ; t=n
while (t): # Iterate over the bits in N1
x=(d*d) % N
if x==1L and d!=1L and d!=N1:
return 0 # Square root of 1 found
if N1 & t:
d=(x*a) % N
else:
d=x
t = t >> 1L
if d!=1L:
return 0
return 1
# Small primes used for checking primality; these are all the primes
# less than 256. This should be enough to eliminate most of the odd
# numbers before needing to do a Rabin-Miller test at all.
sieve=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127,
131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193,
197, 199, 211, 223, 227, 229, 233, 239, 241, 251]
# Improved conversion functions contributed by Barry Warsaw, after
# careful benchmarking
import struct
def long_to_bytes(n, blocksize=0):
"""long_to_bytes(n:long, blocksize:int) : string
Convert a long integer to a byte string.
If optional blocksize is given and greater than zero, pad the front of the
byte string with binary zeros so that the length is a multiple of
blocksize.
"""
# after much testing, this algorithm was deemed to be the fastest
s = ''
n = long(n)
pack = struct.pack
while n > 0:
s = pack('>I', n & 0xffffffffL) + s
n = n >> 32
# strip off leading zeros
for i in range(len(s)):
if s[i] != '\000':
break
else:
# only happens when n == 0
s = '\000'
i = 0
s = s[i:]
# add back some pad bytes. this could be done more efficiently w.r.t. the
# de-padding being done above, but sigh...
if blocksize > 0 and len(s) % blocksize:
s = (blocksize - len(s) % blocksize) * '\000' + s
return s
def bytes_to_long(s):
"""bytes_to_long(string) : long
Convert a byte string to a long integer.
This is (essentially) the inverse of long_to_bytes().
"""
acc = 0L
unpack = struct.unpack
length = len(s)
if length % 4:
extra = (4 - length % 4)
s = '\000' * extra + s
length = length + extra
for i in range(0, length, 4):
acc = (acc << 32) + unpack('>I', s[i:i+4])[0]
return acc
# For backwards compatibility...
import warnings
def long2str(n, blocksize=0):
warnings.warn("long2str() has been replaced by long_to_bytes()")
return long_to_bytes(n, blocksize)
def str2long(s):
warnings.warn("str2long() has been replaced by bytes_to_long()")
return bytes_to_long(s)
This diff is collapsed.
#
# randpool.py : Cryptographically strong random number generation
#
# Part of the Python Cryptography Toolkit
#
# Distribute and use freely; there are no restrictions on further
# dissemination and usage except those imposed by the laws of your
# country of residence. This software is provided "as is" without
# warranty of fitness for use or suitability for any purpose, express
# or implied. Use at your own risk or not at all.
#
__revision__ = "$Id: randpool.py,v 1.14 2004/05/06 12:56:54 akuchling Exp $"
import time, array, types, warnings, os.path
from number import long_to_bytes
try:
import Crypto.Util.winrandom as winrandom
except:
winrandom = None
STIRNUM = 3
class RandomPool:
"""randpool.py : Cryptographically strong random number generation.
The implementation here is similar to the one in PGP. To be
cryptographically strong, it must be difficult to determine the RNG's
output, whether in the future or the past. This is done by using
a cryptographic hash function to "stir" the random data.
Entropy is gathered in the same fashion as PGP; the highest-resolution
clock around is read and the data is added to the random number pool.
A conservative estimate of the entropy is then kept.
If a cryptographically secure random source is available (/dev/urandom
on many Unixes, Windows CryptGenRandom on most Windows), then use
it.
Instance Attributes:
bits : int
Maximum size of pool in bits
bytes : int
Maximum size of pool in bytes
entropy : int
Number of bits of entropy in this pool.
Methods:
add_event([s]) : add some entropy to the pool
get_bytes(int) : get N bytes of random data
randomize([N]) : get N bytes of randomness from external source
"""
def __init__(self, numbytes = 160, cipher=None, hash=None):
if hash is None:
import sha as hash
# The cipher argument is vestigial; it was removed from
# version 1.1 so RandomPool would work even in the limited
# exportable subset of the code
if cipher is not None:
warnings.warn("'cipher' parameter is no longer used")
if isinstance(hash, types.StringType):
# ugly hack to force __import__ to give us the end-path module
hash = __import__('Crypto.Hash.'+hash,
None, None, ['new'])
warnings.warn("'hash' parameter should now be a hashing module")
self.bytes = numbytes
self.bits = self.bytes*8
self.entropy = 0
self._hash = hash
# Construct an array to hold the random pool,
# initializing it to 0.
self._randpool = array.array('B', [0]*self.bytes)
self._event1 = self._event2 = 0
self._addPos = 0
self._getPos = hash.digest_size
self._lastcounter=time.time()
self.__counter = 0
self._measureTickSize() # Estimate timer resolution
self._randomize()
def _updateEntropyEstimate(self, nbits):
self.entropy += nbits
if self.entropy < 0:
self.entropy = 0
elif self.entropy > self.bits:
self.entropy = self.bits
def _randomize(self, N = 0, devname = '/dev/urandom'):
"""_randomize(N, DEVNAME:device-filepath)
collects N bits of randomness from some entropy source (e.g.,
/dev/urandom on Unixes that have it, Windows CryptoAPI
CryptGenRandom, etc)
DEVNAME is optional, defaults to /dev/urandom. You can change it
to /dev/random if you want to block till you get enough
entropy.
"""
data = ''
if N <= 0:
nbytes = int((self.bits - self.entropy)/8+0.5)
else:
nbytes = int(N/8+0.5)
if winrandom:
# Windows CryptGenRandom provides random data.
data = winrandom.new().get_bytes(nbytes)
# GAE fix, benadida
#elif os.path.exists(devname):
# # Many OSes support a /dev/urandom device
# try:
# f=open(devname)
# data=f.read(nbytes)
# f.close()
# except IOError, (num, msg):
# if num!=2: raise IOError, (num, msg)
# # If the file wasn't found, ignore the error
if data:
self._addBytes(data)
# Entropy estimate: The number of bits of
# data obtained from the random source.
self._updateEntropyEstimate(8*len(data))
self.stir_n() # Wash the random pool
def randomize(self, N=0):
"""randomize(N:int)
use the class entropy source to get some entropy data.
This is overridden by KeyboardRandomize().
"""
return self._randomize(N)
def stir_n(self, N = STIRNUM):
"""stir_n(N)
stirs the random pool N times
"""
for i in xrange(N):
self.stir()
def stir (self, s = ''):
"""stir(s:string)
Mix up the randomness pool. This will call add_event() twice,
but out of paranoia the entropy attribute will not be
increased. The optional 's' parameter is a string that will
be hashed with the randomness pool.
"""
entropy=self.entropy # Save inital entropy value
self.add_event()
# Loop over the randomness pool: hash its contents
# along with a counter, and add the resulting digest
# back into the pool.
for i in range(self.bytes / self._hash.digest_size):
h = self._hash.new(self._randpool)
h.update(str(self.__counter) + str(i) + str(self._addPos) + s)
self._addBytes( h.digest() )
self.__counter = (self.__counter + 1) & 0xFFFFffffL
self._addPos, self._getPos = 0, self._hash.digest_size
self.add_event()
# Restore the old value of the entropy.
self.entropy=entropy
def get_bytes (self, N):
"""get_bytes(N:int) : string
Return N bytes of random data.
"""
s=''
i, pool = self._getPos, self._randpool
h=self._hash.new()
dsize = self._hash.digest_size
num = N
while num > 0:
h.update( self._randpool[i:i+dsize] )
s = s + h.digest()
num = num - dsize
i = (i + dsize) % self.bytes
if i<dsize:
self.stir()
i=self._getPos
self._getPos = i
self._updateEntropyEstimate(- 8*N)
return s[:N]
def add_event(self, s=''):
"""add_event(s:string)
Add an event to the random pool. The current time is stored
between calls and used to estimate the entropy. The optional
's' parameter is a string that will also be XORed into the pool.
Returns the estimated number of additional bits of entropy gain.
"""
event = time.time()*1000
delta = self._noise()
s = (s + long_to_bytes(event) +
4*chr(0xaa) + long_to_bytes(delta) )
self._addBytes(s)
if event==self._event1 and event==self._event2:
# If events are coming too closely together, assume there's
# no effective entropy being added.
bits=0
else:
# Count the number of bits in delta, and assume that's the entropy.
bits=0
while delta:
delta, bits = delta>>1, bits+1
if bits>8: bits=8
self._event1, self._event2 = event, self._event1
self._updateEntropyEstimate(bits)
return bits
# Private functions
def _noise(self):
# Adds a bit of noise to the random pool, by adding in the
# current time and CPU usage of this process.
# The difference from the previous call to _noise() is taken
# in an effort to estimate the entropy.
t=time.time()
delta = (t - self._lastcounter)/self._ticksize*1e6
self._lastcounter = t
self._addBytes(long_to_bytes(long(1000*time.time())))
self._addBytes(long_to_bytes(long(1000*time.clock())))
self._addBytes(long_to_bytes(long(1000*time.time())))
self._addBytes(long_to_bytes(long(delta)))
# Reduce delta to a maximum of 8 bits so we don't add too much
# entropy as a result of this call.
delta=delta % 0xff
return int(delta)
def _measureTickSize(self):
# _measureTickSize() tries to estimate a rough average of the
# resolution of time that you can see from Python. It does
# this by measuring the time 100 times, computing the delay
# between measurements, and taking the median of the resulting
# list. (We also hash all the times and add them to the pool)
interval = [None] * 100
h = self._hash.new(`(id(self),id(interval))`)
# Compute 100 differences
t=time.time()
h.update(`t`)
i = 0
j = 0
while i < 100:
t2=time.time()
h.update(`(i,j,t2)`)
j += 1
delta=int((t2-t)*1e6)
if delta:
interval[i] = delta
i += 1
t=t2
# Take the median of the array of intervals
interval.sort()
self._ticksize=interval[len(interval)/2]
h.update(`(interval,self._ticksize)`)
# mix in the measurement times and wash the random pool
self.stir(h.digest())
def _addBytes(self, s):
"XOR the contents of the string S into the random pool"
i, pool = self._addPos, self._randpool
for j in range(0, len(s)):
pool[i]=pool[i] ^ ord(s[j])
i=(i+1) % self.bytes
self._addPos = i
# Deprecated method names: remove in PCT 2.1 or later.
def getBytes(self, N):
warnings.warn("getBytes() method replaced by get_bytes()",
DeprecationWarning)
return self.get_bytes(N)
def addEvent (self, event, s=""):
warnings.warn("addEvent() method replaced by add_event()",
DeprecationWarning)
return self.add_event(s + str(event))
class PersistentRandomPool (RandomPool):
def __init__ (self, filename=None, *args, **kwargs):
RandomPool.__init__(self, *args, **kwargs)
self.filename = filename
if filename:
try:
# the time taken to open and read the file might have
# a little disk variability, modulo disk/kernel caching...
f=open(filename, 'rb')
self.add_event()
data = f.read()
self.add_event()
# mix in the data from the file and wash the random pool
self.stir(data)
f.close()
except IOError:
# Oh, well; the file doesn't exist or is unreadable, so
# we'll just ignore it.
pass
def save(self):
if self.filename == "":
raise ValueError, "No filename set for this object"
# wash the random pool before save, provides some forward secrecy for
# old values of the pool.
self.stir_n()
f=open(self.filename, 'wb')
self.add_event()
f.write(self._randpool.tostring())
f.close()
self.add_event()
# wash the pool again, provide some protection for future values
self.stir()
# non-echoing Windows keyboard entry
_kb = 0
if not _kb:
try:
import msvcrt
class KeyboardEntry:
def getch(self):
c = msvcrt.getch()
if c in ('\000', '\xe0'):
# function key
c += msvcrt.getch()
return c
def close(self, delay = 0):
if delay:
time.sleep(delay)
while msvcrt.kbhit():
msvcrt.getch()
_kb = 1
except:
pass
# non-echoing Posix keyboard entry
if not _kb:
try:
import termios
class KeyboardEntry:
def __init__(self, fd = 0):
self._fd = fd
self._old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3]=new[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, new)
def getch(self):
termios.tcflush(0, termios.TCIFLUSH) # XXX Leave this in?
return os.read(self._fd, 1)
def close(self, delay = 0):
if delay:
time.sleep(delay)
termios.tcflush(self._fd, termios.TCIFLUSH)
termios.tcsetattr(self._fd, termios.TCSAFLUSH, self._old)
_kb = 1
except:
pass
class KeyboardRandomPool (PersistentRandomPool):
def __init__(self, *args, **kwargs):
PersistentRandomPool.__init__(self, *args, **kwargs)
def randomize(self, N = 0):
"Adds N bits of entropy to random pool. If N is 0, fill up pool."
import os, string, time
if N <= 0:
bits = self.bits - self.entropy
else:
bits = N*8
if bits == 0:
return
print bits,'bits of entropy are now required. Please type on the keyboard'
print 'until enough randomness has been accumulated.'
kb = KeyboardEntry()
s='' # We'll save the characters typed and add them to the pool.
hash = self._hash
e = 0
try:
while e < bits:
temp=str(bits-e).rjust(6)
os.write(1, temp)
s=s+kb.getch()
e += self.add_event(s)
os.write(1, 6*chr(8))
self.add_event(s+hash.new(s).digest() )
finally:
kb.close()
print '\n\007 Enough. Please wait a moment.\n'
self.stir_n() # wash the random pool.
kb.close(4)
if __name__ == '__main__':
pool = RandomPool()
print 'random pool entropy', pool.entropy, 'bits'
pool.add_event('something')
print `pool.get_bytes(100)`
import tempfile, os
fname = tempfile.mktemp()
pool = KeyboardRandomPool(filename=fname)
print 'keyboard random pool entropy', pool.entropy, 'bits'
pool.randomize()
print 'keyboard random pool entropy', pool.entropy, 'bits'
pool.randomize(128)
pool.save()
saved = open(fname, 'rb').read()
print 'saved', `saved`
print 'pool ', `pool._randpool.tostring()`
newpool = PersistentRandomPool(fname)
print 'persistent random pool entropy', pool.entropy, 'bits'
os.remove(fname)
"""
Crypto Utils
"""
import sha, hmac, base64
from django.utils import simplejson
from hashlib import sha256
def hash_b64(s):
"""
hash the string using sha1 and produce a base64 output
removes the trailing "="
"""
hasher = sha256(s)
result= base64.b64encode(hasher.digest())[:-1]
return result
def to_json(d):
return simplejson.dumps(d, sort_keys=True)
def from_json(json_str):
if not json_str: return None
return simplejson.loads(json_str)
# -*- coding: utf-8 -*-
# utils/widgets.py
'''
DateTimeWidget using JSCal2 from http://www.dynarch.com/projects/calendar/
django snippets 1629
'''
from django.utils.encoding import force_unicode
from django.conf import settings
from django import forms
import datetime, time
from django.utils.safestring import mark_safe
# DATETIMEWIDGET
calbtn = u'''<img src="%smedia/admin/img/admin/icon_calendar.gif" alt="calendar" id="%s_btn" style="cursor: pointer;" title="Select date" />
<script type="text/javascript">
Calendar.setup({
inputField : "%s",
dateFormat : "%s",
trigger : "%s_btn",
showTime: true
});
</script>'''
class DateTimeWidget(forms.widgets.TextInput):
class Media:
css = {
'all': (
'/static/helios/jscal/css/jscal2.css',
'/static/helios/jscal/css/border-radius.css',
'/static/helios/jscal/css/win2k/win2k.css',
)
}
js = (
'/static/helios/jscal/js/jscal2.js',
'/static/helios/jscal/js/lang/en.js',
)
dformat = '%Y-%m-%d %H:%M'
def render(self, name, value, attrs=None):
if value is None: value = ''
final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
if value != '':
try:
final_attrs['value'] = \
force_unicode(value.strftime(self.dformat))
except:
final_attrs['value'] = \
force_unicode(value)
if not final_attrs.has_key('id'):
final_attrs['id'] = u'%s_id' % (name)
id = final_attrs['id']
jsdformat = self.dformat #.replace('%', '%%')
cal = calbtn % (settings.MEDIA_URL, id, id, jsdformat, id)
a = u'<input%s />%s%s' % (forms.util.flatatt(final_attrs), self.media, cal)
return mark_safe(a)
def value_from_datadict(self, data, files, name):
dtf = forms.fields.DEFAULT_DATETIME_INPUT_FORMATS
empty_values = forms.fields.EMPTY_VALUES
value = data.get(name, None)
if value in empty_values:
return None
if isinstance(value, datetime.datetime):
return value
if isinstance(value, datetime.date):
return datetime.datetime(value.year, value.month, value.day)
for format in dtf:
try:
return datetime.datetime(*time.strptime(value, format)[:6])
except ValueError:
continue
return None
def _has_changed(self, initial, data):
"""
Return True if data differs from initial.
Copy of parent's method, but modify value with strftime function before final comparsion
"""
if data is None:
data_value = u''
else:
data_value = data
if initial is None:
initial_value = u''
else:
initial_value = initial
try:
if force_unicode(initial_value.strftime(self.dformat)) != force_unicode(data_value.strftime(self.dformat)):
return True
except:
if force_unicode(initial_value) != force_unicode(data_value):
return True
return False
"""
Helios URLs for Election related stuff
Ben Adida (ben@adida.net)
"""
from django.conf.urls.defaults import *
from helios.views import *
urlpatterns = patterns('',
(r'^$', one_election),
# edit election params
(r'^/edit$', one_election_edit),
(r'^/schedule$', one_election_schedule),
# adding trustees
(r'^/trustees/$', list_trustees),
(r'^/trustees/view$', list_trustees_view),
(r'^/trustees/new$', new_trustee),
(r'^/trustees/add-helios$', new_trustee_helios),
(r'^/trustees/delete$', delete_trustee),
# trustee pages
(r'^/trustees/(?P<trustee_uuid>[^/]+)/home$', trustee_home),
(r'^/trustees/(?P<trustee_uuid>[^/]+)/sendurl$', trustee_send_url),
(r'^/trustees/(?P<trustee_uuid>[^/]+)/keygenerator$', trustee_keygenerator),
(r'^/trustees/(?P<trustee_uuid>[^/]+)/check-sk$', trustee_check_sk),
(r'^/trustees/(?P<trustee_uuid>[^/]+)/upoad-pk$', trustee_upload_pk),
(r'^/trustees/(?P<trustee_uuid>[^/]+)/decrypt-and-prove$', trustee_decrypt_and_prove),
(r'^/trustees/(?P<trustee_uuid>[^/]+)/upload-decryption$', trustee_upload_decryption),
# election voting-process actions
(r'^/view$', one_election_view),
(r'^/result$', one_election_result),
(r'^/result_proof$', one_election_result_proof),
(r'^/bboard$', one_election_bboard),
(r'^/audited-ballots/$', one_election_audited_ballots),
# server-side encryption
(r'^/encrypt-ballot$', encrypt_ballot),
# construct election
(r'^/questions$', one_election_questions),
(r'^/set_reg$', one_election_set_reg),
(r'^/set_featured$', one_election_set_featured),
(r'^/save_questions$', one_election_save_questions),
(r'^/register$', one_election_register),
(r'^/freeze$', one_election_freeze), # includes freeze_2 as POST target
# computing tally
(r'^/compute_tally$', one_election_compute_tally),
(r'^/combine_decryptions$', combine_decryptions),
# casting a ballot before we know who the voter is
(r'^/cast$', one_election_cast),
(r'^/cast_confirm$', one_election_cast_confirm),
(r'^/cast_done$', one_election_cast_done),
# post audited ballot
(r'^/post-audited-ballot', post_audited_ballot),
# managing voters
(r'^/voters/$', voter_list),
(r'^/voters/upload$', voters_upload),
(r'^/voters/list$', voters_list_pretty),
(r'^/voters/search$', voters_search),
(r'^/voters/email$', voters_email),
(r'^/voters/(?P<voter_uuid>[^/]+)$', one_voter),
(r'^/voters/(?P<voter_uuid>[^/]+)/delete$', voter_delete),
# ballots
(r'^/ballots/$', ballot_list),
(r'^/ballots/(?P<voter_uuid>[^/]+)/all$', voter_votes),
(r'^/ballots/(?P<voter_uuid>[^/]+)/last$', voter_last_vote),
)
from time import strptime, strftime
import datetime
from django import forms
from django.db import models
from django.forms import fields
from widgets import SplitSelectDateTimeWidget
class SplitDateTimeField(fields.MultiValueField):
widget = SplitSelectDateTimeWidget
def __init__(self, *args, **kwargs):
"""
Have to pass a list of field types to the constructor, else we
won't get any data to our compress method.
"""
all_fields = (fields.DateField(), fields.TimeField())
super(SplitDateTimeField, self).__init__(all_fields, *args, **kwargs)
def compress(self, data_list):
"""
Takes the values from the MultiWidget and passes them as a
list to this function. This function needs to compress the
list into a single object to save.
"""
if data_list:
if not (data_list[0] and data_list[1]):
raise forms.ValidationError("Field is missing data.")
return datetime.datetime.combine(*data_list)
return None
"""
Forms for Helios
"""
from django import forms
from models import Election
from widgets import *
from fields import *
class ElectionForm(forms.Form):
short_name = forms.SlugField(max_length=25, help_text='no spaces, will be part of the URL for your election, e.g. my-club-2010')
name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'size':60}), help_text='the pretty name for your election, e.g. My Club 2010 Election')
description = forms.CharField(max_length=2000, widget=forms.Textarea(attrs={'cols': 70, 'wrap': 'soft'}))
use_voter_aliases = forms.BooleanField(required=False, initial=False, help_text='if selected, voter identities will be replaced with aliases, e.g. "V12", in the ballot tracking center')
class ElectionTimesForm(forms.Form):
# times
voting_starts_at = SplitDateTimeField(help_text = 'UTC date and time when voting begins',
widget=SplitSelectDateTimeWidget)
voting_ends_at = SplitDateTimeField(help_text = 'UTC date and time when voting ends',
widget=SplitSelectDateTimeWidget)
class EmailVotersForm(forms.Form):
subject = forms.CharField(max_length=80)
body = forms.CharField(max_length=2000, widget=forms.Textarea)
"""
Management commands for Helios
many of these should be run out of cron
"""
"""
commands
"""
"""
decrypt elections where Helios is trustee
DEPRECATED
Ben Adida
ben@adida.net
2010-05-22
"""
from django.core.management.base import BaseCommand, CommandError
import csv, datetime
from helios import utils as helios_utils
from helios.models import *
class Command(BaseCommand):
args = ''
help = 'decrypt elections where helios is the trustee'
def handle(self, *args, **options):
# query for elections where decryption is ready to go and Helios is the trustee
active_helios_trustees = Trustee.objects.exclude(secret_key = None).exclude(election__encrypted_tally = None).filter(decryption_factors = None)
# for each one, do the decryption
for t in active_helios_trustees:
tally = t.election.encrypted_tally
# FIXME: this should probably be in the encrypted_tally getter
tally.init_election(t.election)
factors, proof = tally.decryption_factors_and_proofs(t.secret_key)
t.decryption_factors = factors
t.decryption_proofs = proof
t.save()
"""
parse and set up voters from uploaded voter files
DEPRECATED
Ben Adida
ben@adida.net
2010-05-22
"""
from django.core.management.base import BaseCommand, CommandError
import csv, datetime
from helios import utils as helios_utils
from helios.models import *
##
## UTF8 craziness for CSV
##
def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
def process_csv_file(election, f):
reader = unicode_csv_reader(f)
num_voters = 0
for voter in reader:
# bad line
if len(voter) < 1:
continue
num_voters += 1
voter_id = voter[0]
name = voter_id
email = voter_id
if len(voter) > 1:
email = voter[1]
if len(voter) > 2:
name = voter[2]
# create the user
user = User.update_or_create(user_type='password', user_id=voter_id, info = {'password': helios_utils.random_string(10), 'email': email, 'name': name})
user.save()
# does voter for this user already exist
voter = Voter.get_by_election_and_user(election, user)
# create the voter
if not voter:
voter_uuid = str(uuid.uuid1())
voter = Voter(uuid= voter_uuid, voter_type = 'password', voter_id = voter_id, name = name, election = election)
voter.save()
return num_voters
class Command(BaseCommand):
args = ''
help = 'load up voters from unprocessed voter files'
def handle(self, *args, **options):
# load up the voter files in order of last uploaded
files_to_process = VoterFile.objects.filter(processing_started_at=None).order_by('uploaded_at')
for file_to_process in files_to_process:
# mark processing begins
file_to_process.processing_started_at = datetime.datetime.utcnow()
file_to_process.save()
num_voters = process_csv_file(file_to_process.election, file_to_process.voter_file)
# mark processing done
file_to_process.processing_finished_at = datetime.datetime.utcnow()
file_to_process.num_voters = num_voters
file_to_process.save()
"""
verify cast votes that have not yet been verified
Ben Adida
ben@adida.net
2010-05-22
"""
from django.core.management.base import BaseCommand, CommandError
import csv, datetime
from helios import utils as helios_utils
from helios.models import *
def get_cast_vote_to_verify():
# fixme: add "select for update" functionality here
votes = CastVote.objects.filter(verified_at=None, invalidated_at=None).order_by('-cast_at')
if len(votes) > 0:
return votes[0]
else:
return None
class Command(BaseCommand):
args = ''
help = 'verify votes that were cast'
def handle(self, *args, **options):
while True:
cast_vote = get_cast_vote_to_verify()
if not cast_vote:
break
cast_vote.verify_and_store()
# once broken out of the while loop, quit and wait for next invocation
# this happens when there are no votes left to verify
helios/media/css/ui-lightness/images/ui-bg_diagonals-thick_18_b81900_40x40.png

260 B

0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment