I'm trying to only allow certain ip addresses to access the register route, but I'm getting Type error:
Argument 1 passed to App\Http\Controllers\Auth\AuthController::showRegistrationForm() must be an instance of Illuminate\Http\Request, none given, called in directory\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php on line 19
Here is my showRegistrationForm
method in AuthController
:
public function showRegistrationForm(Request $request) {
$ip = $request->ip();
if ($ip == "148.124.0.1") {
return redirect("register");
} else {
return redirect("home");
}
}
Does anyone know how I would accomplish this?
The simplest answer would be to use: $table->binary('ip_address'); Pros: Store IP addresses in binary will save you some space.
Assigning Middleware To Routes If you would like to assign middleware to specific routes, you should first assign the middleware a key in your application's app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel.
You can use request object: request()->server('SERVER_ADDR'); Or you can use standard PHP way: $_SERVER['SERVER_ADDR'];
Instead checking in controller please check this way
php artisan make:middleware IpMiddleware
Code
<?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);
}
}
then add the new middleware class in the $middleware
property of your app/Http/Kernel.php
class.
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,
];
then apply middelware to routes
Route::get('/', ['middleware' => ['ipcheck'], function () {
// your routes here
}]);
I hope this helps!
// .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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With