Rails Security – Hiding sensitive Information

There is a time when we often run into a situation where we have keep some secret keys or credentials like payment gateway api key’s or any such secret keys for that matter, we often would go for hard coding and placing them in conf files, but problem is that when we push this to a remote repository all the credentials will be publicly seen by others, there may be times when want to to keep some info which is very private to us or the app. We can set them as environmental variables , If you set them as environment variables, however, they will be set on operating system level in an environment that your application has access to, but not directly coded in the app’s source code – this way, your secrets stay secret from public eyes.

Recently I had run into a situation in the application I was working on to find a way to hide these variables, on doing a research, I found out that there are ways to do at the bash level. This is the restricted solution, you can store the environment variable key/value pairs with the operating system directly and globally, so they are going to be available to the Rails app. In your .bashrc file or zshrc file, set environment variables with lines like:

export Key = Value

With this, you can fire up rails console or irb and access your environment var by doing:

ENV["Key"]
"Value"

This is all well and good but over time, your config file might get cluttered with so many of these variables and you’ll end up with one very messy .bashrc file. This is also not very ideal for creating app-specific environment variables or using different environment variables for different environments such as development and testing.

The Gem Approach(which was ideal) :

After doing a search for a while, that’s when I came across “Figaro”, a rails gem which does the job perfectly for the above mentioned problem. This is very straight forward gem, after installing you can store in a YAML file at config/application.yml. To create the YAML file we have run the command

$ figaro install

This creates a commented config/application.yml file and adds it to your .gitignore. And that’s it you mention your the sensitive data in this and git will ignore it. Using this file you can set variables for different ENV.

While deploying the application on heroku,  figaro  makes it simpler for us. Using the figaro command, you can set values from your configuration file all at once:

$ figaro heroku:set -e production

There are other gems that are available like “dotenv”, have a look at this too.  Hope this blog helped you. Thanks for Reading !

Advertisements

Introduction to Rails Views

Ruby on Rails, or we often call it as Rails, is an open source web application framework written in Ruby programming language. As we all know Rails framework follow MVC architecture. MVC refers to Model-View-Controller. Let us try to understand what is the job of Model-View-Controller.

In Lehman’s term, View is what we see on the screen, Model is the one which fetches or store information in the database and Controller acts as a middle man which connects View and Model. When we click some link, or submit a form on a web application, the request goes to the action in controller, then controller interacts with model if some data needs to be fetched or stored in the database. After the successful execution of the code in the controller, the corresponding view is rendered which shows the data to the end user on an HTML page. In rails, Views are called Action Views and controllers are called Action Controllers. Together they form Action Pack. Every web request is handled by Action Pack, which splits the work into a Controller part, i.e., performing the logic and a View part, i.e., rendering a template. So now as we are familiar with what MVC is, let’s proceed with the main topic, Action Views.

“Controllers are the skeleton and musculature of your Rails application. In which case, models form the heart and mind, and your view templates (based on Action View, the third major component of Rails) are your application’s skin—the part that is visible to the outside world.” ~ Obie Fernandez

Rails Action Views use template systems based on Ruby library “ERB” which create a presentation layer for the end user. Other template system which is very much used these days is “HAML”. ERB stands for Embedded Ruby, as the name suggests, Rails View templates use HTML embedded with Ruby codes. In Rails, for each controller there is an associated directory in the app/views directory which holds the template files that contains the view codes associated with that controller. These files are used to display the view that results from each controller action. The final output consists of three components namely, Templates, Partials and Layouts. Let us understand all the three components in brief.

Templates, there are many ways of writing Action View templates. If .erb extension is used then it is a mixture of HTML and ERB. But, if .builder extension is used then we are rendering data in XML format using an instance of Builder::XmlMarkup library.

Partials, as Rails uses DRY (don’t repeat yourself) convention, one chunk of code can be written in one file and can be used at different places, in views it can be done by using Partials. With partials, you can extract pieces of code from your templates to separate files and also reuse them throughout your templates.

