Posts Tagged ‘application development’

Make an OAuth2 server using Laravel Passport

Tuesday, November 3rd, 2020

Laravel already makes it easy to perform authentication via traditional login forms, but what about APIs? APIs typically use tokens to authenticate users and do not maintain session state between requests.

Laravel Passport is a native OAuth 2 server for Laravel apps. Laravel Passport package comes with database migrations, routes, and middleware to ultimately create an authorization server that will return access tokens to allow access to server resources. It uses the League OAuth2 Server package as a dependency but provides a simple, easy-to-learn, and easy-to-implement syntax.

The source code to the todo application is available on GitHub.

This is not an OAuth or Laravel tutorial, so this article will focus solely on how you can use Laravel Passport to create an OAuth server on an existing application. If you want to learn more about Laravel or OAuth, you can look here and here respectively.

Installation/ Requirements

Before we start setting up, make sure you have the following requirements ready as they will be necessary to follow through this article:

Step-1. Getting Started

Let’s go ahead and create a brand new Laravel project first of all. Open your Terminal or Command Prompt and go to the directory where you want to create an app. You can use the following command to change directory.

First of all install the composer in your system and this command.

$ composer install

Use command to change directory.

$ cd Desktop/

Then, run the following command to create a new project.

$ composer create-project --prefer-dist laravel/laravel auth-app

Next, go inside the directory by running this command.

$ cd auth-app/

Run migration Database.

$ php artisan migrate

Generate a secure application key.

$ php artisan key:generate

Now, run your project after install successfully using this command on the terminal.

$ php artisan serve

Now, you get?http://127.0.0.1:8000?to click it and you see Laravel homepage.

Step-2. Installing Laravel Passport

Now let?s install Laravel Passport as well by running the following command.

composer require Laravel/passport

Step-3. Migrate Database

After Passport service provider registers, we require to run the migration command, after running the migration command you will get several new tables in the database. So, let?s run below command:

$ php artisan migrate

Create a User table

bigincrements(?id?);
          $table->string(?first_name?);
          $table->string(?last_name?);
          $table->string(?email?)->unique();
          $table->timestamp(?email_verified_at?)->nullable();
          $table->string(?password?);
          $table->rememberToken();
          $table->timestamps();
      });
  }
  public function down()
  {
       Schema::dropIfExists(?users?);
  }
}

At .env file we have to manage database configuration.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Database
DB_USERNAME=Username
DB_PASSWORD=Password

Step-4. Passport Configuration at our project

In this step, we have to do the configuration on three place Model, Service provider, and config/auth.php file.

So you have to just follow the change on that file.

In the User model: We added Laravel\Passport\HasApiTokens trait,

In app/Providers/AuthServiceProvider.php call Passport::routes

?App\Policies\Modelpolicy?
       ];
   Public function boot()
     {
     $this->registerPolicies();
     passport::routes();
}
}

In auth.php, we added an API auth configuration.

[
        ?guard? => ?web?,
        ?passwords? => ?users?,
    ],
    ?guards? => [
        ?web? => [
            ?driver? => ?session?,
            ?provider? => ?users?,
      ],
      ?api? => [
          ?driver? => ?passport?,
          ?provider? => ?users?,
       ],
   ],
   ?providers? => [
       ?users? => [
           ?driver? => ?eloquent?,
   ?model? => App\User::class,
        ],
    ],
    ?password? => [
       ?users? => [
        ?provider? => ?users?,
        ?table? => ?password_resets?,
        ?expire? => 60,
    ],
  ],
];

Step-6. Set API routes

Create all our routes in routes/api.php.

?auth?
], function () {
      Route::post(?login?, ?Auth\[email protected]?)->name(?login?);
      Route::post(?register?, ?Auth\[email protected]?);
      Route::group([
         ?middleware? => ?auth:api?
       ], function() {
           Route::get(?logout?, ?Auth\[email protected]?);
           Route::get(?user?, ?Auth\[email protected]?);
    });
});

Step-7. Create Controller

Now we need to create AuthController. Run the following command.

$ php artisan make:controller Auth/AuthController

Then, open AuthController.php and add this code.

In this code, we make 3 functions.

  1. Register Users
  2. Login users
  3. Logout
