Category Archives: IT – Blogs

How to install node/nodejs using source code in ubuntu 14.04/16.04/18.04 server

Sometimes installing from ppa’s/source-lists will not be working smoothly, in that case install using source can be better and easy one option. Installation of nodejs on ubuntu or any linux flavour from source is easy. You need to just follow below steps. Steps are below.

Steps-

1. Download it from source distribution list.

https://nodejs.org/en/download/current/

or simply by using below commands on terminal.

wget https://nodejs.org/dist/v11.3.0/node-v11.3.0.tar.gz

2- untar the downloaded file.

tar -xzf node-v11.3.0.tar.gz

3. move to unzipped directory

cd node-v11.3.0

4. Configure source code dependencies, To generate makefile from makefile.in

./configure

5. issue make command, uses make file to build program.

make

6. issue make install command, uses makefile to to install program.

make install

It will complete the installation process, now you can check the node installed version using below command.

node -v

For more details you can refer to https://nodejs.org/en/

Facade Pattern – Design Pattern

facade

Intent of facade is to provide the ease of use to any library(subsystem) through a an interface/class.

The Facade Pattern provides a unifide interface to a set of Interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use.

Here We can take example of a complex theater system. For playing a movie we may need to set a different programs of each subsystem, Now We can look at facade is some thing like that reduces steps in performing a task, rather than tuning each individual program to work.

In below example TheaterFacade object makes easier to operate programs.

<?php
class TheaterFacade {
    public $dvd, $music, $movie, $player;

    public function TheaterFacade(DVD $dvd, Music $music, Movie $movie, Player $player)
    {
        $this->dvd = $dvd;
        $this->music = $music;
        $this->movie = $movie;
        $this->player = $player;
    }

    public function playMovie($movieName)
    {
        $this->music->setMusic(7);
        $this->movie->setMovie($movieName);
        $this->player->play();
        ...
        ...
    }

    public function stopMovie()
    {
        $this->music->stopMusic();
        $this->player->stop();
        ...
        ...
    }

}

class Music {
    
    public function setMusic($volume)
    {
      //setting volume function
    }

    public function stopMusic()
    {
      //stop function
    }
}

class Player {
    public function play(){
       //play function
    }

    public function stop(){
       //stop player function
    }

}

class Movie {

    public function setMovie ($movie) {
        //set movie to play
    }
}

Laravel Eloquent vs Query Builder

Eloquent Models

Eloquent is Laravel’s implementation of Active Record pattern for working with your database. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. and it comes with all its strengths and weaknesses. It is a good solution to use when you process a single entity in a CRUD manner – that is, read from database or create a new entity and then save it or delete. You will benefit a lot from Eloquent’s features such as dirty checking (to send SQL UPDATE only for the fields which have been changed), model events (e.g. to send administrative alert or update statistics counter when someone has created a new account), traits (timestamps, soft deletes, custom traits) eager/lazy loading etc.

Eloquent is an ORM, which means can automatically handle the relationships of your models for you. You can retrieve related models without writing complex queries. You can even retrieve database information without any kind of database knowledge at all. Also Eloquent has ton of extra features the the query builder lacks, such readability, accessors, mutators, JSON/Array conversion, hiding sensitive attributes, automatic timestamps, automatic attribute casting, softdeletes.

But, as you already know, it comes with some performance price. When you process a single or just a few records, there is nothing to worry about. But for cases when you read lots of records (e.g. for datagrids, for reports, for batch processing etc.) the plain DB is better approach.

Fluent query builder

Laravel’s database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems.

The Laravel’s query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

NOTE: All methods available to Query Builder are available to Eloquent too, But method available to Eloquent Models is not available to Fluent, In short We can see Eloquent as a wrapper class over Query Builder.

CSRF Middleware in Laravel 5

CSRF

Working of CSRF Middleware in Laravel 5

Laravel makes it easy to protect your application from cross-site request forgery (CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user.

Laravel automatically generates a CSRF “token” for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.

The VerifyCsrfToken middleware, which is included in the web middleware group, will automatically verify that the token in the request input matches the token stored in the session.

Laravel 5 enables the VerifyCsrfToken middleware by default for all requests that is using webmiddleware . It works as below:

#1- Check if the request is a reading request (HEAD, GET, OPTIONS). If so, skip the check.
#2- Matches the token from the _token input or from the headers.
#3- Add a cookie with the token to each request.

This makes the CSRF check a lot more flexible. You don’t have to remember where to add you filters, just make sure that every form has a _token field. Because of #2 and #3, it will work with Ajax request without having to modify the core filter.

Note: This reminds us again that GET requests should never change state(More precisely GET Request are meant to retrieve the data from server, rather than make any kind of update to server database). The CSRF middleware assumes that it doesn’t need to check GET (or HEAD/OPTIONS) requests, because they should be safe to execute.

Checking the headers

At first, only the X-XSRF-TOKEN was checked. This used the Angular convention that the token could be read from the XSRF-TOKEN cookie. If Angular detects that cookie, it adds the token to all XHR requests.

var xsrfValue = urlIsSameOrigin(config.url)
? $browser.cookies()[‘XSRF-TOKEN’]
: undefined;
if (xsrfValue) {
reqHeaders[‘X-XSRF-TOKEN’] = xsrfValue;
}

While this does work great for Angular, it has a slight problem: Because the cookies in Laravel are always encrypted, the token from the cookie needs to be decrypted before it can be compared. This is not a problem for Angular, but it is a problem if you want to set the header manually for your own Javascript requests.

In Laravel 5.0.6, there is added support for a plain text X-CSRF-TOKEN header.

input('_token') ?: $request->header('X-CSRF-TOKEN');
if ( ! $token && $header = $request->header('X-XSRF-TOKEN'))
{
$token = $this->encrypter->decrypt($header);
}
return StringUtils::equals($request->session()->token(), $token);
}

You could now simply add a meta-tag to your section, read it with jQuery and set the XHR header:

$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Above will set the token header for all your jQuery requests.

Hope it may be making a few more clarifications.

SCP Command use tips and tricks

scp command

What is SCP

scp stands for secure cp (copy), which means you can copy files across ssh connection(securely encrypted). It is a very secure way to copy files between computers.

It uses by default the port 22, and connect via an encrypted connection using SSH, in short it using all security setting applied for an ssh connections, for transferring data over network during copy of file from one host to another.

When copying a source file to a target file which already exists, scp will replace the contents of the target file (keeping the inode).

scp have various options, which can be specified over command line.

Few Examples of Scp Commands

Copy one single local file to a remote destination

scp [options [-r Recursively copy entire directories]] /path/to/source-file username@hostname:/path/to/destination-folder/

So, if you want to copy the file /home/user/table.csv to a remote host named host.example.com and copy there to abhishek’s home folder, use this command.

scp /home/user/table.csv username@host.example.com:/home/abhishek/

Copy one single file from a remote server to your current local server

scp username@hostname:/path/to/source-file /path/to/destination-folder

example body could be similar to .
scp username@host.deliverchoices.co.in:/home/abhishek/table.csv /home/abhishek/