Layouts can be used to render a common view template around the results of Rails controller actions. Every Rails application when created, has a common layout named application.html.erb, most of the pages are rendered within this template. We can also create custom templates to be used by some set of pages. The special app/views/layout directory holds layout templates, intended to be reusable containers for your views.

So now after going through all the components in brief we know how the Views work in Rails. In the upcoming blogs I’ll go in details on each components and also share some sample codes on how the components work all together. Thanks for reading.

Integration of Paypal Express Checkout using SDK Merchant in rails 4

In this post we will talk about how to integrate paypal express checkout using sdk merchant in rails 4.

Before proceeding, make sure that you have a paypal developer account .You can create a developer account by following the link: https://developer.paypal.com.

After this, you can create some sandbox accounts for buyers and sellers for future use by following this link: https://developer.paypal.com/webapps/developer/applications/accounts.

Step 1:

Add this gem to your gem file:

gem 'paypal-sdk-merchant'

run ‘bundle install’.

Step 2:

Generate the config/paypal.yml file with

rails g paypal:sdk:install

Provide the API Credentials of the Seller’s account in paypal.yml

Step 3:

Create a file config/initializers/paypal.rb with the below content to configure SDK Merchant:

PayPal::SDK.load("config/paypal.yml", Rails.env)

PayPal::SDK.logger = Rails.logger

Step 4:

Create a lib/modules/paypal_interface.rb file and put the basic logic over there.

require 'paypal-sdk-merchant'

class PaypalInterface

attr_reader :api, :express_checkout_response

PAYPAL_RETURN_URL = Rails.application.routes.url_helpers.paid_orders_url(host: HOST_WO_HTTP)

PAYPAL_CANCEL_URL = Rails.application.routes.url_helpers.revoked_orders_url(host: HOST_WO_HTTP)

PAYPAL_NOTIFY_URL = Rails.application.routes.url_helpers.ipn_orders_url(host: HOST_WO_HTTP)

def initialize(order = nil)

@api = PayPal::SDK::Merchant::API.new

@order = order

end

In development.rb,

HOST_WO_HTTP = 'localhost:3000'
HOST = “http://#{HOST_WO_HTTP}”

In production.rb,

HOST_WO_HTTP = 'your production URL'
HOST = “http://#{HOST_WO_HTTP}”

Step 5:

These are the required routes that we need.

resources :orders do

collection do

get :paid

get :revoked

get :pay_through_paypal

post :ipn

end

end

Step 6:

Put the express checkout button in your cart page.

<%= link_to(image_tag("https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif"), pay_through_paypal_orders_path) %>;

Step 7:

Add the following actions in order controller.

#creates an order when the payment is completed

def paid

if order = Order.make_order(params[:token], current_user, params[:PayerID])

redirect_to order_path(order.id), notice: "The order for was successfully created. Soon you will be contacted by our team."

end

end

#this action is called when the user cancels his order

def revoked

redirect_to products_path, notice: "Your order has been cancelled."

end

def ipn

if payment = Payment.find_by_transaction_id(params[:txn_id])

payment.receive_ipn(params)

else

Payment.create_by_ipn(params)

end

end

#passes all the details of the cart to the paypal website

def pay_through_paypal

@paypal = PaypalInterface.new(current_user.cart)

@paypal.express_checkout(current_user)

if @paypal.express_checkout_response.success?

@paypal_url = @paypal.api.express_checkout_url(@paypal.express_checkout_response)

redirect_to @paypal_url

else

redirect_to products_path, notice: "Something went wrong. Please try again."

end

end

‘pay_through_paypal’ – This will call the ‘express_checkout’ method defined in paypal_interface.rb and will redirect you to the paypal website.

‘paid’ – This action is called when the user accepts the payment and redirects  you to the PAYPAL_RETURN_URL.

‘revoked’ – This action is called when the user cancels his order.

‘ipn’ – This action tries to find the payment using the transaction id sent in params. If it doesnt find one then it creates a payment and saves the params that are received.

Step 8:

Define the ‘express_checkout’ and ‘do_express_checkout’ method in PaypalInterface class.

