Wednesday, 11 March 2015

Simple Captcha in Ruby On Rails

When your application has a form that's available to everyone for eg. Contact us, you will be spammed! So what can we do about it? Well, one option is to have all forms secured by authentication... OR we can use a captcha. So, Here is how you can implement your own simple captcha in Ruby on Rails,

First of all we will create Captcha class in lib folder,

Here we are dumping the variables into a string using YAML and then encrypt/decrypt.

Then in your Controller,

class ContactsController < ApplicationController

  def new
    @captcha =

  def create
    @captcha = Captcha.decrypt(params[:captcha_secret])

    unless @captcha.correct?(params[:captcha])[:alert] = "Please make sure you entered correct value for captcha."
      # Here we need to initialize @captcha with new object in order to show 
      # different captcha each time on form 
      @captcha =
      render :new
      flash[:notice] = "Your message has been sent successfully"
      redirect_to root_path

 In your view,

<div class="field">
  <%= hidden_field_tag :captcha_secret, @captcha.encrypt %>
  <%= label_tag :captcha, @captcha.question %>
  <%= text_field_tag :captcha, "" %>

That's it. And it will look similar to this,

Wednesday, 4 June 2014

Client side SSL Certificate Authentication with Rails and Nginx

     Recently i worked on one application which required SSL client certificate based authentication.
So just wanted to share it with you all about how it can be integrated in Rails application.This article is about using SSL certificates installed into a web browser to authenticate against a Ruby on Rails application with Nginx.

Steps for creating certificates,

1) First thing you will need is to configure openssl.cnf, check following gist for configuring your openssl.cnf , as its big file so cant embed here. 
In this configuration important thing is setting path to CA dir,
[ CA_default ]
dir = /path/to/ca
this is the path where you are going create your CA.

2) Then you will need to create your own CA(Certificate Authority) that issues Digital certificates.
For that we will use script is a perl script that supplies the relevant command line arguments to the openssl command for some common certificate operations. It is intended to simplify the process of certificate creation and management by the use of some simple options.
cd /path/to/ca -newca 
Make sure here you enter domain name in common name field when asked in this.

3) Now generate web server CSR
openssl req -new -nodes -keyout -out
then self sign web server Certificate
openssl ca -config /etc/openssl.cnf -policy policy_anything -out -infiles
that gives you web server certificates

4) Now its time to configure nginx server,

5) Generating Client certificate, 
CERT_DIR = "path/to/ca"
  user_name = "test user"
  id = 1

  def create_p12
    subj = "/C=US/ST=YourState/L=city/O=example/OU=example/CN=#{user_name})/emailAddress=#{email}"
    dir_name  = "#{CERT_DIR}#{id}"
    Dir.mkdir(dir_name) unless

  def create_cert(subj)
    system("openssl req -new -sha1 -newkey rsa:1024 -nodes -keyout #{CERT_DIR}#{id}/#{user_name}.key -out #{CERT_DIR}#{id}/#{user_name}.csr -subj '#{subj}'")

  def sign_cert
    system("openssl ca -batch -config /usr/lib/ssl/openssl.cnf -policy policy_anything -extensions ssl_client -out #{CERT_DIR}#{id}/#{user_name}.crt -infiles #{CERT_DIR}#{id}/#{user_name}.csr")

  def generate_p12
    system("openssl pkcs12 -export -clcerts -in #{CERT_DIR}#{id}/#{user_name}.crt -certfile #{CERT_DIR}demoCA/cacert.pem -inkey #{CERT_DIR}#{id}/#{user_name}.key -out #{CERT_DIR}#{id}/#{user_name}.p12 -name '#{name}' -passout pass:#{export_password} ")
Here ,
subj = "/C=US/ST=YourState/L=city/O=example/OU=example/CN=#{user_name})/emailAddress=#{email}"
is a subject for certificate which can be unique for each user or same based on settings in your openssl.cnf.