You can copy multiple file from host to remote by just replacing file name with ‘directory-name/*’ options.

Copy one single file from a remote server to another remote server

With scp you can copy files between remote servers from a third server without the need to ssh into any of them, all weight lifting will be done by scp itself.

scp user1@server1:/path/to/file user2@server2:/path/to/folder/

Copy multiple files with one command

You can copy multiple files at once without having to copy all the files in a folder, or copy multiple files from different folders putting them in a space separated list.

scp file1.txt file2.txt file3.txt username@host.deliverchoices.co.in:/home/abhishek/

Copy all files in a folder recursively to a remote server

scp -r /home/abhishek/html/* username@host.deliverchoices.co.in:/home/abhishek/newfolder/

SSH Command Tips and Tricks

ssh man

SSH is some kind of an abbreviation of Secure SHell. It is a protocol that allows secure connections between computers.

In more detail we can summarize it as, ssh (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. It is intended to replace rlogin and rsh, and provide secure encrypted communications between two untrusted hosts over an insecure network.

ssh connects and logs into the specified hostname (with optional user name). The user must prove his/her identity to the remote machine using one of several methods depending on the protocol version used.

Few Use Case Examples

Assuming you are using any Linux(Like Ubuntu etc.) You can perform ssh command over terminal.

The simplest pattern would be of SSH command as below with minimum option.

ssh yourusername@yourserverip

You will still be asked for a password. For security reasons, it is not even possible to directly specify the password in the syntax. You will always be asked interactively, unless you start configuring the server in an advanced way like (You may have added your system public key to remote system from which you are connecting, in this way you will be only asked a few question during first time login, not the password for your ssh username using which you are logging to system).

You can specify your port too while issuing ssh command, if you do not wish to use default port(22) setting, due to any of reasons.

ssh -p portno yourusername@yourserverip

Sometimes, especially in scripts, you may want to connect to the remote server, and run a single command and then exit again.

ssh yourusername@yourserverip checkinfo

Authentication Methods

The methods available for authentication are: GSSAPI-based authentication, host-based authentication, public key authentication, challenge-response authentication, and password authentication. Authentication methods are tried in the order specified above, though protocol 2 has a configuration option to change the default order: PreferredAuthentications.

Public Key based Authentication

In most of situation you may find you are using public key based Authentication.
Public key authentication works as follows: The scheme is based on public-key cryptography, using cryptosystems where encryption and decryption are done using separate keys, and it is unfeasible to derive the decryption key from the encryption key. The idea is that each user creates a public/private key pair for authentication purposes. The server knows the public key, and only the user knows the private key. ssh implements public key authentication protocol automatically, using either the RSA or DSA algorithms.

Creating of public keys can be done using ssh-keygen command.

Command Pattern – Design Pattern

Commands gives us a way to package a piece of computation(a receiver and a set of actions) and pass it around as a first-class object.
Now, computation may be invoked long after some client application creates the command object.

The process of invoking a command may be done by a different thread. We can take this scenario and apply it to many useful applications such as schedulers, thread pools, and job queues etc.

For understanding command object, Let’s have a example of queue system in Laravel( A php framework ), Queues come to picture when you need to perform a task in background, without affecting the end user experience like as sending a bulk e-mail, or preparing a file to download that will be available after few minutes based on request of end user. In this case we just take the input from end user, what it wishes to do and without completing that request we just intimate to user that specific response will be available or done after a few minutes, mean while what application does, it stores Jobs( implementing queue system methods) or command object, in a database or some other structures depending on your driver configured for queue system.
and then in background we have set some threads that picks the command objects(JOBS) from its pool and gets executed its handle method. As all commands have implemented the Interface that is having handle method, and at time of calling its execute method it calls handle on the command object(JOB class).

We can summarize command pattern as below.

The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable(undo) operations.

It enables encapsulating a request by binding together a set of actions on a specific receiver.

Singleton Pattern – Design Pattern

A Singleton pattern ensures a class has only instance, and provides a global point access to it.

For detailed overview we can have a look at below code flow, We are having a Singleton class having private constructor, that can’t be instantiated directly by outsider class using new operator. For instantiating this class we need to call class’s method.

public function callProgram () {
    ....
    neededInstance = Singleton.getInsatnce(); // will be returning object of singleton class.
    ....
    ....
}


public class Singleton {
    
    private static Singleton uniqueInstance ;

    //constructor of a class
    private Singleton() {

    }

    public static Singleton getInsatnce() {
        if ( uniqueInstance == null) {
            synchronized (Singleton.class) {
                if ( uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }

        return uniqueInstance;
    }
}

Factory Pattern – Design Pattern

Factory Pattern Method encapsulates object creation. The factory method encapsulate object creation by letting subclasses decide what objects to create.


One thing to notice here, class being called(in our case concreteProduct) for instantiating the Object is independent of class that is calling, means to say both of them are unknown to each other, they know only the contract(in our case Product ), with which they will be interacting, Here product interface is contract that is known to both of them, but createrClass does not know that It is interacting with concreteProduct class object, it only know that object which it got from its subclass factory is of type Product, Rest information about object is encapsulated here.

<?php

class createrClass{
    
      function factoryMethod() ;  --> Abstract method
      
      function anOperation()
      {
          
      }
}

class concreteCreator extends createrClass{
        
    //implemented method (responsible for creating objects)
    function factoryMethod()
    {
    }

}

//Interface For concreteProduct class,
interface Product{

}


//class for Object being created by subclass(concreteCreator) method factoryMethod 
class concreteProduct implements Product{ 
 
}

All type of concreteProduct subclasses must implement this interface so that concreteCreator’s factoryMethod only has to know about Product interface type and no more info about subclass that is being instantiated to create Object of specific type

Hope it makes clear picture about factory pattern.

What is design pattern and benefits of adopting it.

A design pattern comes in to picture, when you are designing a project that may come with vital changes(An obious nature of software projects) in your flow depending on customers needs.

Sometimes it’s easy a add a new feature in your application, and some time it becomes difficult due to its impact on the system to add a new feature changes, although it may be too small from a users point of view.

So main use of design pattern comes to picture in identifying how you will be designing your application of a specific domain, so that it can adopt changes(means to add a new features easily from programming point of view) easily to your application, without affecting previous functionalities.

So What comes main things while designing a software from a software architect point of view.

1- Identifying objects and there interactions.

2- How frequent the behavior is going to be changed for an object in your application.

3- How a new object may come in to picture (probably adding a new feature)

4- How it will be serving to end users(speed, accuracy, user traffic load etc.).

 

Above described parameters may help to any software architect/programmer to design a system that can easily incorporate changes as well.

It may look some time that a particular practice is not being followed in your project scenarios, that is ok, sometimes its your design patterns need, as your project design pattern have to be focused mainly on how well it can adopt changes as well as how it will be serving to end users.