Laravel 5.3 - set clear cache on middle not working - php

I want to prevent the user from clicking back the browsers button. Whenever user logged in and click browser's back button the page redirect back to login which is wrong. I create middleware and register it to the kernel and use it in my route as group but its not working. Here's the code
MIDDLEWARE
<?php
namespace App\Http\Middleware;
use Closure;
class ClearCache
{
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set("Cache-Control", "no-cache,no-store, must-revalidate");
return $response;
}
}
KERNEL
protected $routeMiddleware = [
....
// CUSTOM MIDDLEWARE GOES HERE
'clear.cache' => \App\Http\Middleware\ClearCache::class,
];
ROUTES
<?php
Route::group(['middleware' => 'guest'], function() {
Route::get('/', function () {
return view('welcome');
});
});
Auth::routes();
Route::group(['middleware' => 'auth'], function() {
Route::group(['middleware' => 'clear.cache'], function() {
Route::get('/home', 'HomeController#index');
});
});
After logging in when user clicks back button it redirects back on login page. Logged out is fine. Any help? :(

You can define multiple middleware for one group :
Route::group(['middleware' => ['auth', 'cache.clear']], function() {
But by default Laravel redirects users to $redirectTo defined in your Auth controllers. I don't understand why you are trying to avoid back click.

Related

how to check if user is logged in by his session in route and then call controller method in laravel?

I'm using Laravel 5.2. I want to check user session in routes file, so that if session is set user can visit dashboard otherwise redirect to login page.
I have used following code for this but it's not working. It's not giving any error and not redirecting him to login page. anyhow if I write same code in controller functioin, it works fine.
Route::group(['middleware' => ['web']], function () {
Route::get('dashboard/index', ['uses' => 'DashboardController#index'], function() {
$value = $request->session()->get('name', 'not_loggin');
if ($value == 'not_loggin') {
return redirect('/user/login');
}
});
});
it also didn't worked if I write it in constructor.
You should use the auth middleware:
Route::get('dashboard/index', [
'middleware' => 'auth',
'uses' => 'DashboardController#index'
]);

Laravel nested route group inverse middleware

I have a fairly complex application which makes use of custom authentication middleware. I have a route group like this:
Route::group(['prefix' => 'auth', 'middleware' => 'auth'], function() {
Route::get('/', function() {
echo 'private';
});
Route::group(['prefix' => 'public'], function() {
Route::get('/', function() {
echo 'public';
});
})
});
Now the auth middleware will redirect all requests which are not authenticated. The main group with the auth prefix is authenticated. However, I want the group public to be accessible even if the user is not authenticated.
So:
http://example.com/auth < must be authenticated
http://example.com/auth/some-sub-page < must be authenticated
http://example.com/auth/public < no need for authentication
So is there a way to add something like 'remove-middleware' => 'auth' to the nested group with the public prefix? Or would I have to restructure my route groups?
Why not just wrap the auth middleware around the non-public routes?
Route::group(['prefix' => 'auth'], function() {
// routes requiring auth
Route::group(['middleware' => 'auth']) {
Route::get('/', function() {
echo 'private';
});
}
// other routes
Route::group(['prefix' => 'public'], function() {
Route::get('/', function() {
echo 'public';
});
});
});
There may be a way to do a 'remove-middleware' type middleware, but that could get messy. This seems like the cleanest solution.
you can use withoutMiddleware method on your route.
Route::get('/example')->withoutMiddleware('auth')
You can also use withoutMiddleware on Route::group

Laravel auth on all requests (global auth?)

I am working on a Laravel project which is only intended to be used by backend admin staff. So, there is no separation of "standard user" and "admin user". So, I want to implement some sort of global auth filter on the entire project.
What I have so far is this on by app/routes.php
<?php
// Home route with login required
Route::get('/', array('as' => 'home', function () {
return View::make('hello');
}))->before('auth');
/*
* Global Auth Filter - All Guests Go To Login
*/
Route::filter('auth', function($route, $request) {
if (Auth::guest())
return Redirect::guest('login')
->with('login_error', 'Login required!');
});
/*
* Login Route Handler
*/
Route::get('login', array('as' => 'login', function () {
if (Auth::check())
return Redirect::route('home');
return View::make('login');
}))->before('guest');
/*
* Login Post Event Handler
*/
Route::post('login', function ()
{
// Parse form data
$user = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
// Try to login user
if (Auth::attempt($user))
{
// login success
return Redirect::route('home');
}
else
{
// Login error
return Redirect::route('login')
->withInput()
->with('login_error', 'Invalid username and/or password!');
}
});
/*
* Logout Route Handler
*/
Route::get('logout', array('as' => 'logout', function () {
Session::flush();
return Redirect::route('home');
}))->before('auth');
This works fine. If I got to the / page, it redirects me to /login route and from there I can login. Once logged in, I have a /logout link on the hello view and that also works (i.e. logging out).
This code above is my test code. In the real application I am working on (taking over the project from previous developer), the routes app/routes.php are setup like this:
<?php
Route::controller('dev', 'DevController');
Route::controller('orders', 'OrdersController');
Route::controller('customers', 'CustomersController');
Route::controller('picking', 'PickingController');
Route::controller('stock', 'StockController');
Route::controller('suppliers', 'SuppliersController');
Route::controller('warehouse', 'WarehouseController');
Route::controller('upload', 'UploadController');
Route::controller('apixero', 'XeroController');
Route::controller('api/orders', 'OrdersAPIController');
Route::controller('api/picking', 'PickingAPIController');
Route::controller('api/po', 'PurchaseOrdersAPIController');
Route::controller('api/products', 'ProductsAPIController');
Route::controller('api/customer', 'CustomerAPIController');
Route::controller('api/suppliers', 'SuppliersAPIController');
Route::controller('api/currency', 'CurrencyAPIController');
Route::controller('api/notes', 'NotesAPIController');
Route::get('/', function() {
return View::make('dashboard');
});
My question #1 is, how do I apply a "global" auth on requests with this app/routes.php? As the real application routes code seems to be different from what I have worked out in my test code..
Question #2 - Looking at my test code, can someone tell me at which point this filter gets executed:
Route::filter('auth', function($route, $request) { ... });
This code concept was taken out of a tutorial I was reading, but I noticed that my test code continues to work fine - even if I remove this code block. So, I am not entirely sure in which scenario the above code block is being executed.
Route filters are disabled when in the testing environment. To enable them, add Route::enableFilters() to your test.
To add a global auth filter - you could do this:
Route::get('/login')... //rest of code here
Route::get('logout')... //rest of code here
Route::group(array('before' => 'auth'), function()
{
Route::controller('dev', 'DevController');
Route::controller('orders', 'OrdersController');
...
Route::controller('api/notes', 'NotesAPIController');
Route::get('/', function() {
return View::make('dashboard');
});
});

laravel how to create page restriction

Please tell me how to restrict the page using laravel,
i have 3 users.
1. admin, 2. client, 3. partner
i want if admin is logged in then open only- admin.index page
and if client logged in then open only- client.index page
i used in route.php following code-
Route::group(array('before' => 'role'), function(){
Route::resource('admin','AdminController#index');
Route::resource('client','clientController#index');
Route::resource('partner','partnerController#index');
});
using above code this if no any user login then it's coming properly,
and suppose if admin logged in, then page redirect to AdminController but,
if i hard coded (url) hit clientController or partnerController like http://localhost/laravel-login/public/client then client page is coming.
so please tell me how to avoid these
sorry for my english..
thanks
You may use different route filters for each route and create individual filters, for example:
Route::group(array('before' => 'auth'), function() {
Route::resource('admin','AdminController#index');
Route::resource('client','clientController#index');
Route::resource('partner','partnerController#index');
});
In each controller create a __construct method and add filter like:
public function __construct()
{
// In your AdminController
$this->beforeFilter(function() {
if(Auth::user()->role->name != 'admin') return redirect::to('/'); // home
});
}
Same way declare other filters in other controllers:
public function __construct()
{
// In your clientController
$this->beforeFilter(function() {
if(Auth::user()->role->name != 'client') return redirect::to('/'); // home
});
}
And so on. Check more on Laravel website about controller filtering.
The best way to restrict controllers to make new middleware , where you can define rules before the request. example :
I have a admin controller only register users with admin role can access it .
to do so when you define the route include the middleware .
// namespace = indicate where my controller is (sub folder )
// middleware = indicate what restriction i want for my controller you can pass one middleware or array of midlewares
Route::group([ 'namespace' => 'Admin','middleware' => ['auth' , 'IsAdmin'] ], function()
{
Route::resource('admin/posts', 'PostsController');
});
to create the middle ware and register it follow the documentation
look this is my middleware after
<?php
namespace App\Http\Middleware;
use Closure;
class IsAdmin
{
public function handle($request, Closure $next)
{
if($request->user()->is_admin == false ){
return redirect('/');
}
return $next($request);
}
}

Laravel auth check for all pages

I have created the Authentication, and its working perfectly. But there is some problem in checking the inner pages. For example,
Route::get('/', array('before' => 'auth' , 'do'=> function(){
return View::make('home.index');
}));
The index page is only visible for logged in users. But whenever I have go to the inner pages, for example example.com/products. The products page can be visible without log in.
Here is my solution.
/**
* Groups of routes that needs authentication to access.
*/
Route::group(array('before' => 'auth'), function()
{
Route::get('user/logout', array(
'uses' => 'UserController#doLogout',
));
Route::get('/', function() {
return Redirect::to('dashboard');
});
Route::get('dashboard', array(
'uses' => 'DashboardController#showIndex',
));
// More Routes
});
// Here Routes that don't need Auth.
There are several ways of applying filters for many routes.
Putting rotues into Route::group() or if you using controllers add the filter there, add it in the Base_Controller so it will be applied to all. You can also use filter patterns and use a regex which applies the filter to all except a few you don't want to.
Documentation
Route filters: http://laravel.com/docs/routing#route-filters
Example to the pattern filter, as the others are basicly in the docs. This one could be the fastest but also the most problematic because of the problematic way of registering a regex in this function (the * is actually converted into (.*)).
Route::filter('pattern: ^(?!login)*', 'auth');
This will apply auth to any route except example.com/login.
Route::group(['middleware' => ['auth']], function()
{
Route::get('list', 'EventsController#index');
});
Read more on the documentation page:
https://laravel.com/docs/5.2/routing#route-groups
There may be a better way but I take a whitelist approach. Everything is blocked from public except for what the pages I put in this array.
// config/application.php
return array(
'safe' => array(
'/',
'card/form_confirm',
'record/form_create',
'card/form_viewer',
'user/login',
'user/quick_login',
'user/register',
'info/how_it_works',
'info/pricing',
'info/faq',
'info/our_story',
'invite/accept',
'user/terms',
'user/privacy',
'email/send_email_queue',
'user/manual_login',
'checkin/',
'checkin/activate',
'system/list',
),
// routes.php
Route::filter('before', function()
{
// Maintenance mode
if(0) return Response::error( '503' );
/*
Secures parts of the application
from public viewing.
*/
$location = URI::segment(1) . '/' . URI::segment(2);
if(Auth::guest() && !in_array( $location, Config::get('application.safe')))
return Redirect::to( 'user/login' );
});
this code working fine with me
Auth::routes();
Route::group(['middleware' => 'auth'], function () {
// Authentication Routes...
Route::get('/', 'HomeController#index')->name('home');
});
The same problem can be solved using a BaseController to extends all Controller have must logged user.
Example:
class SomeController extends BaseController
{
public function index() { return view('some.index');}
}
just add a __construct() method to BaseController
class BaseController extends Controller
{
protected $redirectTo = '/myIndex'; // Redirect after successfull login
public function __construct()
{
$this->middleware('auth'); // force all controllers extending this to pass auth
}
}
More info here
Just check if user is logged in in your views.
Or restrict all controller (if you use it)
Or check Route Groups, and give a filter to whole group of routes: http://laravel.com/docs/routing#groups
Route::filter('pattern: /*', array('name' => 'auth', function()
{
return View::make('home.index');
}));
It worked for me . take a look at it.
Route::when('*', 'auth.basic');
Route::get('api/getactorinfo/{actorname}', array('uses' =>'ActorController#getActorInfo'));
Route::get('api/getmovieinfo/{moviename}', array('uses' =>'MovieController#getMovieInfo'));
Route::put('api/addactor/{actorname}', array('uses' =>'ActorController#putActor'));
Route::put('api/addmovie/{moviename}/{movieyear}', array('uses' =>'MovieController#putMovie'));
Route::delete('api/deleteactor/{id}', array('uses' =>'ActorController#deleteActor'));
Route::delete('api/deletemovie/{id}', array('uses' =>'MovieController#deleteMovie'));

Categories