Tuesday, April 12, 2016

nil? Vs empty? Vs blank? Vs present? Vs any?


  • blank? objects are false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are blank.

  • nil? objects are instances of NilClass.

  • empty? objects are class-specific, and the definition varies from class to class. A string is empty if it has no characters, and an array is empty if it contains no items.
enter image description here

Tuesday, September 3, 2013

Mass assignment sanitizer Rails 3

The mass assignment vulnerability

Basically the problem is the following: 

 Whenever you scaffold generate code for some resource in Rails, which is pretty common, you can see a snippet like this for creating a resource:


@user = User.new(params[:user])
What this does is create a new user, with all the attributes set to the values that got transmitted from a form and are now in the params[:user] hash. This is very concise as here you can mass assign everything the user entered: name, email, description etc. Cool right? This is why it’s not only generated but also written pretty often. Yeah so far so good.
The problem starts when you got some attributes in your model, which you don’t want your users to have direct access to. For instance the boolean admin, determining if a user is an admin or not. The attacker may use tools to manipulate the html form and hence the transmitted parameters to include the key value pair: admin: true ! So params[:user] may look like this:

params[:user] = { name: 'Sapna', email: 'evil@example.com', description: 'I am an   admin soon', admin: true}

What can I do to protect my app?

Well in general it is pretty easy to protect against this kind of attack you just have to add attr_accessible to all your rails models. This white lists the attributes, that can be assigned during mass assignments. Everything else can not be assigned during mass assignments. So for our example this would look like this: 

class User < ActiveRecord::Base
  attr_accessible :name, :email, :description
  # rest of class omitted
end

Pro-tip: Use Brakeman

Brakeman (can also be found on github) is a static analysis tool (fancy term for: looks at your code, doesn’t execute it), looking for vulnerabilities. So it is a vulnerability scanner for Ruby on Rails. It takes a good look at your source code and informs you of any found security vulnerabilities including the confidence of the scanner that this is indeed a problem (e.g. not a false positive). It seems to find mass assignment vulnerabilities very reliably and it also informed me of a possible Cross-site scripting (XSS) vulnerability in my Rails version (3.2.0) and recommended an update to 3.2.2, as this version fixes the problem. So it is also pretty up to date and I can only recommend it. Now go ahead and gem install brakeman or add it to your Gemfile.
However the default output isn’t very beautiful on my system and hides many important parts so I’d recommend you to run:


brakeman -f html -o brakeman.html path/to/app
For a bit prettier html output. Hope that this helps. And don’t forget to add this brakeman.html to your gitignore. Oh by the way: they also have a plugin for Jenkins/Hudson.
So now go ahead and make your Rails apps more secure!

Tuesday, April 3, 2012

Drag and Drop / Change Position / Move with JQuery and Rails

There are various ways to drag and drop or move or change positions of items.
Here I am listing 2 scenarios using Query.

Lets start it with the following basic steps:
1) Download Download jQuery (version 1.2 or above), then the TableDnD plugin from GitHub (current version 0.6).
2) Reference both scripts in your HTML page in the normal way.
3) Initialize the tables is in the $(document).ready function. Use a selector to select your table and then call tableDnD().

First scenario: (Using JQuery )
After following above steps HTML page will look like:

<%= javascript_include_tag 'jquery.js', 'jquery.tablednd.0.6.min.js', 'jquery.tablednd.js' %>
<h1>Listing Softwares</h1>
<div class="createHeaderApp"> <h3>Softwares...</h3> </div>
<div class="titleWide"></div>
 <div class="jobsHeader">
    <div class='clearfloat'></div>
    <div style="width:595px; float:left;">Name</div>
    <div style="width:70px; float:left;">Show</div>
    <div style="width:70px; float:left;">Edit</div>
    <div style="width:70px; float:left;">Delete</div>
    <div class='clearfloat'></div>
</div>
<table id="softwares">
  <tbody class="appsHeader1" style="overflow:hidden;">
    <% @softwares.each do |software| %>
     <tr class="<%= cycle("even", "odd") -%>" style="font-size:12px; width:875px;  "id="soft-<%= software.id %>">
       <td style="width:595px; float:left;"><%= software.name %></td>
       <td style="width:70px; float:left;"><%= link_to 'Show', software %></td>
       <td style="width:70px; float:left;"><%= link_to 'Edit',  edit_software_path(software) %></td>
      <td style="width:70px; float:left;"><%= link_to 'Delete', software, :confirm => 'Are you sure?', :method => :delete %></td>
      <td class='clearfloat'></td>
    </tr>
  <% end %>
