Last active
January 16, 2017 05:27
-
-
Save janzell/5cc52a5b3455b374a193dc862a954e8a to your computer and use it in GitHub Desktop.
Laravel ApiWhiteList Middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace App\Http\Middleware; | |
use Closure; | |
use Config; | |
use App; | |
class ApiWhiteList | |
{ | |
//List of API path you want to restrict the use based on their IP Addresses | |
protected $apiPath = [ | |
'api/v1/partner', | |
'api/v1/partnerHarness' | |
]; | |
/** | |
* ApiWhiteList constructor. | |
*/ | |
public function __construct() | |
{ | |
} | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @throws \HttpException | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
//check the if requested path exist on the API Path array | |
//validate client IP Address to the Whitelisted IP Addresses | |
if (in_array($request->path(), $this->apiPath) && !$this->isIpWhiteListed($request)) { | |
App::abort(403, 'Access denied'); | |
} | |
return $next($request); | |
} | |
/** | |
* Is IP white listed | |
* | |
* @param object $request | |
* @return bool | |
*/ | |
public function isIpWhiteListed($request) | |
{ | |
//In this case, I used the APP_DEBUG variable under .env file to check which IPs should I used based on their environment. | |
return in_array($request->ip(), | |
( getenv('APP_DEBUG') == 'true') ? Config::get('ip.staging') : Config::get('ip.production') | |
); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @You should add this file under config/ip.php | |
*/ | |
return [ | |
'staging' => [ | |
'112.199.116.18', | |
'112.199.116.19', | |
'124.107.67.135', | |
'184.169.129.472' | |
], | |
'production' => [ | |
'112.199.116.18', | |
'112.199.116.19', | |
'124.107.67.135', | |
'184.169.129.472' | |
] | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment