只允许某些IP地址在Laravel 5.2中注册用户

时间:2016-04-04 08:45:50

标签: php laravel-5.2

我试图只允许某些IP地址访问注册路由,但我收到类型错误:

  

参数1传递给   App \ Http \ Controllers \ Auth \ AuthController :: showRegistrationForm()必须   是一个Illuminate \ Http \ Request的实例,没有给出,被称为   目录\供应商\ laravel \框架的\ src \照亮\基金会\验证\ RegistersUsers.php   第19行

以下是showRegistrationForm中的AuthController方法:

public function showRegistrationForm(Request $request) {
    $ip = $request->ip();

    if ($ip == "148.124.0.1") {
        return redirect("register");
    } else {
        return redirect("home");
    }
}

有谁知道我会如何做到这一点?

2 个答案:

答案 0 :(得分:37)

而是检查控制器,请检查这种方式

php artisan make:middleware IpMiddleware

代码

<?php

namespace App\Http\Middleware;

use Closure;

class IpMiddleware
{

    public function handle($request, Closure $next)
    {
        if ($request->ip() != "192.168.0.155") {
        // here instead of checking a single ip address we can do collection of ips
        //address in constant file and check with in_array function
            return redirect('home');
        }

        return $next($request);
    }

}

然后在middleware类的$ app/Http/Kernel.php属性中添加新的中间件类。

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'ipcheck' => \App\Http\Middleware\IpMiddleware::class,
];

然后将middelware应用于路线

Route::get('/', ['middleware' => ['ipcheck'], function () {
    // your routes here
}]);

我希望这有帮助!

答案 1 :(得分:3)

// .env

WHITELIST='192.168.1.1;192.168.1.2'

// access.php

whitelist => env('WHITELIST')

// WhitelistMiddleware.php

class WhitelistMiddleware
{
 /**
  * @param Request $request
  * @param Closure $next
  * @return \Illuminate\Http\RedirectResponse
  * @throws ForbiddenException
  */
   public function handle($request, Closure $next)
   {

     $whitelist = config('access.whitelist');

     $ipAddresses = explode(';', $whitelist);

      if (! in_array($request->ip(), $ipAddresses)) {

        \Log::error('IP address is not whitelisted', ['ip address', $request->ip()]);

        return redirect('home');
     }

     return $next($request);
  }
}