Friday, 12 October 2012

Devise Details

Devise usages for rails 3 application:

Devise is very simple authentication solution for Rails 3 application.
There are many gems for authenticating a rails application. But, "devise" is the gem which will make authentication of a rails 3 application easier.

1) Include devise gem in Gemfile as following,

gem ‘devise’

2)Run the below command

bundle install

3) Run generator as following,

rails g devise:install

4) Create model ‘User’ to store authentication

rails g devise User

5)To make the view files we have to give the following command

rails g devise:views

6)For database creation

rake db:create
rake db:migration

7)In layouts applicaiton.html.erb:

<div id="user_nav">
<% if user_signed_in? %>
Signed in as <%= current_user.email %>. Not you?
<%= link_to "Sign out", destroy_user_session_path %>
<% else %>
<%= link_to "Sign up", new_user_registration_path %> or <%= link_to "sign in", new_user_session_path %>
<% end %>
</div>


And also add the following code to the same html file in body tag:

<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>

8) Add the following code to the "config/environments/development.rb" file:

config.action_mailer.default_url_options = { :host => 'localhost:3000' }

9) Now we can create our own controller which, we need this authentication.

rails g controller home

10) if we want to authenticate this controller’s action means we have to give like this,

before_filter :authenticate_user!

11) In routes,(config/routes.rb)

root :to => "home#index"

Whenever you enter the home controller action in url means it will authenticate.

References:
https://github.com/plataformatec/devise
http://www.rorexperts.com/authentication-of-rails-3-application-using-devise-gem-t2243.html
http://www.allerin.com/blog/devise-usage-in-rails-3-devise-authentication-in-ruby-on-rails-3-application/


Omniauth gem for facebook and twitter integration:

1.In gem files
gem 'omniauth'

2.bundle install
rails g scaffold authentication user_id:integer provider:string uid:string index create destroy
rake db:migrate


3.models/user.rb
has_many :authentications

4.models/authentications.rb
belongs_to :user

5.config/routes.rb

match '/auth/:provider/callback' => 'authentications#create'
6.authentications_controller.rb

def index
 @authentications = current_user.authentications if current_user
end

def create
 auth = request.env["rack.auth"]
 current_user.authentications.find_or_create_by_provider_and_uid(auth['provider'], auth['uid'])
 flash[:notice] = "Authentication successful."
 redirect_to authentications_url
end

def destroy
 @authentication = current_user.authentications.find(params[:id])
 @authentication.destroy
 flash[:notice] = "Successfully destroyed authentication."
 redirect_to authentications_url
end


7.config/initializers/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
 provider :twitter, 'CONSUMER_KEY', 'CONSUMER_SECRET'

 provider :facebook, 'APP_ID', 'APP_SECRET'
 #provider :linked_in, 'CONSUMER_KEY', 'CONSUMER_SECRET'
end


8.authentications/index.html.erb

<% title "Sign In" %>

<% if @authentications %>
 <% unless @authentications.empty? %>
   <p><strong>You can sign in to this account using:</strong></p>
   <div class="authentications">
     <% for authentication in @authentications %>
       <div class="authentication">
         <%= image_tag "#{authentication.provider}_32.png", :size => "32x32" %>
         <div class="provider"><%= authentication.provider.titleize %></div>
         <div class="uid"><%= authentication.uid %></div>
         <%= link_to "X", authentication, :confirm => 'Are you sure you want to remove this authentication option?', :method => :delete, :class => "remove" %>
       </div>
     <% end %>
     <div class="clear"></div>
   </div>
 <% end %>
 <p><strong>Add another service to sign in with:</strong></p>
<% else %>
 <p><strong>Sign in through one of these services:</strong></p>
<% end %>

<a href="/auth/twitter" class="auth_provider">
 <%= image_tag "twitter_64.png", :size => "64x64", :alt => "Twitter" %>
 Twitter
</a>
<a href="/auth/facebook" class="auth_provider">
 <%= image_tag "facebook_64.png", :size => "64x64", :alt => "Facebook" %>
 Facebook
</a>
<div class="clear"></div>


9.For stylesheets (application.css)

.authentications {
 margin-bottom: 30px;
}
.authentication {
 width: 130px;
 float: left;
 background-color: #EEE;
 border: solid 1px #999;
 padding: 5px 10px;
 -moz-border-radius: 8px;
 -webkit-border-radius: 8px;
 position: relative;
 margin-right: 10px;
}
.authentication .remove {
 text-decoration: none;
 position: absolute;
 top: 3px;
 right: 3px;
 color: #333;
 padding: 2px 4px;
 font-size: 10px;
}
.authentication .remove:hover {
 color: #CCC;
 background-color: #777;
 -moz-border-radius: 6px;
 -webkit-border-radius: 6px;
}
.authentication img {
 float: left;
 margin-right: 10px;
}
.authentication .provider {
 font-weight: bold;
}

