Showing posts with label Ruby On Rails. Show all posts
Showing posts with label Ruby On Rails. Show all posts

Friday, December 20, 2019

Instal RVM on Linux Ubuntu 64 Bit






RVM is a command-line tool which allows you to easily install, manage, and work with multiple ruby environments from interpreters to sets of gems. To install Ubuntu in RVM

1. Check Apache and Mysql existed in your machine.
  •  Type http://localhost or http://127.0.0.1 on your browser to check apache running.
  • Check /var/www/ directory.
  • In /var/www/index.html type <?php phpinfo(); ?> , then type http://localhost or http://127.0.0.1 on your browser. If apache installation in your machine already correct, your browser will load PHP informations installed on your machine
2.Run on your terminal:
  • bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer)
  • source ~/.bash_profile .Note : This command is for reload opened terminal. 
  • rvm requirements. Note : This command is for searching all libs that still needed, and then install the lib.
 3. Install Ruby according to the version we need:     
  • rvm install 1.9.3
4.Install another version of ruby with this method.
5. To view all installed RVM 
  • rvm list
6.To use specifics RVM 
  • rvm use 1.9.3
 7.If there is an error when running rvm use 1.9.3 try open file ~/.bashrc and ~/.bash_profile and then add this script :

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session

8. To use Specifics Gemset

  • rvm use 1.9.3
  • rvm gemset use rails3.2
  • rvm use 1.9.3@rails3.2
9. Set Default RVM
  • rvm use 1.9.3@rails3.2 --default

Share:

Tuesday, October 22, 2019

Veritrans Rails 4 with dynamic server_key and client_key

Veritrans is Indonesian Payment Gateway. Veritrans accepts Credit Card, Direct Debit, e-Wallet,Bank Transfer and Convenience Store. That's why this Payment Gateway is famous in Indonesia. Further explanations about Veritrans https://veritrans.co.id/ .

Veritrans has multiple products with different integration method and pricing. About Veritrans Products https://veritrans.co.id/product.html


Veritrans Products:

VT-Link

VT-Link facilitates a payment feature for your online store by redirecting the customer to Veritrans payment page through a link.

VT-Web

VT-Web facilitatess merchant to use Veritrans payment system, by redirecting the customer to the Veritrans payment page.

VT-Direct

VT-Direct is Veritrans product that allows you to use our payment system directly on your website

Integration Tool Kit

  • Rails 4
  • gem veritrans

Configurations

Add gem Veritrans to Gem File and bundle install

    gem 'veritrans';

In Console generate veritrans.yml

rails g veritrans:install

Generate Veritrans Form

rails g veritrans:payment_form

This command will generate controller and view for Veritrans.
Because we will built dynamic key for this integrations. You can keep veritrans.yml configurations like this:

development:
  # Register in sandbox veritrans and get your keys here:
  # https://my.sandbox.veritrans.co.id/settings/config_info
  client_key: ""
  server_key: ""
  api_host: ""

production:
  # Register and get your keys here:
  # https://my.veritrans.co.id/settings/config_info
  client_key: ""
  server_key: ""
  api_host: ""

staging:
  # Register and get your keys here:
  # https://my.veritrans.co.id/settings/config_info
  client_key: ""
  server_key: ""
  api_host: ""

Scripting

VT-Web Integrations

In VT-Web Integrations, you just need to obtain redirect URL to Veritrans . After last check out process, put this function for directing page to veritrans:

@result = Veritrans.charge(
  payment_type: "VTWEB",
  transaction_details: {
    order_id: "order-id",
    gross_amount: 100_000
  }
)
// For Automatically redirect
redirect_to @result.redirect_url

VT-Direct Integrations

VT-Direct Integrations is a little bit complicated because a lot of sensitive data involved in this process.

Preparing The Form

In /views/shared/_credit_card_form   put your last checkout data in here. For example:



<%= form_for @payment, html: {class: "veritrans-payment-form", id:"card_form"} do |f| %>
<% if @settings.client_key.present? && @settings.server_key.present? && @settings.api_host.present? %>
  

Payments Page

