Created
July 24, 2014 10:18
-
-
Save kimsyversen/6521ecf5b1d18f11a027 to your computer and use it in GitHub Desktop.
Simple IP filter for the Slim Framework
This file contains 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 | |
/** | |
* Simple IP filter | |
* | |
* Use this middleware with your Slim Framework application | |
* to require restrict access to certain ip addresses | |
* | |
* USAGE | |
* | |
* $app = new \Slim\Slim(); | |
* $app->add(new \lib\Middleware\SimpleIpFilter(array('127.0.0.1', '1.2.3.4'))); | |
* | |
* The MIT License (MIT) | |
* | |
* Copyright (c) 2014 Kim Syversen | |
* | |
* Permission is hereby granted, free of charge, to any person obtaining a copy | |
* of this software and associated documentation files (the "Software"), to deal | |
* in the Software without restriction, including without limitation the rights | |
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
* copies of the Software, and to permit persons to whom the Software is | |
* furnished to do so, subject to the following conditions: | |
* | |
* The above copyright notice and this permission notice shall be included in all | |
* copies or substantial portions of the Software. | |
* | |
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
* SOFTWARE. | |
*/ | |
namespace lib\Middleware; | |
class SimpleIpFilter extends \Slim\Middleware { | |
/** | |
* @var array | |
*/ | |
private $_ips; | |
/** | |
* Constructor | |
* | |
* @param array $ips IP addresses allowed to execute API calls | |
*/ | |
function __construct($ips) | |
{ | |
foreach($ips as $ip) | |
$this->_ips[$ip] = true; | |
} | |
/** | |
* Call | |
* | |
* Perform actions specific to this middleware and optionally | |
* call the next downstream middleware. | |
*/ | |
public function call() | |
{ | |
if(array_key_exists($this->app->environment['REMOTE_ADDR'], $this->_ips)) | |
$this->next->call(); | |
else { | |
$this->app->response->status(403); | |
$this->app->response->headers->set('Content-Type', 'application/json'); | |
$this->app->response->body(json_encode( | |
array('code' => 403, 'message' => 'Forbidden' ))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well done ! 👏 simple but effective.