validate([
             ?email? => ?required|string|email?,
             ?password? => ?required|string?
           ]);
        $credentials = request([?email?, ?password?]);
     // print_r($credentials);die;
     if(!Auth::attempt($credentials))
         return response()->json([
            ?message? => ?Unauthorized?
         ],401);
     $user = $request->user();
     $tokenResult = $user->createToken(?Personal Access Token?);
     $token = $tokenResult->token;
     if ($request->remember_me)
         $token->expires_at = Carbon::now()->addWeeks(1);
     $token->save();
     return response()->json([
         ?access_token? => $tokenResult->accessToken,
         ?token_type? => ?Bearer?,
         ?expires_at? => Carbon::parse(
             $tokenResult->token->expires_at
          )->toDateTimeString()
      ]);
   }
   public function register(Request $request)
   {
          $request->validate([
                 ?fName? => ?required|string?,
                 ?lName? => ?required|string?,
                 ?email? => ?required|string|email|unique:users?,
                 ?password? => ?required|string?
          ]);
          $user = new User;
          $user->first_name = $request->fName;
          $user->last_name = $request->lName;
          $user->email = $request->email;
          $user->password = bcrypt($request->password);
          $user->save();
          return response()->json([
               ?message? => ?Successfully created user!?
          ], 201);
   }
   public function logout(Request $request)
   {
        $request->user()->token()->revoke();
        return response()->json([
          ?message? => ?Successfully logged out?
}
public function user(Request $request)
{
            return response()->json($request->user());
}
}

Step-8. Now Adding CORS Middleware

Run the following command to create a new Middleware.

$ php artisan make:middleware Cors
header(?Access-Control-Allow-Origin?, ?*?)
         ->header(?Access-Control-Allow-Methods?,
                   ?GET, POST, PUT, PATCH, DELETE, OPTIONS?)
         ->header(?Access-Control-Allow-Headers?,
                  ?Content-Type, Authorization, X-Requested-With, X-XSRF-TOKEN?);
}
}

Step-9. Register new middleware in app/Http/Kernal.php.

Finally, Run the following command to run.

$ php artisan passport:install
$ php artisan serve

Tests

Now time to test the whole things are working properly or not, if you get an error please follow all these steps again.

We are simply tested by rest-client tools.

For Register New Users

Sending First Name, Last Name, Email, and Password in POST requests.

Now log in with your register email and password.

When you log in with register email and password you got token. You can store this token in local storage. This token is also stored in the oauth_access_tokens table.

We will be sending a GET request to your URL and we need to send it token as Authorization Header.

Conclusion

Above way successive technologies can do API authentication in Laravel Application with a passport. Laravel Passport makes it super easy and it takes only a few steps as we have seen in the article to make your application OAuth2 enabled. If you get any errors, please follow the steps again.

How DevOps is Propelling Business Growth

Tuesday, June 16th, 2020

People often confuse DevOps with a tool or a team, rather it is a process or methodology that uses modern tools for improving the communication and collaboration between Development and the Operations teams and hence the term “DevOps”. Moreover, DevOps has come out of being just a buzzword, it is now covering the mainstream and has gained immense popularity at an extraordinary level forming an entirely new business world.

DevOps provides agility and continuous delivery that support organizations in dealing with real-world industry scenarios like growing speed and complexities. It further assists with both customer and business-level applications empowering digital transformation.

User-based applications demand variations and implementations based on the feedbacks in an agile timeframe. Also, business applications require exceptional performance and robust, automated development & deployment methods to stay in sync. with the consistently evolving market trends. Several organizations have started adopting the business version for ensuring the best strategies for enhancing the infrastructure and security measures. Speed is amazing until quality starts to degrade likewise quality is worthwhile only if the deliverables are reaching customers in a fleet and reasonable time frame. Hence organizations consider DevOps as the key component in software development as it bridges the gap between speed, efficiency, and quality.

DevOps Cycle: The Six Fundamental Cs

Continuous Business Planning: The initial step in DevOps revolves around exploring potential avenues of productivity and growth in your business, highlighting the skillset and resources required. Here, the organizations focus on the seamless flow of value stream and ways of making it more customer-centric. 

Collaborative Development: This part involves drafting a development plan, programming required, and focusing on the architectural infrastructure as it the building block for an enterprise. It is considered as a business strategy, working process, and an assemblage of software applications that promotes several enterprises to work together on the development of a product. Whereas, the infrastructure management incorporates systems management, network management, and storage management which are handled on the cloud.

Continuous Testing: This stage increases the efficiency and speed of the development by leveraging the unit and integration testing. The payoff from continuous testing is well worth the effort. The test function in a DevOps environment supports the developers in effectively balancing speed and quality. Leveraging automated tools can decrease the cost of testing and enable QA experts to invest their time more productively. Besides, CT compresses the test cycles by allowing integration testing earlier in the process.

Continuous Monitoring: Consistent monitoring maintains the quality of the process. Hence, this stage monitor changes and address the flaws & mistakes immediately, the moment they occur. Besides, it enables enterprises to effectively monitor the user experience and improve the stability of their application infrastructure.