.authentication .uid {
 color: #666;
 font-size: 11px;
}
.auth_provider img {
 display: block;
}
.auth_provider {
 float: left;
 text-decoration: none;
 margin-right: 20px;
 text-align: center;
 margin-bottom: 10px;
}


Reference link:

screenshot details:
http://railscasts.com/episodes/235-omniauth-part-1

http://stackoverflow.com/questions/11093120/devise-omniauth-and-facebook-integration-session-error

http://www.phyowaiwin.com/how-to-download-and-display-twitter-feeds-for-new-year-resolution-using-ruby-on-rails

http://railscasts.com/episodes/235-omniauth-part-1

Thursday, 11 October 2012

Authorize.net integration


Authorize.Net is a payment gateway that enables merchants to accept credit card and electronic check payments via Web sites, retail stores, mail order/telephone order (MOTO) call centers and mobile devices. In other words, Authorize.Net enables the traditional credit card swipe machine you find in the physical retail world on the web.
Recently, we had an implementation where we had to integrate Authorize.net with a Rails 3.x application. The integration is a cake walk and is very easy for even the novice programmers to follow:
1. The first thing we need is a developer account on Authorize.net. Sign up for test account to get API Login ID and Transaction Key. You can sign up from here. Enter you details and select “Card Not Present” as Account Type. Click submit.
2. After successful sign up, you will get a welcome email from authorize.net developer center which contains some test credit cards numbers.
3. Now simply log in to the Merchant Interface and click “Account.” Then click “API Login ID and Transaction Key.” Your API Login ID will be displayed. For security reasons, you cannot view your Transaction Key. Instead, you must generate a new one. To do this you will need the Secret Answer to the system-generated Secret Question, which is “Simon”.
4. There are 3 major ways to implement authorize.net in your application:
  • Server Integration Method (SIM)
  • Direct Post Method (DPM) and
  • Advanced Integration Method (AIM)
In this particular blog post, I am going to discuss Server Integration Method (SIM). There are two main features of this method:
  • Provides a customizable, secure hosted payment form.
  • Authorize.Net handles all the steps in the secure transaction process.
  1. We will use authorize-net gem for this particular case. To integrate SIM in your rails application, open the file “Gemfile” in the root directory of your new rails application and add the following line to the end of the file:
1
gem 'authorize-net'
   and run “bundle install” command from console.
  1. Run the following command it will scaffold everything which we need for integration.
1
$ rails generate authorize_net:sim payments YOUR_API_LOGIN_ID YOUR_TRANSACTION_KEY YOUR_API_LOGIN_ID
  1. Open config/routes.rb and add the route to the method to claim the payments:
1
root :to => 'payments#payment'
  1. Now your application is ready to run. Start the server using following command:
1
$ rails server
You will see a page displaying total amount to be paid and a payment button. If you are facing some errors while starting server, refer to Troubleshoot section of the blog.
  1. Terminate the server and open app/views/payments/payment.erb. It will looks like:
1
2
3
4
5
6
7
</pre>
<%= form_for :sim_transaction, :url => AuthorizeNet::SIM::Transaction::Gateway::TEST do |f| %>
 <%= sim_fields(@sim_transaction) %>
 <%= label_tag 'x_amount', "Total: #{number_to_currency(@amount)}" %>
 <br />
 <%= f.submit 'Purchase'%>
<% end %>
  1. Add following code after the label_tag:
1
2
3
4
</pre>
<%= hidden_field_tag("x_invoice_num", UNIQUE_INVOICE_NUMBER, {:id => "x_invoice_num"}) %>
<%= hidden_field_tag("x_cust_id", CUSTOMER_ID, {:id => "x_cust_id"}) %>
<%= hidden_field_tag("x_email", EMAIL_ID, {:id => "x_email"}) %>
In above code you have to replace UNIQUE_INVOICE_NUMBER , CUSTOMER_ID, EMAIL_ID with some values or variables. Invoice number should be unique for every payment transaction.
  1. Open app/views/payments/thank_you.erb and add a link to root of your application.
1
2
3
</pre>
<%= link_to "Home", root_path %>
<pre>
5. Start your rails server and open the application on browser. Click the “Purchase” button and complete the payment form that appears on the hosted payment page.
6. Select “Visa” and enter any test credit card, any expiration date (MMYY) in the future (such as “1120″), and hit “Submit”.
7. That’s it!! The payment is completed and the user will be redirected to thank you page.
Please feel free to drop a comment in case you have any queries.
Troubleshooting:
  • uninitialized constant RAILS_ROOT: Open config/initializers/authorize_net.rb and replace RAILS_ROOT with Rails.root
  • uninitialized constant RAILS_ENV: Open config/initializers/authorize_net.rb and replace RAILS_ENV with Rails.env

Interactor in Rails

What is interactor? Interactor provides a common interface for performing complex user interactions An interactor is a simple, sin...