6) Install your certificate on web browser(p12 file), then hit url of website and it will ask to submit client certificate , just select required certificate from list and submit. Then in your controller you can get certificate using,
cert = request.env["HTTP_X_SSL_CLIENT_S_DN"]
 as we have initialized variable in nginx configuration.
proxy_set_header X-SSL-Client-S-DN   $ssl_client_cert 
You can check more options on

7) You can verify whether certificate submitted by user is valid or not , using
returns the result of client certificate verification: “SUCCESS”, “FAILED”, and “NONE” if a certificate was not present.

Wednesday, 22 January 2014

Transfer files over netcat using Applescript

    At my workplace me and one of my colleague used to transfer files like database dumps etc. for projects from one machine to another.
I came across netcat (nc command) and when we tried that it just worked so quickly, i got surprised with the speed with which it got transferred. :)
So i wrote applescript that transfers file using netcat, with dialog boxes.

after saving(netcat.scpt) this file to your machine just type in your terminal
osascript your_path/netcat.scpt
It will simplify your work to transfer file rather than remembering syntax for netcat 
if you want more shortcut to do this you can add it to .bash_profile file
alias netcat='osascript your_path/netcat.scpt'

and then just type netcat in terminal.. enjoy :)

Tuesday, 7 January 2014

Ruby gem feature_flags new features (0.1.0)

Back again with new features in ruby gem feature_flags (0.1.0).
Here is my blog post on old version of feature_flags . I recommend to go through it first if you haven't, to know more features available in this gem.

Memoization of features is the main change in this version and it really improved performance. Its much more fast now,

What's new  ????

1)  Added Memoization:
In previous versions, Everytime it fires sql query to check whether particular feature is enabled or not when we check
worrying about that ???? Now you need not to because it will fire sql query only when there are changes into database, and memoise it, and that optimizes it to great extent.

2) Check for multiple features at a time:
There may be situation when you need to check following scenario with multiple features,
if FeatureFlags.enabled?(:feature_name1) && FeatureFlags.enabled?(:feature_name2) && FeatureFlags.enabled?(:feature_name3)
  ## some code
  ## some code

 which really increases your code, So now you can do it in better ways
if FeatureFlags.enabled?([:feature_name1, :feature_name2, :feature_name3])
   ## some code
 So when you have more than one features to check simultaneously, pass them as array of feature names
 but if you have single feature to check then just write
  if FeatureFlags.enabled?(:feature_name)
    ## some code
3) Another feature is that you can check if any of given features are active or not:
if FeatureFlags.enabled_any?([:feature_name1, :feature_name2, :feature_name3])
   ## some code
this will execute code inside if any of [:feature_name1, :feature_name2, :feature_name3] feature is active

4) UI changes:
  Do everything on single page (add, edit, enable, disable, remove)

If you are already using previous versions(<= 0.0.3) and want to migrate to this version (0.1.0) then, after updating gem version
just add following line to your model
  include FeatureFlags::FeatureBase
and generate views again..if you have already generated for new updated view
rails generate feature_flags:views
thats it n you are done.  :)

Here is demo

Thursday, 29 August 2013

Manage features in Rails application with feature_flags

You must have faced situation while developing to turn off/on some features in your rails application. So here is ruby gem feature_flags that provides this functionality.Using this we can maintain different features in rails application.
So to add gem in your Rails application,
Add this line to your application’s Gemfile:
gem 'feature_flags'
 then run command
rails generate feature_flags:install

this will generate 3 files,
1) initializer file in config/initializer/feature_flags.rb
2) migration file for Feature model
3) Feature.rb
also it add routes in your rails application
resources :features
 then do
rake db:migrate
In feature_flags.rb initializer file you can mention which layout to use for view
FeatureFlags.configure do |config|
  config.layout = "application" 
FeatureFlags.enabled?(:feature_name) To check whether feature is enabled or not 

FeatureFlags.enable_all                   To enable all features in your app.

FeatureFlags.disable_all                  To disable all features in your app.

