Friday, June 21, 2019

Vagrant: Built Customize Vagrant Box

Built Customize Vagrant Box



We can make customize box from our vagrant existed box. With this, we can change our environment in existing box and customize it according our need.




Scripting

// In your Vagrant Init file directory
vagrant up
// Get in to your vagrant environment
vagrant ssh

/*
 * Do your custumize in here
 * For example. I will remove my existing ruby version from vagrant box and change it to new one
 */

sudo apt-get update -y

sudo apt-get install build-essential zlib1g-dev libssl-dev libreadline-dev \
git-core curl libyaml-dev libcurl4-dev libsqlite3-dev apache2-dev -y

curl --remote-name http://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p194.tar.gz

tar zxf ruby-1.9.3-p194.tar.gz

cd ruby-1.9.3-p194/

./configure

make

sudo make install

// Check if my new ruby version successfully installed
ruby -v

// If succeed quit from vagrant ssh
exit

// Adding your customize box to new box
vagrant package

// Name it
vagrant box add lucid64_with_ruby193 package.box

// Check for your new box
vagrant box list

- lucid32
- lucid64
- lucid64_with_ruby193

// Activate your vagrant 
vagrant init lucid64_with_ruby193





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:

Friday, June 14, 2019

Laravel 4 Scheduller with dispatcher


Dispatcher is a Laravel artisan command scheduling tool used to schedule artisan commands within your project so you don't need to touch your crontab when deploying.

For Futher Information go to this link Dispatcher.


  • Do you hate to touch crontab to add scheduller in laravel?
  • Do you hate with all crontab configuration when add scheduller in different servers?
Congratulations,  Laravel has package to handle this problem using Dispatcher. Everthing become simple and easy with this package. Doubt? Here we go!

Tool Kit

  • PHP 5.3+ or HHVM
  • Laravel 4

Configurations

In your application add this to your "require" :{} composer.json

    "indatus/dispatcher": "1.4.*@dev"

remember to do composer update.
In your app/config/app.php providers array add this line:

'Indatus\Dispatcher\ServiceProvider',

Usage

scheduled
  scheduled:make              Create a new scheduled artisan command
  scheduled:run               Run scheduled commands
  scheduled:summary           View a summary of all scheduled artisan commands

Build scheduled command

php artisan scheduled:make yourCommands

Register scheduled command

In Your app/start/artisan.php add this line depend on Your Command :


Artisan::add(new yourCommands);

Scripting

Go to your command app/command/yourCommands and change 

// my artisan command will be php artisan cron:mycommands
protected $name = 'cron:yourCommands';

// Configure this functions to change schedule time
public function schedule(Schedulable $scheduler)
{
  // Change this function to change time
  return $scheduler->daily();
}

This is Scheduler Changes time function example list:

//every day at 4:17am
return $scheduler->daily()->hours(4)->minutes(17);

//every Monday/Friday at 8:30am
return $scheduler->daysOfTheWeek([
                Scheduler::MONDAY,
                Scheduler::FRIDAY
            ])->hours(8)->minutes(30);

// Using Raw Commands
//every other day at 1:59am, 13:59pm and 23:59pm
return $scheduler->setSchedule(59, [1,13,23], '*/2', '*', '*');

// Every minutes
return $scheduler->everyMinutes();

// Every 20 minutes
return $scheduler->everyMinutes(10);

// Every hours
return $scheduler->everyHours();

Cron Setup

In console add

crontab -e
* * * * * php {{ path to your app}}/artisan scheduled:run 1>> /dev/null 2>&1

Debugging

If your cron not running check this

// Via console, check your mcrypt
php -i | mcrypt.

// Via console
php artisan scheduled:run --debug 
backup:avatars: No schedules were due
     command:name: No schedules were due
     myTestCommand:name: No schedules were due
     cache:clean: /usr/bin/env php /Users/myUser/myApp/artisan cache:clean > /dev/null &
     mail:subscribers: /usr/bin/env php /Users/myUser/myApp/artisan mail:subscribers > /dev/null &

// Via Console
php artisan scheduled:summary
//It works if output something like this:
+----------------+------------------+-----------+--------+------+--------------+-------+-------------+--------+
| Environment(s) | Name             | Args/Opts | Minute | Hour | Day of Month | Month | Day of Week | Run as |
+----------------+------------------+-----------+--------+------+--------------+-------+-------------+--------+
| *              | schedule:test    |           | */5    | *    | *            | *     | *           |        |
+----------------+------------------+-----------+--------+------+--------------+-------+-------------+--------+

Share:

Tuesday, May 28, 2019

Laravel 4 Queue with Beanstalk and Supervisor



Queue  is great tools in laravel for implementing delayed job. Queue allowing system to put task in background so it can become faster and make users skip waiting until tasks is finished.
Queue can be implemented to handle big process such as generating reports, image processing, sending email, or even heavy CRUD process.

