Laravel auth on all requests (global auth?) - php

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');
});
});

Related

Why doesent it redirect to the right index

Sorry for this question, but I have problems.
I don´t understand why it makes like this.
on my localhost I have a page, and when i go to that page I add localhost/transporter/public
And in that public I have index.php
And if I want to go to user page I login in on localhost/transporter/public/login
And I ads up in localhost/transporter/public/dashboard
And if I want to go to provider I login at localhost/transporter/public/provider/login
And the admin page for provider is at localhost/transporter/public/provider/
I have everything setup in routes/web.php
/*
|--------------------------------------------------------------------------
| Provider Authentication Routes
|--------------------------------------------------------------------------
*/
Route::post('/provider/verify-credentials', 'ProviderResources\ProfileController#verifyCredentials');
Route::post('/user/verify-credentials', 'UserApiController#verifyCredentials');
Route::group(['prefix' => 'provider'], function () {
Route::get('auth/facebook', 'Auth\SocialLoginController#providerToFaceBook');
Route::get('auth/google', 'Auth\SocialLoginController#providerToGoogle');
Route::post('/send/otp' , 'ProviderAuth\TokenController#send_otp');
Route::get('/login', 'ProviderAuth\LoginController#showLoginForm');
Route::post('/login', 'ProviderAuth\LoginController#login');
Route::post('/logout', 'ProviderAuth\LoginController#logout');
Route::get('/register', 'ProviderAuth\RegisterController#showRegistrationForm');
Route::post('/register', 'ProviderAuth\RegisterController#register');
Route::post('/password/email', 'ProviderAuth\ForgotPasswordController#sendResetLinkEmail');
Route::post('/password/reset', 'ProviderAuth\ResetPasswordController#reset');
Route::get('/password/reset', 'ProviderAuth\ForgotPasswordController#showLinkRequestForm');
Route::get('/password/reset/{token}', 'ProviderAuth\ResetPasswordController#showResetForm');
});
I moved the page to another webhost were I have SSL so I need to go to ex. https://root.se to come to the page.
And if I want to go to user I login at https://root.se/login and for provider https://root.se/provider/login
The problem I have is that it provider is not getting the root/resources/view/provider/index.blade.php, it get the main root/resources/view/index.php
this 2 pages is the same on localhost and https://root
What can it be.
Uppdate:
I think it this one in app/http/controller/ProviderController.php
public function index()
{
return view('provider.index');
}
and this one in app/Http/Controllers/ProviderAuth/LoginController.php
public $redirectTo = '/provider/';
UPPDATE:
I have now copy routes and resources\views from my localhost server, and provider is showing the right one, so possibly it something wrong in the web.php routes or resources\views.
I now the problems now, it´s this 2 routes that is the problem.
The language switcher.
// Route::get('/{locale?}', function ($locale = null) {
// if (isset($locale) && in_array($locale, config('app.available_locales'))) //{
// app()->setLocale($locale);
// }
// return view('index');
// });
// Route::get('lang/{locale}', function ($locale) {
// app()->setLocale($locale);
// session()->put('locale', $locale);
// return redirect()->back();
// });
this one is the problem :
return view('index');

Redirect to other route when session has expired in Laravel 5.8

I´m trying to return another route because in my case login it´s a modal page, and when the session has expired, return to this route but it does not exist. I don´t know how I would do this.
I can see this in web: if(Auth::check()){ return route('/')} but i don´t know where i´m putting this code.
Also i can see this: in 'App\Exception\Handler' put this:
if ($exception instanceof AuthenticationException) {
return redirect('/');
}
How I would can to do this?
Thanks for helping me
You can create a route to check sessions, every minute it will check session exists or not.
You can use like this:
Blade part:
#if (Auth::user())
<script>
$(function() {
setInterval(function checkSession() {
$.get('/is-logged-in', function(data) {
// if session was expired
if (!data.isLoggedIn) {
// redirect to login page
// or, may be better, just reload page
location.reload();
}
});
}, 60000); // You can change it
});
</script>
#endif
Route:
Route::get('is-logged-in', 'Auth\AuthController#checkSession');
Controller:
public function checkSession()
{
return Response::json(['isLoggedIn' => Auth::check()]);
}
Laravel probably already has what you need. Take a look at the App\Http\Middleware\Authenticate class. This is a middleware that will redirect user to 'login' named route (by default), if the session has expired.
By default none of the routes you put in routes/web.php are protected by this middleware, but you can change this.
Method 1: Add a auth middleware in your controller's constructor:
public function __construct()
{
$this->middleware('auth');
}
Method 2: Add a auth middleware for one of your routes:
Route::get('profile', function () {
// Only authenticated users may enter...
})->middleware('auth');
Method 3: Adding all protected routes into group:
Route::group(['middleware' => ['auth']], function () {
// All your protected routes go here
});
Then you can easily change the URL which will be used for redirecting users with expired session (not authenticated). Just edit the App\Http\Middleware\Authenticate::redirectTo() method and return your URL, for example:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('yourLoginRouteName');
}
}

Laravel PHP: Using Filters with Routes to grant admin access only

I'm trying to protect some of my web pages by only allowing administrators to access them. I've been trying to use a filter to protect these pages but it isn't working as intended. For instance, if a user tries to enter an admin URL into their web browser, the browser still grants the unauthorized user access.
EDIT: Made changes to my code below so that the admin pages are only accessed after successfully logging in.
Routes.php:
// All users have access to this home page
Route::get('/', ['as' => 'home', function()
{
// Default home page
return View::make('index');
}
]);
//Admin access only
Route::get('admin/index', ['before' => 'auth',function()
{
//Only allow admin access to this page
return View::make('admin_index');
}
]);
filters.php (The default filters.php file):
/* Default 'filters.php' is fine. */
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
});
Controller (SesssionsController.php):
public function index()
{
return View::make('sessions.index');
}
/*
Show the form for creating a new resource
*/
public function create()
{
return View::make('sessions.create');
}
public function store()
{
// validate
$input = Input::all();
$attempt = Auth::attempt([
'email'=> $input['email'],
'password' => $input['password']
]);
// If authentication passes, take the user back to the homepage (For Now)
/* EDIT: Changed 'Redirect::intended(admin/index)' to 'Redirect::to('admin/index')... since that was giving me problems */
if ($attempt) return Redirect::to('admin/index')->with('flash_message', 'Welcome ' . $input['email']. ', you are logged in!');
return Redirect::back()->with('flash_message', 'Invalid credentials.')->withInput();
}
After making these changes, I ran 'php artisan dump-autoload' in order for the changes in my Controller to take effect and now my 'admin/index' page can only be accessed after successfully logging in.
Hope this information helps people out!

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