FeatureFlags.set_disabled(:feature_name)  To disable feature in your app.

FeatureFlags.create_and_enable(:feature_name)  To create and enable feature

FeatureFlags.enable(feature_name)         To enable feature

If you want to generate views then use,
rails generate feature_flags:views

It will also solve branching problem in rails application, as we merge branches having different features and then solving conflicts in feature_flags makes it easy, you just turn on/off that feature in app.
for example,
if FeatureFlags.enabled?(:feature_name1)
   # your code for feature_name1

Here are some screenshots, 
 main index view( /feature_flags )

 Adding new feature page,
Blog post for next version (0.1.0) click here

Wednesday, 24 April 2013

Deploying rails application on to OPENSHIFT + via RHC client tool

Want to deploy your Ruby on Rails application on openshift ?
then follow these steps,

1. Go to and create an account

2. Click MY APPS > Create an application ( and select Ruby on rails as the type of the application.

3. Put a name for your application. If this is your first time… make sure that you have  a unique namespace. You can change it here:

4.  Clone your git repo into your local machine via the ssh codes provided…

      Example: git clone ssh://
      cd railsapp/

5. or I recommend to use rhc client tool to create app on openshift

      sudo gem install rhc (first install gem rhc)
      rhc app create -a railsapp -t ruby-1.9

6. Then to add cartridge to your rails application use

      rhc cartridge add -a railsapp -c mysql-5.1

7. Then pull your code from github,

      git remote add upstream -m master git://
      git pull -s recursive -X theirs upstream master

8. Then you will need to change, your database.yml put this config for production only...


      adapter: mysql2
      encoding: utf8
      database: <%=ENV['OPENSHIFT_APP_NAME']%>
      pool: 5
      host: <%=ENV['OPENSHIFT_MYSQL_DB_HOST']%>
      port: <%=ENV['OPENSHIFT_MYSQL_DB_PORT']%>
      username: <%=ENV['OPENSHIFT_MYSQL_DB_USERNAME']%>
      password: <%=ENV['OPENSHIFT_MYSQL_DB_PASSWORD']%>
      socket: <%=ENV['OPENSHIFT_MYSQL_DB_SOCKET']%>

   Leave the development and test ENV under mysql adapter.

9. Now in your application directory look for .openshift folder

    there you will find .openshift/action_hooks/deploy file

     pushd ${OPENSHIFT_REPO_DIR} > /dev/null
       bundle exec rake db:migrate RAILS_ENV="production"
     popd > /dev/null

  commands written between pushd and popd lines will get executed automatically after code is updated on openshift,so if you have any other commands like starting resque, or copying some files after deploy then you can add it here.

10. Now that we have made our changes... push it!

      git add
      git commit -m “configures database.yml,gemfile and adds .openshift files”
      git push

11. That’s all, now check url for your rails app.

      here you will find all enviroment variables details that are available in openshift.

13. If you want to associate your own domain name eg. ( with your openshift rails app url then you will need to create url alias as shown below 

         rhc alias add railsapp

then change cname records in your DNS provider account.

14. If your application require some persistent directory for your data then you can use directory (app-root/data/) you can access this directory in your application using enviroment variable OPENSHIFT_DATA_DIR

15. If you want to remove a cartridge

      $rhc cartridge remove shortname –app appname –confirm

      $rhc cartridge remove mysql2  –app railsapp –confirm

Thursday, 28 February 2013

Stripe payment Integration in Rails

Hi ,
     Here is the simple way to integrate stripe into rails application, If you ever need to process credit card payments through your Rails applications you should take a look at Stripe. Stripe is a payment gateway that is easy to set up and which is very developer friendly. It only charges fees on a per-transaction basis and these are very reasonable. There are no monthly fees or other hidden costs. (By the way we’re not being paid to say this.)

Stripe is currently only available in the United States so you’ll need an account at a U.S. bank if you want to use it in your applications. International support is being worked on, however, and should be available soon. This doesn’t mean that you can’t bill international customers, the only restriction is that the seller must be in the U.S.

1) create stripe account at Stripe

2) add gem to gemfile =>  

 gem 'stripe' 