def express_checkout(user)

if user.present?

cart_items = []

user.cart_items.each do |item|

each_price = (item.product.price * 100).round

hash = {}

hash.merge!(

Name: item.product.name,

Quantity: item.quantity,

Amount: {

currencyID: "USD",

value: item.product.price

},

ItemCategory: "Physical"

)

cart_items << hash

end

@set_express_checkout = @api.build_set_express_checkout({

SetExpressCheckoutRequestDetails: {

ReturnURL: PAYPAL_RETURN_URL,

CancelURL: PAYPAL_CANCEL_URL,

BrandName: 'Your Brand Name',

PaymentDetails: [{

NotifyURL: PAYPAL_NOTIFY_URL,

OrderTotal: {

currencyID: "USD",

value: @order.price

},

ItemTotal: {

currencyID: "USD",

value: @order.price

},

PaymentDetailsItem: cart_items,

PaymentAction: "Sale"

}]

}

})

# Make API call and get response

@express_checkout_response = @api.set_express_checkout(@set_express_checkout)

else

redirect_to new_user_session_path

flash[:notice] = "Please sign in or sign up before checking out."

end

end

def do_express_checkout

@do_express_checkout_payment = @api.build_do_express_checkout_payment({

DoExpressCheckoutPaymentRequestDetails: {

PaymentAction: "Sale",

Token: @order.express_token,

PayerID: @order.express_payer_id,

PaymentDetails: [{

OrderTotal: {

currencyID: "USD",

value: @order.price

},

NotifyURL: PAYPAL_NOTIFY_URL

}]

}

})

# Make API call and get response

@do_express_checkout_payment_response = @api.do_express_checkout_payment(@do_express_checkout_payment)

# Access Response

if @do_express_checkout_payment_response.success?

details = @do_express_checkout_payment_response.DoExpressCheckoutPaymentResponseDetails

else

errors = @do_express_checkout_payment_response.Errors 

@order.save_payment_errors errors

end

end

end

‘express_checkout’- This method passes all the details of the cart items to the paypal website.

‘do_express_checkout’- It will pass the token, PayerID and other details to the paypal’s website. If the values are correct, then the real payment will be done and paypal will return a successfull response.

Step 9:

Add the following method in app/models/order.rb to create an order when the user makes the payment.

def self.make_order(token, user, payerID)

begin

order = self.new

order.express_token = token

order.user_id = user.id

order.price = user.cart.price

order.express_payer_id = payerID

order.save

@paypal = PaypalInterface.new(order)

@paypal.do_express_checkout

return order

rescue

false

end

end

Monitoring jobs with Sidekiq

Sidekiq helped me as an effiecient tool for monitoring jobs when processes dying with cronjobs.

Disadvantage of using cronjob

I have used cronjob in frequent time intervals to perorm some jobs. It kills the connection to database in each 5 seconds. Increasing the database poolsizes did not help any kind . The site crashes ain regular intervals when it did not connect to the database.

Why Sidekiq ?

Simple, efficient background processing for Ruby.

Sidekiq uses threads to handle many jobs at the same time in the same process. It does not require Rails but will integrate tightly with Rails 3/4 to make background processing dead simple.

Sidekiq is compatible with Resque.
It uses the exact same message format as Resque so it can integrate into an existing Resque processing farm.

You can have Sidekiq and Resque run side-by-side at the same time and use the Resque client to enqueue jobs in Redis to be processed by Sidekiq.

At the same time, Sidekiq uses multithreading so it is much more memory efficient than Resque (which forks a new process for every job). You’ll find that you might need 10 200MB resque processes to peg your CPU whereas one 300MB Sidekiq process will peg the same CPU and perform the same amount of work.

Read the rest of this entry

Integration Of Canvas-Pop API (push & loader calls)

Recently I had to implement the canvas-pop store api in the application that i’m currently working on, in rails. Since there was no proper docs or gems provided for this api apart from the one that is avaliable on the site’s documentation. On the site they have mentioned only for pull api call and no where it was mentioned about the ‘push’ and ‘loader’ api methods. This took quite a while for me to implement, let me walk through the steps. This implementation was done in rails.

