Simple Captcha 1.0

Update: SimpleCaptcha 1.2.2 is up!!

Major Changes…

FileSystem Usage Removed

Works Perfectly with Multiple Clustered Servers

Read Here for more details on implementation, usage and examples.


Filed in: captcha, plugin, rails, ruby, rubyonrails, validations

by: sur

160 Comments

Javascript Validations and Encryptions — how to use javascript encryptions in rails.

A Quick Review on ENCRYPTIONS
We all are very familiar with the ruby encryptions we usually implement SHA1 or MD5 in our rails applications. In my ongoing project i have been through encryptions in little bit more depth.
MD5 was the most widely used hash algorithm, it converts a string into a 32 characters long hashed key. Then comes the SHA - Secure Hash Algorith. SHA is a series of hash algorithms and its first member is SHA-0 however soon its usage was replaced by the successor SHA-1 and thereafter SHA-0 was never used again. The current members to the SHA series are SHA-1, SHA-224, SHA-256, SHA-384 and the latest SHA-512. At this moment SHA-1 is considered to be the successor of MD5 because of the usage and popularity statistics.
However SHA-224, SHA-256, SHA-384 and SHA-256 are collectively known as SHA-2 series.
Till yet SHA-0 and SHA-1 have been reported attacked but no attack has been found on SHA-2 series.(took from wiki)

Here we will discuss the javascript and ruby based encryptions for SHA-256 only.

Javascript Encryption in Ruby on Rails

If you need to encrypt the password at client side in ror or any other web-based form submission so that the real password string can not reach the server you can you can download the Javascript Encryption files from here. There is all collection of the javascript encryption files available in the above archive. You will not need all of them. Put the file sha256.js in the /public/javascripts/ directory of your rails application.
Now lets take the example of Reset Password where encryption is a must.
This is how you can make your view say reset_password.rhtml


<%= javascript_include_tag 'sha256' %>
<script type="text/javascript">
// <![CDATA[
  function hashPassword() {
  reg = new RegExp(/^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/);
  if((reg.test($F(’password’)))&&($F(’password’)==$F(’password_confirmation’))){
  document.reset_password.realpass.value = hex_sha256($F(’password’));
  $(’password_confirmation’).value = ”;
  $(’password’).value = ”;
  Element.hide(”reset_password”);
  Element.show(”updating”);
  return true
  }
  else{
  $(’errors_in_pass’).innerHTML = “Password should match confirmation.<br />Password should contain at least one letter and one integer.<br />Password length should be 8 to 40 characters long.<br />”;
  $(’password_confirmation’).value = ”;
  $(’password’).value = ”;
  return false
  }
  }
// ]]>
</script>
<h1>Change Password</h1>
<div style=”display:none;” id=”updating”>Updating Password</div>
<div id = “reset_password”>
<div style = “color:red” id = “errors_in_pass”><%= flash[:notice] %></div>
<% form_for :person, @person, :url => {:action => “reset_password”}, :html => {:name => “reset_password”,:onsubmit => “return hashPassword()”} do |f| %>
<%= hidden_field_tag ‘realpass’ %>
        New Password
        <%= f.password_field :password, :id=>”password”, :class => “field text”, :value=>”" %>
	Confirm New Password
        <%= f.password_field :password_confirmation, :id=>”password_confirmation”, :class => “field text”, :value=>”" %>
	<%= f.submit_tag “Continue” %>
<% end %>
</div>

However it may possible that a user have disabled the javascript of the browser. In that case we will need to add the encryption at server side too. In rubyonrails we can easily handle the SHA256 encryption for let say password by adding the code


require "digest/sha2"

hashed_password = Digest::SHA256.hexdigest("password_string")

in an appropriate position in the controller.

Filed in: encryption, javascript, ror, rubyonrails, validations

by: sur

No Comments

Captcha in Ruby on Rails - Customize the use of captcha in the plugin validates_captcha

Hello Everyone !!
I have released a captcha plugin Simple Captcha. It is really simple to implement, and provides a cool feature of multiple styles of images. Visit here for more explanation.


Previous post on validates_captcha

———————————————————

To implement captcha in RubyonRails, validates_captcha plugin can be a good option but a small customization i need with this plugin was to use it on some specific action and not to be validated the captcha field every time an instance of the model is saved or updated.
Here is a small work-around for its customization…
How to use customized captcha in RoR ?
Install the plugin validates_captcha in your rails application by running this command from the root of your application

ruby script/plugin install http://svn.2750flesk.com/validates_captcha

Make sure that you can now see the directory vedor/plugins/validates_captcha.

Now run these commands from your application root to make the image and data directories

  ruby script/generate captcha store_directory
  ruby script/generate captcha image_directory

Here is the complete API for the usage of this plugin. I am describing the same idea as given in this API but in a bit more specific means.

Lets consider a model User in which we will implement the captcha.
Add the following code in the file app/models/user.rb

  class User < ActiveRecord::Base

    validates_captcha :if => :request_captcha_validation?
    attr_accessor :request_captcha_validation

    def request_captcha_validation?
      (self.request_captcha_validation==true)? true : false
    end

  end

Handle View and Controller

Add the code in the view inside your existing form.

  <% c = prepare_captcha :type => :image -%>
  <%= captcha_hidden_field c, 'user' %>
  <%= captcha_image_tag c %>
  <%= captcha_label 'user', 'Type in the text from the image above' %>
  <%= captcha_text_field 'user' %>

Your controller will look like

  def save
    # the line in bold represents that you need captcha validation.
    # if captcha validation is not required then remove this line from your controller.
    @user = User.new(params[:user])
    @user.request_captcha_validation = true
    @user.save
  end

However image is too noisy and it contains repeated strings.
To improve the quality of images generated by the plugin validates_captcha visit Here.

Filed in: captcha, image, rails, ror, validations

by: sur

38 Comments

Using Regular Expression in Ruby on Rails — Regexp for Password Validation

A regular expression (abbreviated as regexp or regex, with plural forms regexps, regexes, or regexen) is a string that describes or matches a set of strings, according to certain syntax rules. Regular expressions are used by many text editors and utilities to search and manipulate bodies of text based on certain patterns. Many programming languages support regular expressions for string manipulation. Ruby has a strong Regular Expression engine built directly as a class of Ruby Programming language as Regexp
Here we will go through an example which will validate the password string.
Lets say we have to implement the following validations to validate a password…

  • Password should contain atleast one integer.
  • Password should contain atleast one alphabet(either in downcase or upcase).
  • Password can have special characters from 20 to 7E ascii values.
  • Password should be minimum of 8 and maximum of 40 cahracters long.

To fulfill above requirements we can have a regular expression like…

/^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/

in ruby programming language we can have a number of ways to define this regular expression as…
■ reg = Regexp.new(”^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$”)
or
■ reg = %r(^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$)
or simply
■ reg = /^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/

Now look what exactly this regex is doing…
(?=.*\d) shows that the string should contain atleast one integer.
(?=.*([a-z]|[A-Z])) shows that the string should contain atleast one alphabet either from downcase or upcase.
([\x20-\x7E]) shows that string can have special characters of ascii values 20 to 7E.
{8,40} shows that string should be minimum of 8 to maximum of 40 cahracters long.
We can simply use this regular expression for manual handling of password in an action as…

def validate_password(password)

  reg = /^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/

return (reg.match(password))? true : false

end

How to implement this regular expression in a model class in ruby on rails for password validation ?

To implement this regular expression in the model class in the rails way we can do it like…

class MyModel

  validates_format_of :password, :with => /^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/

end

Filed in: password, rails, regexp, validations

by: sur

1 Comment