class CaptchaStore(models.Model):
id = models.AutoField(primary_key=True)
challenge = models.CharField(blank=False, max_length=32)
response = models.CharField(blank=False, max_length=32)
hashkey = models.CharField(blank=False, max_length=40, unique=True)
expiration = models.DateTimeField(blank=False)
def save(self, *args, **kwargs):
self.response = self.response.lower()
if not self.expiration:
self.expiration = timezone.now() + datetime.timedelta(
minutes=int(captcha_settings.CAPTCHA_TIMEOUT)
)
if not self.hashkey:
key_ = (
smart_text(randrange(0, MAX_RANDOM_KEY))
+ smart_text(time.time())
+ smart_text(self.challenge, errors="ignore")
+ smart_text(self.response, errors="ignore")
).encode("utf8")
self.hashkey = hashlib.sha1(key_).hexdigest()
del key_
super(CaptchaStore, self).save(*args, **kwargs)
def __str__(self):
return self.challenge
def remove_expired(cls):
cls.objects.filter(expiration__lte=timezone.now()).delete()
remove_expired = classmethod(remove_expired)
@classmethod
def generate_key(cls, generator=None):
challenge, response = captcha_settings.get_challenge(generator)()
store = cls.objects.create(challenge=challenge, response=response)
return store.hashkey