Tanaka Ryuu

Tanaka Ryuu

1567235685

Protecting Laravel Sites with IP Intelligence

Originally published by Samuel Oloruntoba at scotch.io

From the moment you publish a website, you need to be wary of security. From hackers to script-kiddies, you can’t always be sure of where the next attack could come from.

So, as developers, we are always on the prowl for the next best thing when it comes to protecting our website(s).

In this article, we will cover a simple way of how we can use IP intelligence to detect unwanted connections and protect against insecure requests.

Table of Contents

  • What is IP Intelligence
  • Getting Started
  • Making a Request to IPAPI’s Server
  • Creating Our Middleware
  • Improving for Performance
  • Conclusion

What is IP Intelligence

When most people hear IP intelligence, the thing that comes to mind is “locating users from their IP address”. But, it doesn’t stop there, IP intelligence can be used to accomplish many things:

  • Content personalization.
  • Currency detection.
  • Fraud prevention.
  • Time Zone lookup.
  • Language redirection.

The list above is just a handful of things that can be achieved using IP intelligence.

Building a service that can do all the things listed above can take a lot of time and resources. So, instead of building and managing such a service, that’s what the sponsor IPAPI of this article does.

Getting Started

Our firewall will be built as a middleware for our application, meaning a request coming into our app will pass through this “filter” and reject suspected bad actors.

For demonstrating how we could build a simple middleware to protect our apps, we will be creating a Laravel projectNote, the same can be done in any programming language of choice

composer create-project laravel/laravel firewall --prefer-dist

So, head over to IPAPI and create an account. After that, you’ll see a secret key that has a similar structure to 86ebc30b4adfc508e48bf1b489140fe3. Grab whatever your own is and add it to your .env file.

 IPAPI_ACCESS_KEY=86ebc30b4adfc508e48bf1b489140fe3

After that open config/services.php and add the following array value.

'ip' => [
    'key' => env('IPAPI_ACCESS_KEY'),
],

The last thing to do is to install GuzzleHttp which will be used to make a request to IPAPI’s server.

composer require guzzlehttp/guzzle

After that, we can then build our middleware.

Making a Request to IPAPI’s Server