</tbody>
</table>

<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
    // Initialise the table
    $("#softwares").tableDnD();
});
</script>

Now run server, execute application and test it.(Using above code you can now move or change position of list items with internal links or data.)

Second scenario:(Using JQuery & AJAX function )
If you want to save/update the positions of moving items in the database then you have to call AJAX function like below:

1)Generate migration to add new integer field "position" into softwares table
   rails g migration add_position_to_softwares

2)Change $(document).ready function like below:
<script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
      $('#softwares').tableDnD({
        onDrop: function(table, row) {
          $.ajax({
             type: "POST",
             url: "<%= url_for(:action => 'sort') %>",
             processData: false,
             data: $.tableDnD.serialize() + '&authenticity_token=' + encodeURIComponent('<%= form_authenticity_token if protect_against_forgery? %>'),
             success: function(msg) {
               alert("The specifications have been updated")
             }
           });
        }
      })
    })
</script>

3)Change routes.rb abd add new action into your route file.
   match "/sort" => "softwares#sort"

4)Add new definition "sort" into specified controller, for me its  softwares_controller.rb
 def sort
    Software.all.each do |soft|
      if position = params[:softwares].index(soft.id.to_s)
        soft.update_attribute(:position, position + 1) unless soft.position ==  position + 1
      end
    end
    render :nothing => true, :status => 200
  end

The controller iterates over all the softwares, checking the position in the db (see the acts_as_list plugin) versus the position in the array that was sent in the request. For the items that are affected, it updates the position in the db. Since we are only calling this action via AJAX, we just render nothing and indicate a successful status.
 
5)Now restart server and test application.

Thursday, March 1, 2012

Setup Refinery CMS with rails 3.2.2

Refinery prerequisites :
Ruby – 1.8.7, 1.9.2, Rubinius, and JRuby are all acceptable
RubyGems – Recommended that you have the latest version installed
Database – SQLite3 (default), MySQL, or PostgreSQL
ImageMagick – Recommended that you have the latest version installed

If you already have prerequisites then proceed further steps:
1) Install the Gem 

gem install refinerycms
2) Generate an Application
refinerycms path/to/my_new_app

3)Do you have devise.rb file in your project ? If no then
rails g refinery:cms (it should copy devise.rb file in initializer)
4)Start up your site
cd path/to/my_new_app/ 

rails server

Now visit http://localhost:3000 and you should see your Refinery CMS site and you will be prompted to setup your first user. That's all it takes to install and run your Refinery CMS site! 
 

Monday, February 27, 2012

Execute rake file in crontab(RVM)

While executing rake in crontab using rvm, needs to load it properly.

For every 1minute.
 */1 * * * * cd /home/user/application_path && /home/user/.rvm/bin/rvm use ruby-1.9.2-p136 rake reminder_email >> /home/user/crontab_errors.txt


For dayily
0 0 * * * cd /home/user/application_path && /home/user/.rvm/bin/rvm use ruby-1.9.2-p136 rake reminder_email >> /home/user/crontab_errors.txt

Thursday, February 16, 2012

Paperclip 'identify' command error on ubuntu.

The Paperclip.options[:command_path] setting is for the location of your ImageMagick executables (in this case identify).

Try running which identify and setting the option to be the directory that is returned like identify is hashed (/usr/bin/identify).
If that command doesn't return anything, make sure that ImageMagick is properly installed.

If not installed then run following command and install it.

sudo apt-get install imagemagick
sudo apt-get install libmagickwand-dev
gem install rmagick

Then set Paperclip.options[:command_path] = "/usr/bin" in development.rb file

Problem solved.

Friday, December 16, 2011

How to resolve jcode (LoadError) with contacts gem in rails 3?

Ruby >= 1.9 doesn't have jcode, a module to handle japanese (EUC/SJIS) strings, as it supports unicode natively.

So you will need to add: require 'jcode' if RUBY_VERSION < '1.9' to your gdata gem found under your .rvm directory somewhere similar to this:

/home/.rvm/gems/ruby-1.9.2-p0@your_gemset_name/gems/gdata-1.1.1/lib/gdata.rb
change line 21 to:
if RUBY_VERSION < '1.9'
  require 'jcode'
  $KCODE = 'UTF8'
end