Tool Kit

Configuration

Installing Queue

In your application add this to your "require" :{} composer.json

    "pda/pheanstalk": "2.0.*"

Scripting

You can create new class or use controller/model/any class to execute function with Queue. Below is function in controller class executed by Queue.

<?php

class ReportsController extends \BaseController {
  function fire($job,$data){
    //Function Process
  }
}

To execute this method with queue use this command

Queue::push('ReportsController', $data);

Other alternative is to execute function without fire method

<?php

class ReportsController extends \BaseController {
  function generateReport($job,$data){
    //Function Process
  }
}

To execute this method with queue use this command

Queue::push('ReportsController@generateReport', $data);

Queue::push() command can be use in Route, Controller, or even Command.

Running Queue

To running Queue we need Beanstalk as a worker. To activate beanstalk running this command in console

  // To fire last job
  php artisan queue:work

  // To fire running job and listen it
  php artisan queue:listen

  // add listener with flag (you can choose or implement all of this)
  php artisan queue:work --timeout=0 --queue="default" --delay=0 --memory=128 --sleep=3 --tries=0

Install and Configure Beanstalk

Install Beanstalk

sudo apt-get update
// Install in Debian or ubuntu
sudo apt-get install beanstalkd

Configure Beanstalk

sudo nano /etc/default/beanstalkd

// Add or uncomment this line
START yes

Start Beanstalk
sudo service beanstalkd start

Configure Beanstalk in Our Laravel App

Set default queue in app to Beanstalk. Go to app/config/queue.php

// Change This
'default' => 'beanstalkd',

// This is default beanstalk configurations
'connections' => array(

    'beanstalkd' => array(
        'driver' => 'beanstalkd',
        'host'   => 'localhost', 
        'queue'  => 'default',
        'ttr'    => 60,
    ),

),

Supervisor

We use php artisan queue:work or php artisan queue:work as listener, but we know that impossible for us to running this command every time we push job to Queue or when we start servers.

To overcome this we use Supervisor to listen all of active worker. Supervisor will listen all of our queue:work --daemon and restart it if failed.

Install Supervisor


// Install Supervisor in Debian or ubuntu
sudo apt-get install supervisor

// Adding configurations
sudo nano /etc/supervisor/conf.d/reportqueue.conf

[program:reportqueue]
command=php artisan queue:work --daemon --env=your_environment
directory=/path/to/MYAPP
stdout_logfile=/path/to/MYAPP/app/storage/logs/myqueue_supervisord.log
redirect_stderr=true
autostart=true
autorestart=true

Add Configuration to Supervisor


sudo supervisorctl
reread # Tell supervisord to check for new items in /etc/supervisor/conf.d/
add reportqueue       # Add reportqueue process to Supervisord
start reportqueue     # Let's Rock

Check Supervisor


// In Console
ps aux | grep php

# You should see some output similarish this:
php artisan queue:work --daemon --env=your_environment
sh -c php artisan queue:work  --queue="default" --delay=0 --memory=128 --sleep --env=your_environment
php artisan queue:work --queue=default --delay=0 --memory=128 --sleep --env=your_environment
Share:

Sunday, April 21, 2019

Setting Vagrant with VHOST




1. Install Vagrant in this article.

2. Log to your Vagrant from directory projects with Vagrantfile.
  •  vagrant ssh
3. From your Vagrant server type: 
  • sudo nano /etc/apache2/apache2.conf
4. Add this text in apache2.conf

<Directory /home/vagrant/public_html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

Directory /home/vagrant/public_html/ : I put my vagrant directory sync in this path. If you use /var/www/ you can skip this step.

5. From your Vagrant server go to: 
  • cd /etc/apache2/sites-available/
6. Create vhost file for example: sample.conf

7. In sample.conf create this configuration:

<VirtualHost *:80>
        ServerName sample.notcom

        ServerAdmin webmaster@localhost
        DocumentRoot /home/vagrant/public_html/php/sample

        ErrorLog ${APACHE_LOG_DIR}/error-sample.log
        CustomLog ${APACHE_LOG_DIR}/access-sample.log combined
</VirtualHost>

ServerName: Use this to access app from browser.
DocumentRoot: path to your sync projects registered in Vagrantfile
ErrorLog and CustomLog: Log Apache2

8. Register sample.conf to sites-enabled
  • sudo a2ensite sample.conf

9. Restart your apache
  • sudo service apache2 restart
10. Access your app using:
  • sample.notcom
  • IP registered in Vagrantfile. config.vm.network "private_network", ip: "192.168.33.10"
  • If, it's still not works use registered PORT in Vagrantfile: 192.168.33.10:8064
11. Remember that you need to install some PHP extensions, PHPMYADMIN, composer, etc in your Vagrant server environment.
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: