1 | from DateTime import DateTime |
---|
2 | |
---|
3 | from zope.interface import Interface, Invalid |
---|
4 | from zope.component import adapts |
---|
5 | from zope.i18n import MessageFactory |
---|
6 | |
---|
7 | from Products.CMFCore.utils import getToolByName |
---|
8 | |
---|
9 | from quintagroup.plonecaptchas.utils import decrypt, parseKey, encrypt1, getWord |
---|
10 | |
---|
11 | from z3c.form.validator import SimpleFieldValidator |
---|
12 | |
---|
13 | from interfaces import ICaptcha |
---|
14 | |
---|
15 | _ = MessageFactory('quintagroup.z3cform.captcha') |
---|
16 | |
---|
17 | class CaptchaValidator(SimpleFieldValidator): |
---|
18 | """Captcha validator""" |
---|
19 | |
---|
20 | adapts(Interface, Interface, Interface, ICaptcha, Interface) |
---|
21 | |
---|
22 | def validate(self, value): |
---|
23 | # Verify the user input against the captcha |
---|
24 | errors = () |
---|
25 | context = self.context |
---|
26 | request = self.request |
---|
27 | value = value or '' |
---|
28 | captcha_type = context.getCaptchaType() |
---|
29 | if captcha_type in ['static', 'dynamic']: |
---|
30 | hashkey = request.get('%shashkey' % self.widget.form.prefix, '') |
---|
31 | decrypted_key = decrypt(context.captcha_key, hashkey) |
---|
32 | parsed_key = parseKey(decrypted_key) |
---|
33 | |
---|
34 | index = parsed_key['key'] |
---|
35 | date = parsed_key['date'] |
---|
36 | |
---|
37 | if captcha_type == 'static': |
---|
38 | img = getattr(context, '%s.jpg' % index) |
---|
39 | solution = img.title |
---|
40 | enc = encrypt1(value) |
---|
41 | else: |
---|
42 | enc = value |
---|
43 | solution = getWord(int(index)) |
---|
44 | |
---|
45 | captcha_tool = getToolByName(context, 'portal_captchas') |
---|
46 | if (enc != solution) or (captcha_tool.has_key(decrypted_key)) or (DateTime().timeTime() - float(date) > 3600): |
---|
47 | raise ValueError(_(u'Please re-enter validation code.')) |
---|
48 | else: |
---|
49 | captcha_tool.addExpiredKey(decrypted_key) |
---|