def validate(self, value): # Verify the user input against the captcha # Captcha validation is one-time process to prevent hacking # This is the reason for in-line validation to be disabled. if detectInlineValidation(inline_validation): return context = self.context request = self.request value = value or '' captcha_type = context.getCaptchaType() if captcha_type in ['static', 'dynamic']: hashkey = request.get('%shashkey' % self.widget.form.prefix, '') decrypted_key = decrypt(context.captcha_key, hashkey) parsed_key = parseKey(decrypted_key) index = parsed_key['key'] date = parsed_key['date'] if captcha_type == 'static': img = getattr(context, '%s.jpg' % index) solution = img.title enc = encrypt1(value) else: enc = value solution = getWord(int(index)) captcha_tool = getToolByName(context, 'portal_captchas') captcha_tool_has_key = captcha_tool.has_key if (enc != solution) or (captcha_tool_has_key(decrypted_key)) or \ (DateTime().timeTime() - float(date) > 3600): raise ValueError(_(u'Please re-enter validation code.')) else: captcha_tool.addExpiredKey(decrypted_key)
def validate(self, value): # Verify the user input against the captcha errors = () context = self.context request = self.request value = value or '' captcha_type = context.getCaptchaType() if captcha_type in ['static', 'dynamic']: hashkey = request.get('%shashkey' % self.widget.form.prefix, '') decrypted_key = decrypt(context.captcha_key, hashkey) parsed_key = parseKey(decrypted_key) index = parsed_key['key'] date = parsed_key['date'] if captcha_type == 'static': img = getattr(context, '%s.jpg' % index) solution = img.title enc = encrypt1(value) else: enc = value solution = getWord(int(index)) captcha_tool = getToolByName(context, 'portal_captchas') if (enc != solution) or (captcha_tool.has_key(decrypted_key)) or (DateTime().timeTime() - float(date) > 3600): raise ValueError(_(u'Please re-enter validation code.')) else: captcha_tool.addExpiredKey(decrypted_key)
def testSubmitRightCaptcha(self): decrypted = decrypt(self.captcha_key, self.hashkey) key = getWord(int(parseKey(decrypted)['key']) - 1) try: self.validator.validate(key) except ConversionError, e: self.fail("Rised unexpected %s error on right captcha submit" % e)
def testSubmitRightCaptcha(self): key = getWord(int(parseKey(decrypt(self.captcha_key, self.hashkey))['key']) - 1) self.form_data['key'] = key response = self.publishForm().getBody() self.assertFalse(NOT_VALID.search(response))
def testSubmitRightCaptcha(self): decrypted = decrypt(self.captcha_key, self.hashkey) key = getWord(int(parseKey(decrypted)['key']) - 1) try: res = self.widget._toFieldValue(key) except ConversionError, e: self.fail("Rised unexpected %s error on right captcha submit" % e.doc())
def testSubmitRightCaptchaTwice(self): decrypted = decrypt(self.captcha_key, self.hashkey) key = getWord(int(parseKey(decrypted)['key']) - 1) self.widget._toFieldValue(key) try: self.widget._toFieldValue(key) except ConversionError, e: self.assertEqual(e.doc(), u'Please re-enter validation code.')
def testSubmitRightCaptcha(self): decrypted = decrypt(self.captcha_key, self.hashkey) key = getWord(int(parseKey(decrypted)['key']) - 1) try: res = self.widget._toFieldValue(key) except ConversionError, e: self.fail("Rised unexpected %s error on right captcha submit" % e.doc())
def testSubmitRightCaptchaTwice(self): decrypted = decrypt(self.captcha_key, self.hashkey) key = getWord(int(parseKey(decrypted)['key']) - 1) self.validator.validate(key) try: self.validator.validate(key) except ValueError, e: self.assertEqual(str(e), u'Please re-enter validation code.')
def testSubmitRightCaptchaTwice(self): decrypted = decrypt(self.captcha_key, self.hashkey) key = getWord(int(parseKey(decrypted)['key']) - 1) self.widget._toFieldValue(key) try: self.widget._toFieldValue(key) except ConversionError, e: self.assertEqual(e.doc(), u'Please re-enter validation code.')
def afterSetUp(self): # prepare context self.loginAsPortalOwner() testPatch() addTestLayer(self) # prepare captcha data captcha_key = self.portal.captcha_key self.hashkey = self.portal.getCaptcha() decrypted = decrypt(captcha_key, self.hashkey) self.captcha_word = getWord(int(parseKey(decrypted)['key']) - 1)
def testSubmitRightCaptchaTwice(self): key = getWord(int(parseKey(decrypt(self.captcha_key, self.hashkey))['key']) - 1) self.form_data[self.formkey_key] = key response1 = self.publishForm().getBody() self.elog("right1", response1) response2 = self.publishForm().getBody() self.elog("right2", response2) self.assertTrue(NOT_VALID.search(response2))
def afterSetUp(self): # prepare context self.loginAsPortalOwner() testPatch() addTestLayer(self) # prepare captcha data captcha_key = self.portal.captcha_key self.hashkey = self.portal.getCaptcha() decrypted = decrypt(captcha_key, self.hashkey) self.captcha_word = getWord(int(parseKey(decrypted)['key']) - 1)
def testSubmitRightCaptchaTwice(self): hashkey = self.portal.getCaptcha() decrypted_key = decrypt(self.captcha_key, hashkey) key = getWord(int(parseKey(decrypted_key)["key"]) - 1) parameters = "form.submitted=1&key=%s" % key path = "%s/test_form?%s" % (self.absolute_url, parameters) extra = {"hashkey": hashkey, "form.button.Save": "Save"} self.publish(path, self.basic_auth, extra=extra, request_method="GET") response = self.publish(path, self.basic_auth, extra=extra, request_method="GET").getBody() self.assert_(NOT_VALID.search(response))
def test_GetCaptcha_Key(self): decrypted_key = decrypt(self.captcha_key, self.hashkey) parsed_key = parseKey(decrypted_key) # *key* must present after parsing decrypted key self.assertTrue('key' in parsed_key.keys()) # index start from 1 and lower or equals to CAPTCHAS_COUNT index = int(parsed_key['key']) self.assertTrue(index >= 1 and index <= CAPTCHAS_COUNT) # encrypted key must be equals to title of the image key = getWord(index - 1) img = getattr(self.portal, '%s.jpg' % index) self.assertTrue(encrypt1(key) == img.title)
def test_GetCaptcha_Key(self): decrypted_key = decrypt(self.captcha_key, self.hashkey) parsed_key = parseKey(decrypted_key) # *key* must present after parsing decrypted key self.assertTrue('key' in parsed_key.keys()) # index start from 1 and lower or equals to CAPTCHAS_COUNT index = int(parsed_key['key']) self.assertTrue(index >= 1 and index <= CAPTCHAS_COUNT) # encrypted key must be equals to title of the image key = getWord(index - 1) img = getattr(self.portal, '%s.jpg' % index) self.assertTrue(encrypt1(key) == img.title)
def testGoodData(self): hashkey = self.portal.getCaptcha() decrypted_key = decrypt(self.captcha_key, hashkey) key = getWord(int(parseKey(decrypted_key)['key']) - 1) self.req.form['hashkey'] = hashkey self.req.form['key'] = key + '1' cstate = self.pfc.validate(self.dummycs, self.req, ['captcha_validator', ]) error_msg = 'Please re-enter validation code.' self.assertTrue(cstate.getErrors()['key'] == error_msg, "Static captcha validator validate wrong key")
def test_GetCaptcha_Key(self): decrypted_key = decrypt(self.captcha_key, self.hashkey) parsed_key = parseKey(decrypted_key) # *key* must present after parsing decrypted key self.assertTrue('key' in parsed_key.keys()) # index start from 0 and lower or equals to captchas count index = int(parsed_key['key']) words = utils.basic_english.words.split() self.assertTrue(index >= 0 and index <= len(words)) # encrypted key must be equals to word from the dictionary, # under index position and must be not empty string self.assertFalse(getWord(index) == "")
def test_GetCaptcha_Key(self): decrypted_key = decrypt(self.captcha_key, self.hashkey) parsed_key = parseKey(decrypted_key) # *key* must present after parsing decrypted key self.assertTrue('key' in parsed_key.keys()) # index start from 0 and lower or equals to captchas count index = int(parsed_key['key']) words = utils.basic_english.words.split() self.assertTrue(index >= 0 and index <= len(words)) # encrypted key must be equals to word from the dictionary, # under index position and must be not empty string self.assertFalse(getWord(index) == "")
def testGoodData(self): hashkey = self.portal.getCaptcha() decrypted_key = decrypt(self.captcha_key, hashkey) key = getWord(int(parseKey(decrypted_key)['key']) - 1) self.req.form['hashkey'] = hashkey self.req.form['key'] = key + '1' cstate = self.pfc.validate(self.dummycs, self.req, [ 'captcha_validator', ]) error_msg = 'Please re-enter validation code.' self.assertTrue(cstate.getErrors()['key'] == error_msg, "Static captcha validator validate wrong key")
def testSubmitRightCaptchaTwice(self): hashkey = self.portal.getCaptcha() decrypted_key = decrypt(self.captcha_key, hashkey) key = getWord(int(parseKey(decrypted_key)['key']) - 1) parameters = 'form.submitted=1&key=%s' % key path = '%s/test_form?%s' % (self.absolute_url, parameters) extra = {'hashkey': hashkey, 'form.button.Save': 'Save'} self.publish(path, self.basic_auth, extra=extra, request_method='GET') response = self.publish(path, self.basic_auth, extra=extra, request_method='GET').getBody() self.assert_(NOT_VALID.search(response))
def test_GetImage(self): # getCaptchaImage function must return image coded in hashkey same to # image get by 'key' after parsing decrypted key req, resp = self.app.REQUEST, self.app.REQUEST.RESPONSE decrypted_key = decrypt(self.captcha_key, self.hashkey) parsed_key = parseKey(decrypted_key) img = self.portal.restrictedTraverse(parsed_key['key'] + '.jpg') img_html = img.index_html(req, resp) portal = self.portal.absolute_url(1) captcha_path = portal + "/getCaptchaImage/%s" % self.hashkey obj_html = self.publish(captcha_path).getBody() msg = "Image get by getCaptchaImage script is differ from"\ "image get by index (after parsing decrypted key)" self.assertTrue(obj_html == img_html, msg)
def test_GetImage(self): # getCaptchaImage function must return image coded in hashkey same to # image get by 'key' after parsing decrypted key req, resp = self.app.REQUEST, self.app.REQUEST.RESPONSE decrypted_key = decrypt(self.captcha_key, self.hashkey) parsed_key = parseKey(decrypted_key) img = self.portal.restrictedTraverse(parsed_key['key'] + '.jpg') img_html = img.index_html(req, resp) portal = self.portal.absolute_url(1) captcha_path = portal + "/getCaptchaImage/%s" % self.hashkey obj_html = self.publish(captcha_path).getBody() msg = "Image get by getCaptchaImage script is differ from"\ "image get by index (after parsing decrypted key)" self.assertTrue(obj_html == img_html, msg)
def testBadDate(self): # First path DateTime to get old dated hash origDTTT = DateTime.timeTime now = DateTime().timeTime() DateTime.timeTime = lambda s: now - float(3601) hashkey = self.portal.getCaptcha() decrypted_key = decrypt(self.captcha_key, hashkey) key = getWord(int(parseKey(decrypted_key)['key']) - 1) self.req.form['hashkey'] = hashkey self.req.form['key'] = key # Return original Date DateTime.timeTime = origDTTT cstate = self.pfc.validate(self.dummycs, self.req, ['captcha_validator', ]) error_msg = 'Please re-enter validation code.' self.assertTrue(cstate.getErrors()['key'] == error_msg, "Static captcha validator validate wrong key")
def _toFieldValue(self, input): # Captcha validation is one-time process to prevent hacking # This is the reason for in-line validation to be disabled. if inline_validation and detectInlineValidation(inline_validation): return super(CaptchaWidget, self)._toFieldValue(input) # Verify the user input against the captcha. # Get captcha type (static or dynamic) site = self.get_site() captcha_type = site.getCaptchaType() # validate captcha input if input and captcha_type in ['static', 'dynamic']: # make up form prefix if self._prefix: prefix = '%s.' % self._prefix else: prefix = '' hashkey = self.request.get('%shashkey' % prefix, '') decrypted_key = decrypt(site.captcha_key, hashkey) parsed_key = parseKey(decrypted_key) index = parsed_key['key'] date = parsed_key['date'] if captcha_type == 'static': img = getattr(site, '%s.jpg' % index) solution = img.title enc = encrypt1(input) else: enc = input solution = getWord(int(index)) captcha_tool = getToolByName(site, 'portal_captchas') if (enc != solution) or (decrypted_key in captcha_tool.keys()) or \ (DateTime().timeTime() - float(date) > 3600): raise ConversionError(_(u'Please re-enter validation code.')) else: captcha_tool.addExpiredKey(decrypted_key) return super(CaptchaWidget, self)._toFieldValue(input)
def testBadDate(self): # First path DateTime to get old dated hash origDTTT = DateTime.timeTime now = DateTime().timeTime() DateTime.timeTime = lambda s: now - float(3601) hashkey = self.portal.getCaptcha() decrypted_key = decrypt(self.captcha_key, hashkey) key = getWord(int(parseKey(decrypted_key)['key']) - 1) self.req.form['hashkey'] = hashkey self.req.form['key'] = key # Return original Date DateTime.timeTime = origDTTT cstate = self.pfc.validate(self.dummycs, self.req, [ 'captcha_validator', ]) error_msg = 'Please re-enter validation code.' self.assertTrue(cstate.getErrors()['key'] == error_msg, "Static captcha validator validate wrong key")
def _toFieldValue(self, input): # Verify the user input against the captcha context = self.context.context request = context.REQUEST # get captcha type (static or dynamic) captcha_type = context.getCaptchaType() # validate captcha input if input and captcha_type in ['static', 'dynamic']: # make up form prefix if self._prefix: prefix = '%s.' % self._prefix else: prefix = '' hashkey = request.get('%shashkey' % prefix, '') decrypted_key = decrypt(context.captcha_key, hashkey) parsed_key = parseKey(decrypted_key) index = parsed_key['key'] date = parsed_key['date'] if captcha_type == 'static': img = getattr(context, '%s.jpg' % index) solution = img.title enc = encrypt1(input) else: enc = input solution = getWord(int(index)) captcha_tool = getToolByName(context, 'portal_captchas') if (enc != solution) or (captcha_tool.has_key(decrypted_key)) or (DateTime().timeTime() - float(date) > 3600): raise ConversionError(_(u'Please re-enter validation code.')) else: captcha_tool.addExpiredKey(decrypted_key) return super(CaptchaWidget, self)._toFieldValue(input)
## Script (Python) "getCaptchaImage" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters= ##title= from quintagroup.captcha.core.utils import decrypt, parseKey try: hk = context.REQUEST.traverse_subpath[0] except IndexError: return try: dk = decrypt(context.captcha_key, hk) except: return key = parseKey(dk)['key'] try: img = getattr(context, '%s.jpg' % key) except AttributeError: return return img.index_html(context.REQUEST, context.REQUEST.RESPONSE)
def test_GetCaptcha_Date(self): # *date* must present after parsing decrypted key decrypted_key = decrypt(self.captcha_key, self.hashkey) parsed_key = parseKey(decrypted_key) self.assertTrue('date' in parsed_key.keys())
def test_GetCaptcha_Date(self): # *date* must present after parsing decrypted key decrypted_key = decrypt(self.captcha_key, self.hashkey) parsed_key = parseKey(decrypted_key) self.assertTrue('date' in parsed_key.keys())
def __call__(self, emailaddress, name=''): """ helper method to enable osh mail subscription to anonymous user """ reg_tool = getToolByName(self.context, 'portal_registration') host = getToolByName(self.context, 'MailHost') REQUEST = self.request if not emailaddress: emailaddress = REQUEST.get('emailaddress', '') refererstem = REQUEST.get('HTTP_REFERER').split('?')[0] referer = refererstem + '?' qs = REQUEST.get('QUERY_STRING', '') if qs: referer += '?' + qs + '&' if not reg_tool.isValidEmail(emailaddress): msg = _(u'You did not enter a valid email address.') referer += "err=email&msg=%s&" % msg return REQUEST.RESPONSE.redirect(referer) # validate captcha test_key = REQUEST.get('key', '') hashkey = REQUEST.get('hashkey', '') decrypted_key = decrypt(self.context.captcha_key, hashkey) parsed_key = parseKey(decrypted_key) index = parsed_key['key'] date = parsed_key['date'] if REQUEST.has_key('unsubscribe'): return REQUEST.RESPONSE.redirect( self.context.absolute_url() + "/confirm-unsubscription?emailaddress=%s" % (emailaddress)) img = getattr(self.context, '%s.jpg' % index) solution = img.title enc = encrypt1(test_key) captcha_tool = getToolByName(self.context, 'portal_captchas') if (enc != solution) or (captcha_tool.has_key(decrypted_key)) \ or (DateTime().timeTime() - float(date) > 3600): msg = _(u"Please re-enter validation code.") referer += "err=captcha&msg={msg}&emailaddress={emailaddress}&".format( msg=msg, emailaddress=emailaddress) return REQUEST.RESPONSE.redirect(referer) else: captcha_tool.addExpiredKey(decrypted_key) mesg = "subscribe OSHMail anonymous\n" mssg = _( "Thank you for subscribing to the OSHmail newsletter. You will " "receive an email to confirm your subscription.") recipient = '*****@*****.**' sender = emailaddress if name: sender = "%s <%s>" % (name, sender) subject = '' try: host.send(mesg, mto=recipient, mfrom=sender, subject=subject) except Exception, e: mssg = _("Your subscription could not be sent. Please try again.") mssg = u"%s %s" % (mssg, e)
def __call__(self, emailaddress, name=''): """ helper method to enable osh mail subscription to anonymous user """ reg_tool = getToolByName(self.context, 'portal_registration') host = getToolByName(self.context, 'MailHost') REQUEST = self.request if not emailaddress: emailaddress = REQUEST.get('emailaddress', '') refererstem = REQUEST.get('HTTP_REFERER').split('?')[0] referer = refererstem + '?' qs = REQUEST.get('QUERY_STRING', '') if qs: referer += '?' + qs + '&' if not reg_tool.isValidEmail(emailaddress): msg = _(u'You did not enter a valid email address.') referer += "err=email&msg=%s&" % msg return REQUEST.RESPONSE.redirect(referer) # validate captcha test_key = REQUEST.get('key', '') hashkey = REQUEST.get('hashkey', '') decrypted_key = decrypt(self.context.captcha_key, hashkey) parsed_key = parseKey(decrypted_key) index = parsed_key['key'] date = parsed_key['date'] if REQUEST.has_key('unsubscribe'): return REQUEST.RESPONSE.redirect( self.context.absolute_url() + "/confirm-unsubscription?emailaddress=%s" % (emailaddress)) img = getattr(self.context, '%s.jpg' % index) solution = img.title enc = encrypt1(test_key) captcha_tool = getToolByName(self.context, 'portal_captchas') if (enc != solution) or (captcha_tool.has_key(decrypted_key)) \ or (DateTime().timeTime() - float(date) > 3600): msg = _(u"Please re-enter validation code.") referer += "err=captcha&msg={msg}&emailaddress={emailaddress}&".format( msg=msg, emailaddress=emailaddress) return REQUEST.RESPONSE.redirect(referer) else: captcha_tool.addExpiredKey(decrypted_key) mesg = "subscribe OSHMail anonymous\n" mssg = _( "Thank you for subscribing to the OSHmail newsletter. You will " "receive an email to confirm your subscription.") recipient = '*****@*****.**' sender = emailaddress if name: sender = "%s <%s>" % (name, sender) subject = '' try: host.send(mesg, mto=recipient, mfrom=sender, subject=subject) except Exception, e: mssg = _("Your subscription could not be sent. Please try again.") mssg = u"%s %s" %(mssg, e)