So, IPAPI offers two endpoints for us to use.

  • api.ipapi.com/api/<ip> where we provide the IP we want to check.
  • api.ipapi.com/check will guess the incoming IP address and give a response (good for requests coming from the browser.

We are most interested in the first one because using the second one will retrieve the IP of our server instead of the incoming request. So, using the first one, we can capture the user’s IP and forward it to IPAPI.

After we create a request like:

GET https://api.ipapi.com/api/161.185.160.93?access_key=86ebc30b4adfc508e48bf1b489140fe3

The response will look something like this

{
    "ip": "161.185.160.93",
    "hostname": "161.185.160.93",
    "type": "ipv4",
    "continent_code": "NA",
    "continent_name": "North America",
    "country_code": "US",
    "country_name": "United States",
    "region_code": "NY",
    "region_name": "New York",
    "city": "Brooklyn",
    "zip": "11238",
    "latitude": 40.676,
    "longitude": -73.9629,
    "location": {
        "geoname_id": 5110302,
        "capital": "Washington D.C.",
        "languages": [
            {
                "code": "en",
                "name": "English",
                "native": "English"
            }
        ],
        "country_flag": "http://assets.ipapi.com/flags/us.svg",
        "country_flag_emoji": "🇺🇸",
        "country_flag_emoji_unicode": "U+1F1FA U+1F1F8",
        "calling_code": "1",
        "is_eu": false
    },
    "time_zone": {
        "id": "America/New_York",
        "current_time": "2018-09-24T05:07:10-04:00",
        "gmt_offset": -14400,
        "code": "EDT",
        "is_daylight_saving": true
    },
    "currency": {
        "code": "USD",
        "name": "US Dollar",
        "plural": "US dollars",
        "symbol": "$",
        "symbol_native": "$"
    },
    "connection": {
        "asn": 22252,
        "isp": "The City of New York"
    },
    "security": {
        "is_proxy": false,
        "proxy_type": null,
        "is_crawler": false,
        "crawler_name": null,
        "crawler_type": null,
        "is_tor": false,
        "threat_level": "low",
        "threat_types": null
    }
}

We can see that IPAPI does a lot of work for us. For this, however, for this article, we are interested in the “security” part of the response.

...
    "security": {
        "is_proxy": false,
        "proxy_type": null,
        "is_crawler": false,
        "crawler_name": null,
        "crawler_type": null,
        "is_tor": false,
        "threat_level": "low",
        "threat_types": null
    } ...

Taking a closer look at the security portion, we can see that IPAPI does a lot of checks for us. From giving the response a security rating, to checking if the incoming request is from the TOR network. It even tells us if a crawler is making the incoming request.

Creating Our Middleware

Middlewares are mechanisms that sit in-between an incoming request and your app. Scotch has a short intro to Laravel middlewares.

Now, we’ll move into the root of our project and run

php artisan make:middleware IPFirewall

After we’ve created the middleware, we can find it in app/Http/Middlewares/IPFirewall.php you will see something similar to;

<?php

namespace App\Http\Middleware;

use Closure;

class IPFirewall
{
/**

  • Handle an incoming request.
  • @param \Illuminate\Http\Request $request
  • @param \Closure $next
  • @return mixed
    */
    public function handle($request, Closure $next)
    {
    return $next($request);
    }
    }

So, to protect our server, we can do this:

public function handle($request, Closure $next)
{
$ip = $request->ip();
$key = config('services.ip.key');
$url = "http://api.ipapi.com/api/{$ip}?access_key={$key}&amp;security=1";

// make request
$client = new Client;
$response = $client-&gt;request('GET', $url);
$data = json_decode((string) $response-&gt;getBody(), true);

if (!array_key_exists('security', $data)) {
    return false;
}

return $data['security']['threat_level'] === 'high' ? abort(403) : $next($request);

}

From the request above:

  • We first get the incoming IP address of the user
  • Then we build our request to send to IPAPI,
  • When we get a response from IPAPI, we check if the security response exists
  • Then if the request threat level is high, we want to restrict user access.

Improving for Performance

The above solution is not the best implementation we have. Because this means that the request is going to slow down for every incoming request.

Because Laravel has a cache layer, we can use that to our advantage by doing

public function handle($request, Closure $next)
{
$ip = $request->ip();
$insecureRequest = Cache::remember(“firewall_$ip”, function() use ($ip) {
// build parameters
$key = config(‘services.ip.key’);
$url = “http://api.ipapi.com/api/{$ip}?access_key={$key}&security=1”;
// make request
$client = new Client;
$response = $client->request(‘GET’, $url);
$data = json_decode((string) $response->getBody(), true);
if (!array_key_exists(‘security’, $data)) {
return false;
}
return $data[‘security’][‘threat_level’] === ‘high’ ?? false;
});
return $insecureRequest ? abort(403) : $next($request);
}

Calling Cache::remember() will tell Laravel to fetch a value from the cache, if it doesn’t exist, it’ll run the closure and return the value from the closure to the cache.

Using the IP address as the unique key, Laravel will first try to fetch the IP’s threat status. If it the request is considered an insecure request, Laravel aborts. Otherwise, the request is allowed through, and we only need to perform the check every once in a while.

Conclusion

IPAPI is a great service used many companies, give them a shot and improve your application security.

Originally published by Samuel Oloruntoba at scotch.io

=========================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

☞ RESTful API with Laravel: Build a real API with Laravel

☞ Master Laravel - A php framework for Beginner to Advanced

☞ PHP with Laravel for beginners - Become a Master in Laravel

☞ Projects in Laravel: Learn Laravel Building 10 Projects

☞ Laravel 2019, the complete guide with real world projects

☞ Laravel for RESTful: Build Your RESTful API with Laravel

☞ Real Time Single Page Forum App with Pusher Laravel & vuejs

☞ Master Laravel PHP in 2019 for Beginners and Intermediate


#laravel #php #web-development

What is GEEK

Buddha Community

Protecting Laravel Sites with IP Intelligence

I am Developer

1608637001

Laravel 8 Get Country, City Address From IP Address

How to get country name from IP address in Laravel 8 app. In this tutorial, i will show you How to get country city state zip code metro code from IP address in Laravel 8 app.

How to get location(county,city address) information from ip address in Laravel

  • Step 1 - Install Laravel 8 App
  • Step 2 - Connecting App to Database
  • Step 3 - Install "stevebauman/location"
  • Step 4 - Add Routes
  • Step 5 - Create Controller By Command
  • Step 6 - Start Development Server

https://www.tutsmake.com/laravel-8-get-country-city-address-from-ip-address-tutorial/

#get location from ip address in laravel #laravel address from ip address #laravel get country city from ip address #laravel get user country by ip #laravel geoip to address

Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

sophia tondon

sophia tondon

1618970788

Top Laravel Development Company India | Laravel Development Services

Laravel is a popular framework for website development, acquiring 25.85% of the PHP framework market share. As a most admired framework among PHP frameworks, it is being utilized for e-commerce, enterprise, social media, and various different types of websites.

There are more than 1 million websites worldwide available over the web that are created using Laravel. Laravel framework is the first preference of PHP developers as it allows them to develop highly scalable, flexible, and faster web applications.

Surely, you, too, would want to deliver a splendid and unhindered user experience to your target audience over the web. Laravel framework can help you achieve this pursuit at ease; all you need to do is hire Laravel developers from reliable & coveted hosts. But! There is no shortage of Laravel development companies that promise to deliver an excellent solution, but only some are able to deliver top-notch quality.

Therefore, I have decided to enlist top Laravel development companies to help you find a reliable and expert host for web development. So, stay hooked with me till the end of this article and explore the best Laravel developers in 2021.

While creating this list, I have kept the following pointers in reflection:

Years of excellence (average 8 years)
Workfolio
Rewards & Recognition
Client rating & feedback
Hourly/Monthly Price
Number of happy clients
Number of successfully launched projects
Minimum man-years experience
So, let’s not waste a minute and glance at top Laravel development companies to hire for creating excellent web solutions.

Read More - https://www.valuecoders.com/blog/technology-and-apps/top-laravel-development-companies-to-hire-experts/

#hire a laravel developer #hire laravel developer #hire laravel developers #laravel developer for hire #laravel developers #laravel developers for hire

sophia tondon

sophia tondon

1620977020

Hire Laravel Developers | Laravel Development Company, Services India

Looking for a team of experienced offshore Laravel developers? Hire a top dedicated team of Laravel developers from India online with 6+ years of average experience on an hourly or dedicated (monthly) basis from ValueCoders and enjoy easy hiring, quality work, and on-demand scalability at up to 60% less cost.

Our offshore Laravel development experts are fully competent to build scalable, secure, and robust custom web apps suiting your business requirements.

First Time Right Process
Complete Control Over The Team
Certified Laravel Coders
Agile & DevOps Enablement
Non-Disclosure Agreement
No Contract Lock-Ins

Visit Us- https://www.valuecoders.com/hire-developers/hire-laravel-developers

#hire a laravel developer #hire laravel developer #laravel development #hire laravel experts #find laravel developers #laravel development services india

Seamus  Quitzon

Seamus Quitzon

1595205213

How to perform migration rollback in laravel

As we know that laravel migration provides very simple way to create database table structure. We need to create migration file and write table structure then migrate that migration. Sometimes we need to rollback that migration. So here we will discuss about the migration rollback in laravel.

We can run the rollback artisan command to rollback on a particular step. We can execute the following artisan command.

php artisan migrate:rollback --step=1

Every time when we will rollback, we will get the last batch of migration.

**Note: **This rollback command will work on laravel 5.3 or above version. For the version below 5.3, there is no command available for migration rollback in laravel.

We can also use the following command to rollback and re migrate.

php artisan migrate:refresh --step=2

It will rollback and remigrate last two migration.

You can also checkout the article for executing single migration by clicking on the link below.

How to migrate single migration in laravel

#laravel #how to perform rollback migration in laravel #laravel migration rollback #migration refresh in laravel #migration rollback batch in laravel #migration rollback for one specific migration #migration rollback in laravel