How to create a simple auth guard in Laravel 5.7? - laravel

I am trying to implement a very simple authentication mechanism with Laravel 5.7, and am not sure of the best approach to take.
For the sake of reducing my issue to the most simple terms possible, let's say that I want to protect certain routes so they are viewable only by users from a specific IP address. If a user from a different IP address attempts to access a protected route, they will be redirected to an external URL.
Basically, I want to do this:
if ($_SERVER['REMOTE_ADDR'] != '123.45.67.89') {
return Redirect::away('https://external-url.example.com/login');
}
What is the cleanest way to implement this in Laravel? I've read a lot of tutorials that explain how to create custom Auth providers, but they seem overly complicated for what I'm doing.
Can I simply create a single middleware class that implements the code above? What are some terms that I can search for via Google, to find tutorials that will help me through implementing this?

Middleware
<?php
namespace App\Http\Middleware;
use Closure;
class VerifyIpAddress
{
/**
* Check request ip address and ..
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($request->ip() !== 123.123.123.123) {
// forbidden page or smth!
}
return $next($request);
}
}

Related

Laravel - extending Illuminate\Http\Request and using session

I've extended the Illuminate\Http\Request class and am passing it along to my controller.
use Illuminate\Http\Request;
class MyRequest extends Request
{
...
}
Controller
class MyController
{
// Doesnt work
public function something(MyRequest $request) {
var_dump($request->session())
}
// Does work
public function something(Illuminate\Http\Request $request) {
var_dump($request->session())
}
}
So when I'm trying to get session $request->session() I get RuntimeException - Session store not set on request.
I feel it has something to do with not running middlewares on my custom request but I dont know how to make it work. Helping or pionting to the right direction would be much apreciated.
To give a little bit more info. I'm trying to make a wizard. Several pages where content of one page depends on choices on previous pages. I'm storing the data in session and on the final page I do "stuff" with it and clear the session storage of current user.
Because it a lot of lines of code and since session instace lives on request I though it would be elegant to hide all those line it in custom request and in controler simply call $myRequest->storeInputs()
This is what seemed to me as "most elegant" in this particular case so I would prefer to finish it this way but I'm also open to a different solution if there is a better aproach.
Summary: basically where should I hide all those lines which are storing and retriving data from sesison?
Solution: I actually solved it by extending FormRequest since it was solution which was the best fit for what I was trying to do. However I accepted the one offered answer since I believe it is generally better solution and I would use it if not for this very particullar case.
The classic Laravel request already got a bunch of settings you didn't catch on your custom request. To achieve that, you should setup a middleware (maybe global in your use-case) which replaces old request in Laravel's container by yours.
<?php
namespace App\Http\Middleware;
use App\Http\MyRequest;
use Closure;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;
class CustomizeRequest
{
/**
* #var \Illuminate\Contracts\Foundation\Application
*/
protected $app;
/**
* #var \App\Http\MyRequest
*/
protected $myRequest;
/**
* #param \Illuminate\Contracts\Foundation\Application $app
* #param \App\Http\MyRequest $myRequest
*/
public function __construct(Application $app, MyRequest $myRequest)
{
$this->app = $app;
$this->myRequest = $myRequest;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
$this->app->instance(
'request', Request::createFrom($request, $this->myRequest)
);
return $next($this->myRequest);
}
}

how to check whether a restaurant is verified in laravel

I am new to laravel and trying to make a panel for food delivery
I have used Laravel default Registration and Login for User Category--Restaurant
and then after user login , the user can Add restaurant details using route (/add_details)
once the user has added restaurant details the user should not be able to go to that route (/add_details)
this will depend on a column in restaurant table (is_verified)
how do i check that
I was thinking of using a Laravel middleware
but then i was stuck how laravel middleware $request variable works
how can i get column value in middleware and verify it
or if any other simple but effective solution
as
i will be using it in sidebar.blade.php as well
so that i can hide the menu
I made a middleware and added it to kernel.php and is using it in routes
Its working fine
but i want to ask is this the right way i have done it
Route::get('/manage_cuisines', 'RestaurantCuisineController#create')->name('manage-cuisines')->middleware('restaurant_verified');
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
use \App\User;
use \App\Restaurant;
class CheckRestaurantVerification
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$restaurant = Restaurant::find(User::find(Auth::id())->restaurant_id);
if($restaurant->is_verified == 0)
{
return redirect('home');
}
return $next($request);
}
}

Detecting unauthenticated ajax requests in Laravel

I am trying to handle ajax request that were initiated from idle/expired session(maybe the page was left open and the session got expired). I wrote the below middleware but it's not working as expected:
namespace App\Http\Middleware;
use Closure;
class AjaxSessionCheck
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(!\Auth::check())
{
if($request->ajax())
{
return response()->json(['Session_error'=>'Session Expired'], 401);
}
}
return $next($request);
}
}
I also tried to add this code to the Auth middleware with no luck.
Strangely enough authenticated(user logged in) ajax requests are detected by this.
Lost 2 days finding solutions. Desperate call here.
use optimised code for performance use both auth::check and request->ajax() in same if condition by AND operator. just try session expiry in configuration file
It's because session runs after middleware, you can see the reference here. If you want to check that session expired, I think you should use after middleware instead of before middleware

Laravel 5.2 subdomain routing, depending on user role.

I have some problems with subdomain routing in laravel 5.2 and hope you can help me with it.
The point is that I need to redirect a user on certain subdomain, depending on it's usertype.
For example in database I have a usertype (1,2,3 etc...) and basing on that value I need to redirect user on
type1.mysite.com
type2.mysite.com
type3.mysite.com
etc...
But the problem is that I can't get authenticated user in routes.php, it always returns null.
Any ideas on how to solve that problem?
And by the way, to make a subdomain routing, I have to configure apache in some way or it can be done with laravel?
Thanks for the answers!
you need to edit it and specify what we want it to do.
In App\Http\Middleware you should see the newly created file
php artisan make:middleware UserTypeMiddleware
<?php namespace App\Http\Middleware;
use Closure;
class UserTypeMiddleware {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
//check your user type here
if ($request->user()->type != 1)
{
return redirect('DefinedRoute');
}
return $next($request);
}
}

How to implement security system to keep IP addresses and browser history in laravel?

To implement the security system in my application. I want to keep the history of visitors and users IP addresses and browser identity. In my application, visitors are those who do not sign up with my application and can access certain parts of my application.
What is the best way to implement it in laravel 5? Is there method like boot() which could serve my requirement.
You can use middleware.
Create middleware:
artisan make:middleware StoreUserInfo
This command will create class App\Http\Middleware\StoreUserInfo
Edit StoreUserInfo class:
<?php
namespace App\Http\Middleware;
use DB;
use Session;
class StoreUserInfo
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!Session::get('user-info-stored')) {
// save IP address and browser to DB
// set session flag to prevent DB duplicates
Session::put('user-info-stored', true);
}
return $next($request);
}
}
Keep in mind that your software should be privacy-compliant. In some countries like Germany it's illegal to store user's IP address. Read more: https://github.com/piwik/piwik/issues/692

Resources