Howto use custom color for collective.captcha?

How to use your custom color with collective.captcha and Plone? This tutorial shows you an easy way to customize it using your own BrowserLayer.

collective.captcha uses a BrowserView to display it’s captcha image. Therefore it’s very easy to customize it for your own theme because you can subclass that BrowserView for your own theme layer which is a BrowserLayer. You can change colors and/or fonts as you need it for your custom theme without doing any code change on the original collective.captcha package.

You need to create a captcha.py in your theme product’s browser directory and register the new BrowserView for your IThemeSpecific layer in configure.zcml:

[your-namespace].[your-package]/[your-namespace]/[your-package]/browser/captcha.py

Aliases and package structure does should match plone’s standard filesystem structure: http://plone.org/documentation/manual/theme-reference/whereiswhat/productlocation.

BrowserView

The new customized BrowserView inherits from CaptchaView in collective.captcha package. We just have to override the image method which generates the captcha image.

captcha.py
from skimpyGimpy import skimpyAPI
from collective.captcha.browser import captcha

FONT = captcha.VERAMONO
COLOR = '#336699'

class Captcha(captcha.Captcha):

    def image(self):
        """Generate a captcha image"""
        self._setheaders('image/png')
        return skimpyAPI.Png(self._generate_words()[0],
                             fontpath=FONT, color=COLOR[1:],
                             speckle=1, scale=2.0).data()

skimpyAPI.Png expects the color value without a leading #, so lets strip it away by starting second character. After that code change lets open our configure.zcml file which should be located in browser directory to register the new captcha for our theme BrowserLayer.

ZCML

Extend your file configure.zcml which should be located in following directory:

[your-namespace].[your-package]/[your-namespace]/[your-package]/browser/configure.zcml

… with this <browser:view … /> statement:

<configure
    xmlns="http://namespaces.zope.org/zope"
    xmlns:browser="http://namespaces.zope.org/browser">

    <include package="collective.captcha" />

    <browser:view
        name="captcha"
        for="*"
        layer=".interfaces.IThemeSpecific"
        permission="zope2.Public"
        provides="collective.captcha.browser.interfaces.ICaptchaView"
        class=".captcha.Captcha">

        <browser:page name="image" attribute="image" />
        <browser:page name="audio" attribute="audio" />

    </browser:view>

</configure>

Restart your zope instance and your new captcha view should be used instead of the default one.

Comments

comments powered by Disqus