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