我正在尝试检查用户是否已从列入白名单的IP上传文件。
目前我已经创建了一个自定义中间件,但我有两个问题:
用户使用基本的HTTP身份验证对自己进行身份验证,此处遵循我的中间件
namespace Safemail\Middleware;
use App\Validator;
use Safemail\Model;
class LocalizationLock extends \Slim\Middleware
{
/**
* Deny Access
*/
public function deny()
{
$this->app->halt(403, \App\Utilities::array2json(array('status' => 403, 'message' => 'You are not allowed to connect from your current ip')));
}
/**
* Localize user, if he's in the range, return true,
* otherwise return false
* @param string $username
* @param string $ip
* @return bool
* @throws \Exception
*/
protected function localize($username, $ip)
{
if (!$username = Model\User::findByUsername($username)) {
throw new \Exception('User not found');
}
// admin can upload from everywhere
if ($username->isAdmin()) {
return true;
}
$uploadRanges = $username->getUploadAllowedRanges();
/**
* Upload ranges can be either an array of ranges,
* an array of ip addresses or both.
*
* No ranges specified, allow, do a permissive check:
* - '' (empty string)
* - null
* - false
*/
if (!$uploadRanges) {
return true;
}
$uploadRanges = explode('|', $uploadRanges);
foreach ($uploadRanges as $uploadRange) {
if (Validator::validateIpOverRange($ip, $uploadRange) ||
(Validator::validateIpAddress($uploadRange) && $uploadRange === $ip)) {
return true;
}
}
return false;
}
/**
* Call
* This method will check the HTTP request for source IP. If
* the request comes from an allowed ip or range, the next middleware is called. Otherwise,
* a 425 Forbidden response is returned to the client.
*/
public function call()
{
$req = $this->app->request();
$authUser = $req->headers('PHP_AUTH_USER');
if ($this->localize($authUser, $req->getIp())) {
$this->next->call();
} else {
$this->deny();
}
}
}