纤薄的框架路由中间件

时间:2014-12-01 11:27:54

标签: php middleware slim

我正在尝试检查用户是否已从列入白名单的IP上传文件。

目前我已经创建了一个自定义中间件,但我有两个问题:

  • 如果引发异常(例如:未找到用户)app->错误()
  • 未捕获异常
  • 如果我暂停()应用程序,则会引发异常并查看我的第一个问题
  • 我想将这个中间件应用到单个路由,但路由中间件在调度之前被调用,因此我无法访问请求,因此我没有要检查的源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();
    }
  }
}

0 个答案:

没有答案