3) create config/initializers/stripe.rb  and add follwing lines (stripe keys)  to it

  Stripe.api_key : your_stripe_api_key 
  STRIPE_PUBLIC_KEY : your_stripe_public_key 
    You will get these keys from your stripe account


4) add these 2 lines to layouts/application.html.erb

<%= javascript_include_tag "", "application" %>
<%= tag :meta, :name => "stripe-key", :content => STRIPE_PUBLIC_KEY %>

this will add Stripe’s Javascript API and set stripe publishable key

 then create form for payment:

<% form_tag(your_payment_path, :method=>'post',:id=>"stripe-form") do %>
  <div class="field">
    <%= f.label :email %>
    <%= f.text_field :email %>
  <div class="field">
    <%= label_tag :card_number, "Credit Card Number" %>
    <%= text_field_tag :card_number, nil, name: nil,:class=>'credit-number' %>
  <div class="field">
    <%= label_tag :card_code, "Security Code on Card (CVV)" %>
    <%= text_field_tag :card_code, nil, name: nil,:class=>'credit-security' %>
  <div class="field">
    <%= label_tag :card_month, "Card Expiration" %>
    <%= select_month nil, {add_month_numbers: true}, {name: nil, id: "card_month",:class => "card-expiry-month"} %>
    <%= select_year nil, {start_year:, end_year:}, {name: nil, id: "card_year",:class => "card-expiry-year"} %>
<% end %>
<div id="stripe_error">
  <noscript>JavaScript is not enabled and is required for this form. First enable it in your web browser   settings.

  make sure these payment information should not get saved in your database,
  Next, we’ll need Stripe’s Javascript API:

  then add following javascript to handle payment form request to stripe,

function stripeResponseHandler(status, response) {
  if (response.error) {
  else {
    var form$ = $("#stripe-form");
    var token = response['id'];
    form$.append("<input type='hidden' name='stripeToken' value='" + token + "'/>");
  $(document).ready(function() {
    $("#stripe-form").submit(function(event) {
      $('.signup-button').attr("disabled", "disabled");
      Stripe.createToken({ number: $('.credit-number').val(),
                           cvc: $('.credit-security').val(),
                           exp_month: $('.card-expiry-month').val(),
                           exp_year: $('.card-expiry-year').val()
                         }, stripeResponseHandler);
return false;
5)  then on submitting form create stripe customer, that will make user to get subscribed to plan with id 'stripe_plan_id'.
    To create a new plan, go into the dashboard, then, into plans, and, from there, there’s a nice little “wizard” that’ll walk you through the process.
    you can specify a trial period for your users, so, if you want them to have 15 days free, you just have to set it up on the dashboard – no code needed! 

Stripe::Customer.create(email: users email , card: params['stripeToken'], plan: stripe_plan_id)

 after creating customer stripe will send stripe_customer_token. Make sure u store this token in database associating to that particular user, in order to access stripe customer associated with particular user registered in your application.

6) In order to handle stripe errors you can check out this link
7) Next thing you will need to add (as per your application's requirement) catching stripe events which are sent by stripe on every transactions
   you can check all types of events here-
8) in your stripe account add webhook url as http://your-url/stripe_events

    then  in routes.rb
match "/stripe_events", :to => "events#stripe_events", :as => :stripe_events, :via => :post

    and now you can catch stripe events in events_controller/stripe_events
class EventsController < ApplicationController
  protect_from_forgery :except => [ :stripe_events ]
  def stripe_events
    # params['type'] will give u type of stripe event
    using these events you make the changes in your application like activating/deactivating users based on whether payment is done or not. 
9) If in case payment fails due some reason for subscription, you can manage it on stripe as shown in following image

10) or you can also use 'stripe_event' gem , that will also provide a way handle  stripe events.