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

Thursday, December 8, 2011

Export data to XLS/CSV/TEXT from MySQL

To dump all the records from a table called "users" into the file /home/sapna/users.xls as a XLS file you need to do is.

1) Go to mysql comand prompt using command
mysql -u root -p database_name

2)Then use the following SQL query:
SELECT *
INTO OUTFILE '/home/sapna/users.xls'
FIELDS TERMINATED BY ','
ENCLOSED BY ' " '
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM users;
Note that the directory must be writable by the MySQL database server. 
If it's not, you'll get an error message like this:
Can't create/write to file '/home/sapna/users.xls' (Errcode: 13)
 
To resolve above error, you need to do is
i)sudo gedit /etc/apparmor.d/usr.sbin.mysqld
ii)Add line at last  /home/sapna/* rw, - means read/write permission of folder where you want to write xls file
iii)And then make AppArmor reload the users. 
sudo /etc/init.d/apparmor restart/reload
Also note that it will not overwrite the file if it already exists, 
instead showing this error message:
File '/home/sapna/users.xls' already exists
 

Thursday, December 1, 2011

NGINX server configurations.

1) To find path of nginx.conf file.
locate nginx.conf
It will give you locaiton of nginx file.
/usr/local/nginx/conf/nginx.conf                                                                                       
/usr/local/nginx/conf/nginx.conf.default

2)To set domain name
Edit nginx.conf.default
nano /usr/local/nginx/conf/nginx.conf.default
Change server_name settings

server {
                listen       80;
                server_name  localhost; #instead of localhost set live domain name like abc.com

                access_log  logs/localhost.access.log  main;

                location / {
                    root   html;
                    index  index.html index.htm;
                }
        }
}

3)After making of any changes in nginx.conf file you need to reload it.
/etc/init.d/nginx reload

4)After making any changes of project files on server you need to restart nginx server.
/etc/init.d/nginx restart

5)To kill process of nginx
ps aux | egrep '(PID|nginx)'
and kill the PID

Refer site:http://library.linode.com/web-servers/nginx/configuration/basic

Tuesday, November 29, 2011

Setup project from Heroku and git repository

1) Install gem heroku
gem install heroku

2) Add heroku key
The first time you run the heroku command, you’ll be prompted for your credentials. Your public key will then be automatically uploaded to Heroku.
heroku keys:add
Generating new SSH public key.
Uploading ssh public key /home/sapna/.ssh/id_rsa.pub

3)git clone git@heroku.com:giraffe-dev.git

Tuesday, November 15, 2011

Kill Webrick process running on port 3000 without daemon

root@root:~$ sudo netstat -anp | grep 3000
tcp        0      0 0.0.0.0:3000            0.0.0.0:*               LISTEN      3023/ruby     
root@root:~$ sudo kill -9 3023
root@root:~$ rails s

Wednesday, November 9, 2011

Mysql - How to search for exact word match using REGEXP?

If you are looking to match EXACT words then don't use LIKE keyword.
You could do word boundaries with the following REGEXP. 
SELECT * FROM TABLE WHERE field_name RLIKE "[[:<:]]foo[[:>:]]";
In Ruby code you can use it like
Model.find(:all, :conditions => "field_name RLIKE 'foo.*'")
or
Model.find(:all, :conditions => "field_name REGEXP 'foo.*'")

Thursday, November 3, 2011

Javascript to check uncheck all checkbox in a Table

<a href="#" id="check_<%= id %>" onclick="checkParent('<%= id %>', true); return false;">All</a>

<a href="#" id="uncheck_<%= id %>" onclick="checkParent('<%= id %>', false); return false;" style="display:none;">All</a>

<table id="table_<%= id %>">
  <tr>
    <td>
      <%= check_box_tag "locations[]", location.id, false, :onchange => "validate();" ,:id => "locations", :class => "location" %>
    </td>
  </tr>
</table>

function checkByParent(aId,aChecked) {
   
    var inputs_in_table = document.getElementById("table_"+aId).getElementsByTagName("input");
    for(var i=0; i<inputs_in_table.length; i++)
    {
        if(inputs_in_table[i].type == "checkbox") inputs_in_table[i].checked= aChecked;
    }
    if (aChecked == true)
    {
      document.getElementById("check_"+aId).style.display = "none";
      document.getElementById("uncheck_"+aId).style.display = ""; 
    }
    else if(aChecked == false)
    {
      document.getElementById("check_"+aId).style.display = "";
      document.getElementById("uncheck_"+aId).style.display = "none"; 
    }
  }

Thursday, September 29, 2011

extract urls

I have some content with a list of URLs contained in it.

I am trying to grab all the URLs out and put them in an array.

I have code like:

content = "Sample of URLs: http://www.google.com and http://www.google.com/index.html which I want to grab"

And I am trying to get the end results to be:

['http://www.google.com', 'http://www.google.com/index.html']

Either of two ways you can extracts URLs

1) urls = content.split(/\s+/).find_all { |u| u =~ /^https?:/ }

Or you can grab it by using REGEX

2) urls = content.scan(/(?:http|https):\/\/[a-z0-9]+(?:[\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(?:(?::[0-9]{1,5})?\/[^\s]*)?/ix)

but note that it won't match pure IP-address URLs (like http://127.0.0.1), because of the [a-z]{2,5} for the TLD.

Wednesday, August 24, 2011

Install Skype CallRecorder

Download skype-call-recorder-0.8.tar.gz from http://atdot.ch/scr/download/

Prerequisites
sudo apt-get install cpp
sudo apt-get install qt4-dev-tools
sudo apt-get install libmp3lame-dev
sudo apt-get install libid3-dev
sudo apt-get install libvorbis-dev

Install Make

To install make need to go on path where download file resides.

sapna@sapna-desktop:~$ cd /home/sapna/Downloads/skype-call-recorder-0.8/
sapna@sapna-desktop:~/Downloads/skype-call-recorder-0.8$ cmake .
sapna@sapna-desktop:~/Downloads/skype-call-recorder-0.8$ make
sapna@sapna-desktop:~/Downloads/skype-call-recorder-0.8$ sudo make install

Restart PC or use like below
skype-call-recorder &

Setup OS from fresh install of Ubuntu 10.04

Setup OS from fresh install of 10.04
1. Apply any updates requested by Update Manager
2. Install ssh using Synaptics PackageManager
3. sudo apt-get update
4. sudo apt-get install build-essential libreadline6-dev
5. sudo apt-get install postgresql-server-dev-8.4 postgresql-8.4
6. sudo apt-get install libmagickwand-dev
7. sudo apt-get install git-core curl subversion
8. sudo apt-get install libxslt-dev libxml2-dev
9. bash < <(curl -s https://rvm.beginrescueend.com/install/rvm)
10. logout and login
11. rvm install 1.8.7-p330
12. rvm install rubygems 1.3.7
13. rvm use 1.8.7-p330

Gem installation specific for ruby 1.8.7
1. gem install rails -v=2.1.2
2. gem install rodf -v=0.1.8
3. gem install roo -v=1.3.11
4. gem install uuidtools -v=2.1.1
5. gem install RedCloth -v=4.2.7
6. gem install rmagick -v=2.13.1
7. gem install zipruby -v=0.3.6
8. gem install pg -v=0.10.1
9. gem install fastercsv -v=1.5.4
10. gem install linefit -v=0.1.0
11. gem install gruff -v=0.3.6
12. gem install mezza-rubyzip
13. gem uninstall rubyzip
* Don't worry about dependency alert. Resolved by mezza-rubyzip
14. gem install testunitxml
15. gem install nokogiri -v=1.4.4
16. gem install xml-simple -v=1.1.0

Postgresql pg_hba.con
1. sudo pico /etc/postgresql/8.4/main/pg_hba.conf
2. replace ident and md5 with trust
* sudo /etc/init.d/postgresql-8.4 restart
3. psql -U postgres < FISHSOURCE_DUMP.SQL

Password for null GNOME keyring in SVN

This happens because your subversion system is trying to use the gnome-keyring for authentication and you've accidentally deleting your GNome keyring.

> Password for '(null)' GNOME keyring:

A solution suggested to avoid the SVN prompting for a password for a keyring. That is typing command in the terminal.

> rm ~/.gnome2/keyrings/login.keyring

After giving this command in the terminal I could svn up and committed code.Usual username and password for SVN were asked and after entering them, the codes are successfully committed.

Monday, January 3, 2011

Break continues text(WRAP TEXT)

When there is continues text like "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" it disturbs the text format.There are 2 ways to do it
1)Adding newline or break after every 100 characters using Javascript.
2)Wrap text by adding style into div tag

Example of first way
-----------------------------------
<div id="company_expertise">
<%long_string = "MYCompanyExpertiseMYCompanyExpertiseMYCompanyExpertiseMYCompanyExpertise"%>
<%= hidden_field_tag "hnd_company_expertise", long_string %>
</div>
<script type="text/javascript">

str1 = document.getElementById("hnd_company_expertise").value;
str = str1.replace(/(.{100})/g, "$1\n");
document.getElementById("company_expertise").innerHTML = str;
</script>
Example of second way
-----------------------------------------
<div style="word-wrap: break-word;">
<%= "MYCompanyExpertiseMYCompanyExpertiseMYCompanyExpertise" %>
</div>

Friday, June 18, 2010

How to create virtual hosts in Windows (wamp) web server?

To create virtual hosts or virtual domains in your Apache server on Windows using WAMP server is just a matter of editing few files. Find the walk-through below.

Prerequisites : Apache server for Windows

Step 1 – Setting up the ‘host’ file

1. Find the ‘host’ file in ‘C:\WINDOWS\system32\drivers\etc’ folder (or where you installed windows)
2. Open it with Notepade or any text editor.
3. You will see following lines

# Copyright (c) 1993-2009 Microsoft Corp.
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
# For example:
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
# localhost name resolution is handled within DNS itself.
127.0.0.1 localhost
::1 localhost

4. Add the desired domain names in the end of the text (after the default localhost settings indicated above) it can be anything with or without extension (see the examples below)

127.0.0.1 mydomain.local
127.0.0.1 www.mydomain
127.0.0.1 mywebsite
127.0.0.1 subdomain.mydomain.local

Step 1 is done.

Step 2 – Configuring the Apache ‘httpd.conf’ and ‘httpd-vhosts.conf’ files

1. First we’ll enable a configuration file located in the WAMP server Apache folder. For this, open up the ‘httpd.conf’ file from the the “ c:\wamp\bin\apache\apahce2.2.11\conf” folder.
2. Find the below lines and delete the # key in front of the second line to un-comment and enable it.

# Virtual hosts
Include conf/extra/httpd-vhosts.conf

This will include the particular configuration file where we’ll setup the virtual hosts and their folders.
3. Now we’ll find the ‘httpd-vhosts.conf’ file located in the Apache server. Usually we can find it in “c:\wamp\bin\apache\apahce2.2.11\conf\extra\” in the WAMP server (replace the apache version number after the \apache\ folder)

Add these lines in that file to enable the virtual hosts (which we created in step 1)

NameVirtualHost 127.0.0.1
# This line will make virtual host based on names not IPs

DocumentRoot "c:/wamp/www”
#this is default root for websites in WAMP
ServerName localhost
#this is default localhost domain


Now again we’ll add another block of virtualhost which will point out custom domain this time.


DocumentRoot "c:/wamp/www/mydomain.local"
#We’ll create a folder inside /www/ folder for our domain files.
#No restrictions in the folder name but we’ll keep it same to make it
#easily identifiable.
ServerName mydomain.local
#this is our custom domain we added in the first step


So, the final look of the file will be like this:

NameVirtualHost 127.0.0.1


DocumentRoot "c:/wamp/www”
ServerName localhost



DocumentRoot "c:/wamp/www/mydomain.local"
ServerName mydomain.local


We can add virtual hosts as many as we needed using the same block. Once everything is added in the ‘host’ file as in step 1 and in the apache config files as in the step 2, we’ll have to restart the WAMP server to take effect new changes we’ve done. Click the WAMP server icon in the system notification area and chose ‘Restart All services’.

Thats it. Now you can access the domain by typing ‘http://mydomain.local’ in the address bar of your favorite browser.

Work locally with IIS and virtual hosts on windows

Here it shows how you can easily create virtual hosts on a windows machine to run multiple sites simultaneous each one having its own domain

Prerequisites : IIS Server for Windows

Steps:
1)Need to add instance in hosts file resides in C:\WINDOWS\system32\drivers\etc path. Add instance 127.0.0.1 mytestsite.local in host file.

2)Then need to start your server like ruby script/server -p 3000

3)Now run site using URL mytestsite.local:3000

Thus newly created instance can execute on custom url.

You can add multiple instance also.
e.g 127.0.0.1 mytestsite.local
      127.0.0.1 new.mytestsite.local