Routes: Check if session exists in Laravel - php

So in my LoginController.php, I started a session for different post request variables below where the session code is inside the authenticated function of auth.
protected function authenticated(Request $request, User $user){
$request->session()->put('param1',$param1);
$request->session()->put('param2',$param2);
$request->session()->put('param3',$param3);
.....
}
and I easily access these session in my different controllers like this
$request->session()->get('param1')
and I also placed this code when logout triggers..
session()->flush();
But I need also to protect my route if these session exists or not
What I'm trying to do is to not allow the users not to access these routes if session is not exists web.php
Route::group(['middleware'=> ['auth']], function(){
Route::get('/pay', 'PayController#index');
Route::post('pay/getReceipt', 'PayController#getReceipt')->name('getReceipt');
....
});

Create a middleware that checks if those session parameters exist then wrap your routes in it.
public function handle($request, Closure $next)
{
if (Session::has('your_params')) {
return $next($request);
}
return redirect()->back();
}

Related

how to get the roles and permissions dinamically - Laravel

I'm trying to implement roles and permissions for my laravel API. I installed the package:
https://yajrabox.com/docs/laravel-acl/3.0/introduction
It would be great if someone could explain to me how it works, all I want to do is get the permission when the user hits one API route.
I don't want to set the middleware in every route, because I'm going to do several routes and it would be a pain to set middleware every time, I want do it dynamically.
I tried to do it myself but it's not working. This is my code in Authserviceprovider:
public function boot(GateContract $gate)
{
$this->registerPolicies();
Passport::routes();
Passport::tokensExpireIn(Carbon::now()->addDays(15));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
$permissions = Permission::with('roles')->get();
foreach ($permissions as $permission)
{
$gate->define($permission->name, function (User $user) use ($permission) {
return $user->hasPermission($permission);
});
}
}
I'm doing like this: https://github.com/laracasts/laravel-5-roles-and-permissions-demo/tree/master/app
You can use middleware within your web.php / api.php file such as my example (web.php) below:
Route::group(['middleware' => ['verified']], function () {
Route::get('/', 'HomeController#index')->name('home');
});
As my example shows, this will check an account is verified before allowing it to view '/'
Updated
This is almost irrelevant to the question above but as the Op asked a secondary question within the comments to my answer: here is my middleware code to show the Op how the middleware will function:
public function handle($request, Closure $next)
{
$verified = Auth::user();
if ($verified->verified == 0)
{
Auth::logout();
Session::flash('error', "$verified->username, your email address hasn't been verified yet therefore you're unable sign in.");
return Redirect('/login');
}
return $next($request);
}

Laravel: Check Permission for Each Controller

I have a Middleware for Admin login where i am checking whether is user is admin or not. But now i want to check if an admin have permission to access the page or not. How can i do that?
My AdminMiddleware is:
public function handle($request, Closure $next)
{
if(Auth::check())
{
$user = Auth::user();
if($user->user_type=='employee')
{
return $next($request);
}
else
{
return redirect('/');
}
}
else
{
return redirect('/');
}
}
One way is to add the following code to each and every function of every controller.
if(Auth::user()->permission=='manage_employee'){
//code here
}
else
{
//redirect to access denied page
}
But this is not the correct way and time consuming. Is there any other way without using packages?
This is the proper way to use your middleware
Route::get('/your-url', 'YourController#yourFucntion')->middleware('admin');
Where admin is the name you register your middleware in your Kernel.php file :
to register it you have to insert this in $routeMiddleware part
'admin' => MustBeAdministrator::class,
If you wan to have different kind of admin check you can edit your route to pass a variable:
->middleware('admin:employee');
and you can get this variable in your middleware like this:
enter this below the comment #param \Closure $next :
#param string $permition
and modify your function:
public function handle($request, Closure $next, $permition)
Then use your permition variable in an if statement to do whatever you want to do.

How to add custom middleware inside a Route group in laravel