<%= render "layouts/notification" %> <%= f.hidden_field :token_id, id:"card_token" %>
<%= label_tag "Length Of Membership" %> <%= number_field_tag :length_of_membership, 1,in: 1..10000 ,size: 5,class:"form-control", id:"length_of_membership",style:"width:10%;float:left;margin-right:10px;" %>
<%= label_tag "Membership Expired" %> <%= text_field_tag :membership_expired, (@company[:membership_expired] + 1.month).strftime('%Y-%m-%d'),size: 5,:readonly => true,class:"form-control", id:"date_expired",style:"width:75%;" %>
<%= f.number_field :amount, id:"gross_amount", size: 25,:readonly => true,class:"form-control",style:"width:75%;" %>
<%= label_tag :credit_card_number %> <%= text_field_tag :credit_card_number, '',:required => true,:placeholder => "4811 1111 1111 1114", name: nil, size: 25,class:"form-control", id:"card_number" %>
<%= label_tag :credit_card_cvv %> <%= text_field_tag :credit_card_cvv, '',:required => true,:placeholder => "123", name: nil,class:"form-control", id:"card_cvc" %>
<%= label_tag :credit_card_expire %> <%= text_field_tag :credit_card_expire, '',:required => true, placeholder: "MM / YY", name: nil,class:"form-control", id:"card_exp" %>
<%= f.label :credit_card_secure, "3D-secure" %> <%= f.check_box :credit_card_secure %>
<%= f.label :notes %> <%= text_area(:notes, :text, class:"form-control", size: "20x30") %>
<%= link_to (image_tag "undo-logo.png", title: :back).html_safe, users_path() %> <%= f.submit "Pay via VT-Direct", class:"btn green-btn" %>
<% else %>
<%= link_to (image_tag "undo-logo.png", title: :back).html_safe, users_path() %>
<% end %> <% end %>

Return Process

In Return Process build this functions

    veritrans_callback = {
      transaction_details: {
        order_id: payment.order_id,
        gross_amount: params[:payment][:amount].presence || @payment.amount
      }
    }
    // Get setting from database
    setting = Setting.first
    // Set key and host for Veritrans
    Veritrans::Config.client_key=(setting.client_key)
    Veritrans::Config.server_key=(setting.server_key)
    Veritrans::Config.api_host=(setting.api_host)

    params[:type] = "Credit Card"
    veritrans_callback[:payment_type] = "credit_card"
    veritrans_callback[:credit_card] = {}
    veritrans_callback[:credit_card][:token_id] = params[:payment][:token_id]
    result = Veritrans.charge(veritrans_callback)

    transaction_params = {}
    transaction_params = {
 order_id:payment.order_id,amounts:result.data[:gross_amount],transaction_status:result.data[:status_message],transaction_id:result.data[:transaction_id],transaction_time:result.data[:transaction_time]
}

    // If Transaction Success
    if result.data[:status_code] == "200"
      // Success Process 
    else
      // Failed Process
    end

That's All. I hope this will help anyone out there. :D



Share:

Wednesday, September 18, 2019

Understanding Rubycritic Smells

Rubycritic is gem that wraps around static analysis gems such as Reek, Flay and Flog to provide a quality report of your Ruby code.

Because this gem was uses as Audit guidelines code quality in my company, I often faced hard time to adjust, optimizing and refactor my code.

I began to summarize Rubycritic detecting behavior and implement it in my code to avoid Smells and easier get at least Grade C to bare pass.