The site mentions about a two-step and three-step handshake image-process, here I’ll implement a two-step handshake.

step 1:

“Complete a single image handshake using the /api/push/image endpoint and receive an image_token value”

For this step I had used ‘httpclient’ gem to interact with the api server, to get the image token.

Read the rest of this entry

Useful GIT Commands in ROR

There are a good number of GIT commands, and the documentation is excellent, so I won’t cover many here. Here you will find a list with the major GIT commands, with their short descriptions and usage.

git config:
Sets configuration values for your user name, email, and more.
Usage: git config –global user.name “Your Name” git config –global user.email “example@example.com” cat ~/.gitconfig [user] name = Your Name email = example@example.com

git init:
Create an empty Git repository or reinitialize an existing one
Usage: cd /path/to/my/codebase git init

Read the rest of this entry

Some Useful Ruby Tips Worth Trying

In this blog I’m going to share some ruby (or ROR) tips that I found helpful and somewhat awesome. As compared to other programming, in ruby we can implement any logic in lesser lines of code. So here is the first tip:-

1. Many a times while working on some application in rails we write(try out) long active record queries which run successfully but at the same time we forget to assign the result of the query to a variable. Again to do that we press the UP key then left key until we get back to start point of the query to declare a variable and assign the result to it. But not many of us know there’s a way to do that in no time. See an example below

Read the rest of this entry

Listing Parent-Child Hierarchy in ROR Where Depth Level is Unknown

In this blog, I will go through the steps required to list parent-child hierarchy on the page. First let me tell you about what I had to implement into my application. I’ve been working on an application which deals with categories and products, where categories can have subcategories and subcategories can also have sub-sub categories. So basically it was a parent child relationship with depth level unknown or we can say dynamic. For that I’d used “parent_id” column in the categories table, a category would be a base category if parent_id cell of that category is NULL. So, firstly in the model I’d defined a relationship between a category and it’s subcategory. Following is my Category model:


class Category < ActiveRecord::Base
has_many :subcategories, :class_name => "Category", :foreign_key => :parent_id, :dependent => :destroy
has_one :parent, :class_name => "Category", :primary_key => :parent_id, :foreign_key => :id
end

So now I had to fetch all the categories from the database, so in the categories controller:

Read the rest of this entry

The Rails Rumble(rs) From Mindfire Solutions

At Mindfire ,we are always busy with client work… with one focus to deliver best application to our client and help him to grow. But in the same hand, we are very actively involved with ROR community and participate in regular basics. Last week, Few Rails geeks from Mindfire solutions participated in Rails Rumble with two good concepts.

People across globe has already appreciate our idea and application; please find the details below,

1st Thought:
Listening to music can have a tremendously relaxing effect on our minds and bodies, especially slow, quiet classical music. This type of music can have a beneficial effect on our physiological functions, slowing the pulse and heart rate, lowering blood pressure, and decreasing the levels of stress hormones.

Read the rest of this entry

AJAX in will_paginate (2)

Hi guys, hope you have read my previous blog regarding use of AJAX in will_paginate gem. Here I am going to share how we can use UJS in will_paginate.

For that, I have over-ridden the will_paginate helper methods. Here are the following steps.

I have added a will_paginate_helper.rb helper in my application and added the following code in it.

module WillPaginateHelper
class WillPaginateAjaxLinkRenderer < WillPaginate::ActionView::LinkRenderer

def prepare(collection, options, template)
options[:params] ||= {}
options[:params]["_"] = nil
@@remote = options[:remote]
super(collection, options, template)
end

protected

def link(text, target, attributes = {})
attributes['data-remote'] = @@remote if @@remote
super
end
end

def custom_will_paginate(collection, options = {})
will_paginate(collection, options.merge({:renderer => 
                         WillPaginateHelper::WillPaginateAjaxLinkRenderer, 
                         :remote => options[:remote]}))
end

end

Read the rest of this entry