I have a Route group in laravel which has middleware of auth
Route::group(['middleware'=>'auth', function()
{
//Routes
});
Now these routes are only available to logged in users. I have a situation that logged in users have privileges. I have some routes that are only to be visited by logged in users AND if they have privilege of OWNER
In function I have started a session and stored privilege value.
I did something like this
Route::group(['middleware'=>'auth', function()
{
//Routes
if(session::get('privilege')
{
//Routes
}
});
This isn't working neither it's appropriate method. Can anyone tell me how add middleware inside a middleware?
There should be no logic inside your routes file(s) - these should simply define routes and nothing else. What you should do is define middleware which verifies privileges/roles your user has, you can specify parameters which are passed to the middleware like this:
Route::group(['middleware' => 'auth', function() {
Route::get('/my-route', 'Controller#method')->middleware('role:some_role');
Route::get('/my-other-route', 'Controller#otherMethod')->middleware('role:some_other_role');
});
Then in your middleware, you can access that parameter via a third argument in the handle method. With that value, you could verify the privileged/role the user has and then decide if the user should access that route:
public function handle($request, Closure $next, $role)
{
// Do something with $role
return $next($request);
}
If you're unsure about defining your own custom middleware, check out the docs here: https://laravel.com/docs/middleware
You will need to create a custom middleware called OWNER
php artisan make:middleware Owner
Will create a middleware file for you.
Then in the public function called handle u can do something like
if (Auth::user()->privilege == "OWNER") {
return $next($request);
}
return redirect('home');
So at the end your custom middleware will look something like this:
<?php
namespace App\Http\Middleware;
use Closure;
class Owner
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->privilege == "OWNER") {
return $next($request);
}
return redirect('home');
}
}
More about Laravel Middelware here

LARAVEL 5.4 ROLE ON MIDDLEWARE

i'm trying to setup my role on routing using middleware, but everytime i log in into my system, it redirects back on my login view.
here is my routing
Route::group(['middleware' => ['auth','admin']],function(){
Route::get('dashboard','RouteController#adminDashboard');
Route::get('admin',function(){
return 'this is admin page';
});
});
and here is my middleware
public function handle($request, Closure $next)
{
if(Auth::User()->id_role == 1){
return $next($request);
}
return redirect::to('dashboard');
}
can u guys helpme.
You're missing the initial slash.
Route::group(['middleware' => ['auth','admin']],function(){
Route::get('/dashboard','RouteController#adminDashboard');
Route::get('/admin',function(){
return 'this is admin page';
});
})
Or inside your controllers declare a construct function like this:
public function __contstruct(){
$this->middleware('auth');
}
Followed by your usual functions
If login is successful then the middleware checks the id, if the id is 1 then you return the next request ($next($request);). Your redirect never occurs.
So the next request is handled by your adminDashboard function in RouteController.
You should return your view in RouteController like this:
public function adminDashboard() {
return view('your-path-to-your-dashboard');
}
and change your route to this
Route::get('/', 'RouteController#adminDashboard');

Laravel Middleware - how to execute inside a controller method?

I am using multiple views for the same URL, depending if the user is logged in or not.. so mywebsite.com is routed like this:
Route::get('/', 'HomeController#redirector')->name('home');
The controller is this:
public function redirector(){
if(!\Auth::check()){
return view('welcome');
}
else{
return $this->index();
}
}
Now, when it runs the index function I need it to run the middleware 'auth', that updates and checks the user. The problem is, I cannot attach it to the route, since they might be unlogged causing a redirection loop. I tried this:
public function redirector(){
if(!\Auth::check()){
return view('welcome');
}
else{
$this->middleware('auth');
return $this->index();
}
}
It does not run the middleware.
If I put it in the costructor method attaching it to index, like this:
$this->middleware('auth', ['only' => 'index'])
it also won't run.
Any solutions to this?
if(!\Auth::check()){..} //this returns false if a user is logged in, are you sure that's what you want?
If not then remove the '!'
You can also put the redirection logic in the middleware instead. If you are using the auth middleware that ships with Laravel this is already in place. You just have to modify it as below and place the middleware call in the constructor.
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
return redirect()->guest('login');
}
return $next($request);
}

Categories