A few my conclusion things to consider when developing code according Rubycritic :


  1. Don't! Never! Avoid! Duplicity Code. Rubycritic love this think and will give you sudden great high score, enough to drop your Code Rating Grade.
  2. Evade complicated nested logic with multiple if, switch, etc. It's saver to use functions to handle logic rather than nested logic. Fox example

    // Rather than this
     if obj == "a"
       if obj1 == "1" && obj2 == "2"
         // Process
       elsif obj1 == "3" && obj2 == "4"
         // Process
       else
         // Process
       end
     elsif obj1 == "b"
       if obj1 == "1" && obj2 == "2"
         // Process
       elsif obj1 == "3" && obj2 == "4"
         // Process
       else
         // Process
       end
     else
      // Process
     end
    
    // Use this
     if obj == "a"
       process(obj1,obj2)
     elsif obj1 == "b"
       process(obj1,obj2)
     else
      // Process
     end
    
    
  3. Evade complicated nested loops with multiple each, for, etc. It's saver to use functions to handle loops rather than nested loops. Fox example

    // Rather than this
     data_sources.each do |data_source|
      data_source.each do |data|
      end
     end
    
    // Use This
     data_sources.each do |data_source|
      process(data_source)
     end
    
    
  4. If your function using nested hash, redeclare multiple used nested hash using variable.

    // rather than
    if params[:id] == '1'
      user = User.where('id = ?',params[:id])
    end
    
    // Used This
    id = params[:id]
    if id == '1'
      user = User.where('id = ?',id)
    end
    

  5.  To combine Hash uses:  .merge!()

          params_data_assign = {}
          params_data_assign[:password_salt] = BCrypt::Engine.generate_salt
          params_data_assign[:password_hash] = BCrypt::Engine.hash_secret(password, self.password_salt)
          params_data.merge!(params_data_assign)
    


  6. Use method = const_get(method) to change string into Model Constant. (surprisingly isn't it?).

      def myfunction
       my_return = obj == 'User' ? 'User' : 'Member'
       process_my_return(my_return)
      end 
      def process_my_return(my_return)
        method = const_get(my_return)
        data = method.where('id = ?',1)
        // Process
      end
If you have found something more than this or have more effective way. Please, tell us so we can share about this problem more.

Share:

Tuesday, June 18, 2019

Breakman Rails: How to avoid Mass Assignment Warning

Breakman is static analysis security scanner for Ruby on Rails. It's open source vulnerability scanner specifically designed for Ruby on Rails applications. It statically analyzes Rails application code to find security issues at any stage of development.

I will share some trick to avoid Breakman Mass Assignment medium settings warning.
  1. Pay attention to your model relationship. My suggestion always use Nested Attributes .
  2. If necessary used attr_protected to relationship variable key in your model.
Below is some of example case I've solved:
  • Example Case 1 "Without Relationship" :
         Set relationship variable in attr_protected to avoid Breakman warning.
      attr_accessible :name, :description
      attr_protected : user_id
         Do this saving method:
            create :
         data_list = {:name => name, :description => description}
        saving_create = self.new(data_list)
        saving_create.user_id = user_id
        saving_create.save
             update :
        data_list = {:name => name, :description => description}
        user_data = self.find_by_id(1)
        user_data.attributes = data_list 
        user_data.user_id = user_id
        user_data.save

  • Example Case 2 "With Relationship" :
      attr_accessible :name, :description
      attr_protected : user_id

      has_one :category
      has_many :products

      accepted_nested_attributes :category, :products

            create :
        products = []
        data_list = {:name => name, :description => description}
        saving_create = self.new(data_list)
        saving_create.user_id = user_id
        all_data.each do |d|
          saving_process = saving_create.products.build
          saving_process.product_id = d[:product_id] 
          saving_process.product_name = d[:product_name]
        end
        saving_create.save
      update :
        products.each do |p|
        data_list = {:name => p.name, :description => p.description}
         update_process = self.find_by_id(p.user_id)
         update_process.attributes = data_list
         update_process.product_id = p.id
         update_process.product_name = p.id
         unless update_process.save
            raise ActiveRecord::Rollback 

         end
        end
      

Share:

Thursday, April 11, 2019

Linkedin Gem: LinkedIn OAuth 2.0 add_share Error

LinkedIn OAuth 2.0 is Rails Gems to integrate Linked Social Media to our Apps through API. This Gem is easy to integrated and use, we can directly GET and POST data from  Linkedin.

But, theres a problem when using add_share API using https://github.com/emorikawa/linkedin-oauth2  documentations. api.add_share(content: "hi") will always generated error.

I've search, read Linkedin documentation, and customize the library but it always generated error. After a few times I found that doing a little change in add_share comments it will works. 

Changes the command into: 
api.add_share(comment: "hi")
Voila, it works... :D
Share:

Tuesday, April 9, 2019

Use arsduo/koala in Rails for Facebook Connect

 Koala is a Facebook library for Ruby, supporting the Graph API (including the batch requests and photo uploads), the REST API, realtime updates, test users, and OAuth validation.

Installation

In Gemfile:
gem "koala", "~> 2.0"
gem 'oauth', '~> 0.4.7'

Never forget to bundle install

Build Callback URL route:
 get '/facebook_callback' => 'facebook#callback', as: :facebook_callback

Facebook Configurations

Get App ID and Secret Key:

  1. Go to https://developers.facebook.com/
  2. In My Apps, add or go to your New App
  3. Get your App ID and App secret

App Configurations

In config/environments/{{your-environments}}  add this line

  ENV["facebook_app_id"] = "{{your-app-id}}"
  ENV["facebook_secret_key"] = "{{your-secret-id}}"
  ENV["facebook_callback"] = "{{your-facebook-callback}}"

REST API With OAUTH

This process will built redirect function to permission page user account in Facebook and return with App Token and App Token Secret. Facebook doesn't recognize localhost with port, if we want to built this connectivity it's better to do it in staging or live servers. Only to get Token and Secret Token Code.
// Connect
facebook_connect = Koala::Facebook::OAuth.new({{your-app-id}},{{your-secret-id}}, {{callback URL}})

// This function will automatically redirecting user to Facebook permission page and redirect it back to your Callback URL
redirect_to facebook_connect.url_for_oauth_code(:permissions => ["publish_actions", "user_posts"])

About Permission can be found in here https://developers.facebook.com/docs/facebook-login/permissions/v2.2

In Return Process built this functions

// Get Token Accces Code
code = facebook.get_access_token(params[:code])

// Get Token Access Secret Code
app_code = facebook.get_app_access_token

// Sample of Get my profile from Facebook
client = Koala::Facebook::API.new(code, {{your -secret-key}})
me = client.get_object("me")

// Save code and app_code to database. This tokens needed for REST API Process

REST API From Facebook Get Status, Profile,etc

Get Status and Profile


// Connect
client = Koala::Facebook::API.new({{ Token Accces }}, {{Token Access Secret}} )
// Get Profile and Feed/Status
facebook_data = client.get_connections("me", "feed", {}, api_version: "v2.0")

Post Status and Comment


// Connect
client = Koala::Facebook::API.new(g{{ Token Accces }}, {{Token Access Secret}})
// Post Status
post_content = client.put_wall_post(params[:description])



Share:

Friday, February 22, 2019

Breakman Rails: How to avoid XSS cross site Warning

I will share some trick to avoid XSS cross site warning in Breakman Rails.

  • Example Case: URL 
          Problem :
            <%= raw generated_link_to("View Barcode","schedule/show_barcode?id="+data[0].to_s+"&schedule_id="+@schedule[:id].to_s","edit_schedule",{:class => 'btn btn-mini btn-info',:remote=>"true"}) %>
          Solved :
            <%= raw generated_link_to("View Barcode", schedule_show_barcode_path({:id=>data[0].to_s, :schedule_id=>@schedule[:id].to_s})"edit_schedule",{:class => 'btn btn-mini btn-info',:remote=>"true"}) %>
           *) schedule_show_barcode_path = route alias in config/routes
          
  • Example Case: Javascript or CSS
          Problem :
         <%= raw generated_link_to('<i class="icon-trash"</i>'.html_safe,"#delete_progress","add_schedule",{:class => 'removedbuttonsetting', :onclick => (params[:row_index],params[:form_type])})%>

<script type="text/javascript">
  function delete_row_form_extrarow(index,form_type){
    $("#tr_body_"+form_type+"_"+index).remove();
  }
</script>

          Solved :
            <%= raw generated_link_to('<i class="icon-trash"></i>'.html_safe,"#delete_progress","add_schedule",{:class => 'removedbuttonsetting', :indexattr => params[:row_index].to_json,:typeattr => params[:form_type].to_json})%>

<script type="text/javascript">
  $(function(){
    $(".removedbuttonsetting").click(function(){
        var index = $(this).attr('indexattr');
        var form_type = $(this).attr('typeattr');
        delete_row_form_extrarow(index,form_type);
    })
  });

  function delete_row_form_extrarow(index,form_type){
    var index1 = JSON.parse(index);
    var form_type1 = JSON.parse(form_type);
    $("#tr_body_"+form_type1+"_"+index1).remove();
  }
</script>


Share:

Thursday, August 16, 2018

Breakman Rails: How to avoid SQL injection

Breakman is static analysis security scanner for Ruby on Rails. It's open source vulnerability scanner specifically designed for Ruby on Rails applications. It statically analyzes Rails application code to find security issues at any stage of development.

I will share some trick to avoid Breakman SQL Injection medium settings warning.

1. Example Case "IN query": 
Wrong Format :
  id = [1,2,3,4,5]
  query = self.find(:all, :conditions =>["id in ("+id.joins(",")+")"])
Correct Format :
  id = [1,2,3,4,5]
   query = self.find(:all, :conditions =>["id in (?)", id])
  or
   query = self.where("id in (?)", id)

2. Example Case "string query": 
Wrong Format :
  query = self.where("id = '"+id+"' and place = '"+place+"' and user = '"+user+"' ")
Correct Format :
  query_conditions = []
  unless id.blank?
  query_conditions << {"id = '"+id+"'"}
  end
  unless id.blank?
  query_conditions << {"place= '"+place+"'"}
  end
  unless id.blank?
  query_conditions << {"user = '"+user+"'"}
  end
  query_where = query_conditions.joins("and")
  result = self.where(query_where)
Share: