Tuesday, October 21, 2008

Rails Captcha

I just finished a lot of improvement on the custom Captcha implementation I use on all my websites. Right now the captcha protects comment forms and user profiles to prevent abuse by spammers, and it's very effective. Spammers obviously can't post spam without actually reading and interpreting my images as letters, or without having access to my MySQL database.

How It Works
The design for my custom captcha for rails is simple enough. Whenever the user request a page displaying a captcha-protected form, a captcha object is created in the database, which has a randomly generated private key, and I use it's id number as the public key. If the inputter does not submit the correct private key along with the public key (which is stored in a hidden value on the form), then they are given an error message. The user can see the private key, if they are a human, through a gif image which includes the letters A-L as part of the 5-digit key. The letters are blurred a little using a few RMagick functions and a few calls to random, and then the resulting image is given through rails in response to a .gif format request.

My improvements recently were rather simple. I first realized I had way too much code in the controller, and I moved most of it to methods in the Captcha.rb model method. Then I used a collect function and some loops to simplify things that were repeated, trying to follow along with DRY principals. Now I'm pretty sure that the program runs a little smoother and bugs will be easier to iron out.