def authenticate(request):
    #TODO timing attack to discover usernames
    username = str(request.POST["username"])
    password = str(request.POST["password"])
    if not re.match("^\w{3,16}$", username):
        return HttpResponseForbidden("username needs to have between 3-16 alphanumeric or underscore characters")
    #print str(username)
    bylogin = Person.objects.filter(login = str(username))
    badluck = HttpResponseForbidden("wrong username/password")
    if bylogin:
        if len(bylogin) == 1:
            userrecord = bylogin[0]
            observed = hmachash(password, userrecord.salt)
            expected = userrecord.hashedPassword
            if observed != expected:
                return badluck
            else:
                randombytes = rand256hex()
                token = Tokena(value = randombytes, active = True, belongs_to = userrecord, created=datetime.datetime.utcnow())
                token.save()
                response = HttpResponse(status = 200)
                response.set_cookie("tokena", value=randombytes, httponly=True)
                return response
        else:
            return HttpResponseServerError("couldn't authenticate the user, username non-ambiguous.")
    else:
        return badluck
def magic(request):
    p1 = Person(login = "******", hashedPassword = "******")
    p1.save()
    k1 = Tokena(value = "please come in", active = True, belongs_to = p1, created=datetime.datetime.utcnow())
    k1.save()
    k2 = Tokena(value = "you're not welcome", active = False, belongs_to = p1, created=datetime.datetime.utcnow())
    k2.save()
    print k1
    print k2
    return HttpResponse("nice", RequestContext(request))