Continuous Release & Deployment: This step incorporates monitoring release and deployment procedures. Here, a constant CD pipeline will help in implementing code reviews and developer check-ins seamlessly. This step incorporates monitoring release and deployment procedures. Here, a constant CD pipeline will help in implementing code reviews and developer check-ins seamlessly. The main focus is to depreciate the manual tasks, scale the application to an Enterprise IT portfolio, provide a single view across all the applications and adopt a unified pipeline that will integrate and deploy tasks as and when they occur.

Collaborative Customer Feedback & Optimization: Customer feedbacks are always important as it helps organizations to make adjustment decisions and actions that can enhance the user experience. This stage enables an instant acknowledgment from the customers for your product and helps you implement the corrections accordingly. Besides, customer feedbacks enhance the quality, decreases risks & costs, and unifies the process across the end to end the lifecycle.

Now let us move on to the how DevOps helps driving business growth but before that:

Business Benefits of Leveraging DevOps

Quick Development Leads to Quick Execution

DevOps have three significant and key principles: Automation, Continuous Delivery, and Rapid Feedback Cycle. These principles create a nimble, dynamic, productive, and robust software development lifecycle. Being an evolutionary extent of the Agile Methodology, DevOps uses automation to assure a seamless flow of software development. With the combined strength of the development and operations team, applications are promptly executed and releases are performed at a much faster rate.

Fewer Deployment Errors and Prompt Delivery

With DevOps, it is easy to execute a bulky level of codes in a relatively short period. Teams are enabled to share their feedback so that the errors are early recognized as well as solved early. This, however, results in shorter and robust software development cycles. 

Enhanced Communication and Collaboration

DevOps promotes a growing work culture and intensifies productivity, it inspires teams to combine and innovate together. To improve business agility, DevOps creates an environment of mutual collaboration, communication, and integration across globally distributed teams in an organization. It is because of the combined and collaborative work culture, employees have become more comfortable and productive.

Improved Productivity

Since DevOps is a continuous cycle, therefore it assures a quick development process along with minimal chances of errors. Efficient and seamless development, testing, and operational phases result in enhanced productivity and growth. Also, the cloud-based models significantly enhance the testing and operational stages in DevOps making it more robust and scalable.

New Era of DevOps: SecOps

SecOps is the effective collaboration between the Security and Operations teams offering best security practices for organizations to follow, a process to adhere, utilization of modern tools ensuring the security of the application environment. It enables organizations to supervise the analysis of security threats, incident management, security controls optimization, decreased security risks, and increased business efficiency. SecOps can be a social and transforming process for certain businesses demanding solutions for bigger security threats before the accomplishments of their objectives.

Queuing Tasks with Redis

Thursday, January 23rd, 2020

Introduction and background

Redis is an open-source data structure that is used for in-memory storage and helps developers across the globe with the quick and efficient organization and utilization of data. Even though many developers worldwide are still struggling to decide which open-source software application to use, Redis is quickly growing to be a widely popular choice. Currently, more than 3000 tech joints, including our team, are using Redis.

Redis supports several data structures, including lists, sets, sorted sets, hashes, binary-safe strings, and HyperLogLogs. Our team uses Redis to support queuing in this project.

Queuing is the storing or deferring of tasks of operation inside a queue so that they can be used later. It comes into use for operations which are large in number and/or takes up a lot of time. Tasks can be executed in two different methods –

  • Tasks can be executed in the same order they were inserted, or
  • Tasks can be executed at a specific time.

Challenges

For this project, we needed to download large files, which is extremely time-consuming. To make the process more time-efficient, we decided to use queuing to effectively manage the download request. These download requests were added and served in the FIFO order.

Moreover, we wanted to retry the request in the time interval of one hour if it fails, until it fails three times. After this, the request is marked as failed and then removed from the queue. Our team soon found that manually creating and managing separate queues was rather inefficient, time-consuming, and troublesome, which hinted that we needed a new solution. This is where Redis comes in.

Solution

To create and manage separate queues more effectively, we put Kue npm package to the test. We hoped that it would make our task less time-consuming and more efficient.

And what exactly is Kue? Kue is a priority job queue package that is built for node.js and backed by Redis. What makes Kue so appealing for developers is that it provides us with a UI where the status of queues is displayed. This means that we can see the current status of the queues in real-time, thus helping us work better and smarter.

To use Kue, you have to first install it, then create a job Queue with Kue.createQueue(). The next step is to create a job of type email with arbitrary job data using create() method. This enables the return of a job, which will be saved in Redis using save() method.

Then, after the jobs are created, the next step is to process them using process() method, after which failed jobs should be removed. You can then add Kue UI if you choose and install kue-UI package.

With this, you will be able to store your request in the Redis queue and then process them in FIFO order.

Recent Posts

Recent Comments

Get In Touch

Ask Us Anything !

Do you have experience in building apps and software?

What technologies do you use to develop apps and software?

How do you guys handle off-shore projects?

What about post delivery support?