Exemple #1
0
 def validate(self, value):
     print '\n---- CaptchaEntity.validate:', value, self.value, self.created
     return (self.value.strip().lower() == value.strip().lower() and
         datetime.datetime.now() - self.created <= datetime.timedelta(minutes=app_conf('captcha-valid-minutes')))
Exemple #2
0
    def render(self):

        font_file = os.path.join(
             app_conf('captcha-font-path'),
             random.choice([font_file for font_file in os.listdir(app_conf('captcha-font-path')) if fnmatch.fnmatch(font_file, '*.ttf')]))
        font = ImageFont.truetype(font_file, app_conf('captcha-font-size'))

        text_color = random.choice([(190, 0, 0, 255), (37, 37, 37, 255), (0, 0, 127, 255)])

        size = font.getsize(self.captcha_entity.value)
        image = Image.new('RGBA', size, (0, 0, 0, 0))
        draw = ImageDraw.Draw(image)
        draw.text((0, 0), self.captcha_entity.value, font=font, fill=text_color)

        # deform begin

        project = lambda orig, dist: orig + random.randint(-1 * dist, dist)
  
        divisions = int(len(self.captcha_entity.value) / 1.5)
        distorsion = dict(x=app_conf('captcha-distortion-x'), y=app_conf('captcha-distortion-y'))

        # add margins

        margin_img_size = (
            image.size[0] + (2 * distorsion['x']),
            image.size[1] + (2 * distorsion['y']),
        )
        margins_img = Image.new('RGBA', margin_img_size, (0, 0, 0, 0))
        margins_img.paste(image, (distorsion['x'], distorsion['y']))
        image = margins_img

        # calculate distortion mesh

        last_projected_x = last_projected_y = 0
        mesh = []
        for pos in xrange(divisions + 1):
            x0 = image.size[0] / divisions * pos
            x1 = image.size[0] / divisions * (pos + 1)
            y0 = 0
            y1 = image.size[1]
  
            projected_x = project(x1, distorsion['x'])
            projected_y = project(y0, distorsion['y'])
  
            mesh.append((
                (x0, y0, x1, y1),
                (
                    last_projected_x, last_projected_y,
                    x0, y1,
                    x1, y1,
                    projected_x, projected_y,
                ),
            ))
            last_projected_x, last_projected_y = projected_x, projected_y

        image = image.transform(image.size, Image.MESH, mesh, Image.BICUBIC)
        image = image.crop(image.getbbox())

        # deform end

        stringio = StringIO.StringIO()
        image.save(stringio, 'PNG') #, quality=100) # TODO png quality?
        return (stringio.getvalue(), 'image/png')
Exemple #3
0
 def delete_expired(cls):
     stmt = "delete from captcha where current_timestamp - created > INTERVAL '%(valid_min)s min'" % dict(valid_min=app_conf('captcha-valid-minutes'))
     Session().connection().execute(stmt)# text(stmt))
     mark_changed(Session())