def get_captcha_image(request): """Return a captcha image. Can't think of a good way to tie IDs of generated images to the form input field Instead timestamp each and have a timeout checked on submission. User could potentially have a large array of captcha solutions per session. So will also cull the list here when it gets big. """ response = HttpResponse() response['Content-type'] = "image/png" g = PseudoGimpy() i = g.render() i.save(response, "png") safe_solutions = [sha1(s).hexdigest() for s in g.solutions] try: if len(request.session['captcha_solns']) > 100: for (sol, createtime) in request.session['captcha_solns']: if ((datetime.datetime.now() - createtime) > datetime.timedelta( seconds=settings.CAPTCHA_WINDOW_SEC)): request.session['captcha_solns'].remove((sol, createtime)) settings.LOG.debug( "Adding solution:%s to session, number of solutions stored: %s" % (safe_solutions, len(request.session['captcha_solns']))) request.session['captcha_solns'].append( (safe_solutions, datetime.datetime.now())) #Need explicit save here because we don't add a new element and #SESSION_SAVE_EVERY_REQUEST is false request.session.save() except KeyError: request.session['captcha_solns'] = [(safe_solutions, datetime.datetime.now())] return response
def captcha_image(request): # set the HttpResponse response = HttpResponse(mimetype='image/png') g = PseudoGimpy() i = g.render() i.save(response, 'png') solutions = g.solutions request.session[CAPTCHA_SOLUTIONS] = solutions return response
def serve_captcha(request): """Serve a random CAPTCHA image and remember the expected answer by storing it in the session. """ g = PseudoGimpy() answer_plain_text = g.solutions[0] enc = save_answer(request, answer_plain_text) response = HttpResponse(mimetype="image/png") im = g.render() im.save(response, "PNG", optimize=True) return response
def get_question(winograd_source='winograd.txt',dbpath=DBPATH): """Returns a question, and a token that can be used to check the user's answer. This token can't be reused (to avoid a replay attack)""" g = PseudoGimpy() i = g.render() w,h = i.getbbox()[2:] buff = StringIO.StringIO() i.save(buff,'png') return { 'token':_register_challenge(dbpath,g.solutions), 'imgsrc':'data:image/png;base64,'+buff.getvalue().encode('base64'), 'imgwidth':w,'imgheight':h}
def captcha_jpeg(context, request): site = find_site(context) output = StringIO() captcha = PseudoGimpy() image = captcha.render() image.save(output, 'JPEG') data = output.getvalue() browserid = request.environ.get('repoze.browserid') session = site.sessions.get(browserid) session['captcha_solutions'] = captcha.solutions r = Response(data, '200 OK', [ ('Content-Type', 'image/jpeg'), ('Content-Length', len(data)) ]) return r
def getChallenge(): """ Returns a string, which should be placed as a hidden field on a web form. This string identifies a particular challenge, and is needed later for: - retrieving the image file for viewing the challenge, via call to getImageData() - testing a response to the challenge, via call to testSolution() The format of the string is:: base64(id+":"+expirytime+":"+sha1(id, answer, expirytime, secret)) Where: - id is a pseudo-random id identifying this challenge instance, and used to locate the temporary file under which the image is stored - expirytime is unixtime in hex - answer is the plaintext string of the word on the challenge picture - secret is the secret signing key 'captchaSecretKey """ # get a CAPTCHA object g = PseudoGimpy() # retrieve text solution answer = g.solutions[0] # generate a unique id under which to save it id = _generateId(answer) # save the image to disk, so it can be delivered from the # browser's next request ## the new created image, ZG i = g.render() path = _getImagePath(id) f = file(path, "wb") i.save(f, "jpeg") f.close() # compute 'key' key = _encodeKey(id, answer) return key
def getChallenge(): """ Returns a string, which should be placed as a hidden field on a web form. This string identifies a particular challenge, and is needed later for: - retrieving the image file for viewing the challenge, via call to getImageData() - testing a response to the challenge, via call to testSolution() The format of the string is:: base64(id+":"+expirytime+":"+sha1(id, answer, expirytime, secret)) Where: - id is a pseudo-random id identifying this challenge instance, and used to locate the temporary file under which the image is stored - expirytime is unixtime in hex - answer is the plaintext string of the word on the challenge picture - secret is the secret signing key 'captchaSecretKey """ # get a CAPTCHA object g = PseudoGimpy() # retrieve text solution answer = g.solutions[0] # generate a unique id under which to save it id = _generateId(answer) # save the image to disk, so it can be delivered from the # browser's next request i = g.render() path = _getImagePath(id) f = file(path, "wb") i.save(f, "jpeg") f.close() # compute 'key' key = _encodeKey(id, answer) return key
def generarCaptcha(): """ @note: Función que permite generar la imagen del captcha y su correspondiente hash para su verificación @author: T.S.U. Roldan D. Vargas G. @contact: [email protected] @return: Retorna una lista con las variables a ser utilizadas para la generación del captcha """ random.seed("%d%s" % (os.getpid(), time.ctime())) g = PseudoGimpy() g.__init__() answer = g.solutions[0] id = _generateId(answer) i = g.render() captchaFile = os.path.join(settings.PATH, "tmp")+"/"+id+"Image.png" i.save(captchaFile) img = "<img src='/tmp/"+id+"Image.png' border='0' width='140px' height='40px' /> <img src='/media/images/base/reload.png' width='20px' height='20px' style='cursor:pointer' title='"+_(u"Pulse sobre el botón si desea recargar la imagen")+"' onclick='Dajax.usuario_reloadCaptcha();' />" SALT = settings.SECRET_KEY[:20] imgtext = answer imghash = hashlib.sha1(SALT+imgtext).hexdigest() Lista = [img,imghash,id] #logging.info(u"Nueva imagen de captcha generada") return Lista
#!/usr/bin/env python # # A very simple example that creates a random image from the # PseudoGimpy CAPTCHA, saves and shows it, and prints the list # of solutions. Normally you would call testSolutions rather # than reading this list yourself. # from Captcha.Visual.Tests import PseudoGimpy g = PseudoGimpy() i = g.render() i.save("output.png") #i.show() print g.solutions
#!/usr/bin/env python # # A very simple example that creates a random image from the # PseudoGimpy CAPTCHA, saves and shows it, and prints the list # of solutions. Normally you would call testSolutions rather # than reading this list yourself. # from Captcha.Visual.Tests import PseudoGimpy g = PseudoGimpy() i = g.render() i.save("output.png") i.show() print(g.solutions)