Laravel login and admin panel (after successful authentication) pages both on "/" - session

I want to have the login of my application and the admin panel (accessed after successful login) both accessible on "/".
I use the create method of a SessionsController for the login part (SessionsController.php):
class SessionsController extends \BaseController {
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
if ( Auth::check() ) return Redirect::to('homeAdmin');
//return View::make('homeLogin');
return View::make('homeLogin');
}
// Other methods, store, destroy...
}
I have my routes set like this (routes.php):
<?php
// Home page as guest displays a login form
Route::get('/', ['as' => 'homeLogin', 'uses' => 'SessionsController#create']);
// Authentication via the SessionsControlle
Route::resource('sessions', 'SessionsController');
// Pages for logged in users
Route::group(['before' => 'auth'], function()
{
// Home page with admin panel for authenticated users
Route::get('/', ['as' => 'homeAdmin']);
// Other pages from admin panel
Route::get('manageThis', ['as' => 'manageThis']);
Route::get('manageThat', ['as' => 'manageThat']);
});
And the filters are unchanged, ie (filters.php):
<?php
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
});
Route::filter('auth.basic', function()
{
return Auth::basic();
});
Route::filter('guest', function()
{
if (Auth::check()) return Redirect::to('/');
});
The thing is that I am constantly redirected to '/login' instead of to the 'homeLogin' route. I guess there is something to change in the guest filter but when I edited it, it got even worse and didn't solve the issue.

Have you tried putting homeLogin within a guest group? So like...
Route::group(['before' => 'guest'], function()
{
Route::get('/', ['as' => 'homeLogin', 'uses' => 'SessionsController#create']);
});
Otherwise you can manually check this in your controller/route programatically:
if(!Auth::user()) {
return View::make('guest.page');
}
For further info, check this answer also: Laravel 4: Two different view pages for a single URI based on auth status

Route should be one and programatically check on controller for both login view and dashboard view.You have two routes for this process.
Route::get('/', ['as' => 'homeLogin', 'uses' => 'SessionsController#create']);
Route::get('/', ['as' => 'homeAdmin']);
Delete one and check it on controller like this:
if(Auth::user()) {
return View::make('dashboard')->with('datas', $yourDatabaseQureiesForDashboard);
}
else
{
return View::make('login');
}

Related

How to assign two middleware to the same group of routes. Laravel

I have 3 Middleware with all different routes assigned. These are the routes that correspond to each user type.
Like this:
In my routes I have this
Route::group(['middleware' => 'auth'], function () {
Route::resource('/', 'DashController');
Route::get('/logout')->name('logout')->uses('Auth\LoginController#logout');
Route::group(['middleware' => ['director']], function () {
//survey
//questions
//groups
//forum
});
Route::group(['middleware' => ['super']], function () {
//import
});
Route::group(['middleware' => ['admin']], function () {
//semester
//users
//sections
//category
//classrooms
//careers
//courses
});
});
What I need to do is add the routes that are inside the director group also to the admin group. The admin middleware checks if the user is an admin or superadmin, so thats why the super group only has the import route.
I've tried nesting the group one inside the other like this:
Route::group(['middleware' => ['director', 'admin']], function () {
//survey
//questions
//groups
//forum
Route::group(['middleware' => ['admin']], function () {
//semester
//users
//sections
//category
//classrooms
//careers
//courses
});
});
I've also tried same as above but first group like this
Route::group(['middleware' => ['director'], ['admin']], function () {});
Nothing is working, in the sense of letting both share those routes. How can I do this?
Here is a way to use that cascading setup:
Have to think of this in reverse with the highest role needed to the lowest, since you have a funnel of permission here, where the top can access everything, the next down almost everything then the bottom the least.
Route::group(['roles' => 'super', 'middleware' => 'check', ...], function () {
// only routes for 'super admin'
Route::group(['roles' => 'admin', ...], function () {
// routes only for superadmin and admin
Route::group(['roles' => 'director', ...], function () {
// remaining routes that director, admin and super admin can access
Route::get('sometest', function () { })->name('for-all');
});
})
});
We are going to use the cascading ability of route groups with route parameter/attributes.
The route named for-all will end up with a action parameter named roles which will be an array, ['super', 'admin', 'director']. We can have the middleware use this so we know what to check for.
class CheckMiddleware
{
public function handle($request, Closure $next)
{
$roles = $request->route()->getAction('roles', []);
foreach ((array) $roles as $role) {
// if the user has this role, let them pass through
if (...) {
return $next($request);
}
}
// user is not one of the matching 'roles'
return redirect('/');
}
}
I do not know how you are checking the User to see what 'role' they have but that will come into play in this middleware.

Laravel middleware multi roles routing

I have problem to make routing with middleware multi roles
I have tried some in internet but still wont work
I have 3 roles, superadmin, admin and member
I want the superadmin and admin can access the add page
here is my code :
Route::group(['prefix' => 'staff', 'middleware' => 'auth'], function () {
Route::GET('/add', [
'uses' => 'StaffController#page_add',
'middleware' => 'rule:superadmin', ???
]);
});
I have tried to put 'middleware' => 'rule:superadmin|rule:admin'
but wont work
thank you
Create a middleware file eg Role.php
public function handle($request, Closure $next, ... $roles)
{
if (!Auth::check()) // I included this check because you have it, but it really should be part of your 'auth' middleware, most likely added as part of a route group.
return redirect('login');
$user = Auth::user();
if($user->isAdmin())
return $next($request);
foreach($roles as $role) {
// Check if user has the role This check will depend on how your roles are set up
if($user->hasRole($role))
return $next($request);
}
return redirect('login');
}
Finally in your web routes
Route::get('admin/scholen/overzicht', 'SchoolsController#overview')->middleware('role:editor,approver');
Route::get('admin/scholen/{id}/bewerken', 'SchoolsController#edit')->middleware('role:admin');
Check out this best answer for more details
Hey you can put a column named "role" in your users table then check it with a condition.
Route::get('/add', function() {
if (Auth::user()->role == 'superadmin' || Auth::user()->role == 'admin') {
return view('add-page');
}
else {
return view('error-page');
}
});

Laravel 5.5 administrator route issue

I have the below mentioned route:
Route::get('/', 'HomeController#index');
Route::get('administrator', array('before' => 'auth', 'uses' => 'Administrator\IndexController#index'));
//Route::get('/administrator', 'Administrator\IndexController#index');
Route::group(['prefix' => 'administrator'], function() {
Route::get('login', 'Administrator\IndexController#index')->name('login');
Route::post('login', 'Auth\LoginController#doLogin');
Route::get('logout', 'Auth\LoginController#logout');
});
My intention is when someone try to access http://127.0.0.1:8000/administrator/ this will go directly to the login page of the administrator.
However, when I tried to access the same, it said 404 not found.
IndexController under Administrator folder is looks below:
class IndexController extends Controller {
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('guest')->except('doLogout');
}
public function index() {
//$session = session()->all();
if(Auth::check() == 1){
return Redirect::intended('/administrator/dashboard')->with('successMessage', 'You have successfully logged in.');
}
//print_r($session);
//echo $session['_token'];
//if($session['_token'] == '')
$data = array();
$data['title'] = "Shop To My Door - Administrator Panel";
return view('Administrator.index.index', $data);
}
}
You have route and group with the same name "administrator"
My suggestion for routing:
Route::get('/', 'HomeController#index');
Route::group(['prefix' => 'administrator'], function() {
Route::get('/', 'Administrator\IndexController#index');
Route::get('login', 'Administrator\IndexController#login');
Route::post('login', 'Auth\LoginController#doLogin');
Route::get('logout', 'Auth\LoginController#logout');
});

working with laravel nested route group

I am using middleware for route groups and have three middlewares admin, teacher, and teacheradmin
Well admin is working fine but suppose I have 10 routes and all of them defined under group teacheradmin (working case for now)
but I want only 5 of those 10 routes to be accessed by middleware teacher and all 10 to be accessed by middleware teacheradmin
this is how I nested route groups
Route::group(['middleware' => 'teacheradmin'], function() {
//defined 5 routes only accessible by teacheradmin
Route::group(['middleware' => 'teacher'], function() {
//defined the other routes accessible by both teacher and teacheradmin
});
});
but the above nesting is not working, teacheradmin is not able to access the routes defined under teacher
plz I need a direction on how can I make it work
Update:
as per the answer I have defined middleware array for common routes
Route::group(['middleware' => ['teacher', 'teacheradmin']], function() {
//defined common routes
});
and the handle methods for teh two middleware is:
teacher
public function handle($request, Closure $next)
{
if(Auth::check())
{
if(Auth::user()->user_type != 'TEACHER')
{
return redirect()->route('dashboard');
}
return $next($request);
}
else
{
return redirect('/')
->withErrors('That username/password does not match, please try again !!!.');
}
}
teacheradmin
public function handle($request, Closure $next)
{
if(Auth::check())
{
if(Auth::user()->user_type != 'TEACHER_ADMIN')
{
return redirect()->route('dashboard');
}
return $next($request);
}
else
{
return redirect('/')
->withErrors('That username/password does not match, please try again !!!.');
}
}
and the dashboard route goes to this method
public function Dashboard(Request $request)
{
$user = Auth::user();
if($user->user_type === 'ADMIN') {
return redirect()->route('dashboardadmin');
} else if($user->user_type === 'TEACHER_ADMIN') {
return redirect()->route('dashboardteacher');
} else if($user->user_type === 'TEACHER') {
return redirect()->route('world_selection');
} else {
return redirect()->route('dashboardchild');
}
}
now the problem I am facing is when I am on dashboard and I try to access a common route as teacheradmin then it also goes to handle of teacher hence coming back to the same page again
Not sure why you are nesting them. You can attach multiple middleware via array notation to a group like this:
Route::group(['middleware' => 'teacheradmin'], function() {
//defined 5 routes only accessible by teacheradmin
});
Route::group(['middleware' => ['teacher', 'teacheradmin']], function() {
//defined the other routes accessible by both teacher and teacheradmin
});
Update:
I think what you are trying to do can be done by using just one middleware with middleware parameters:
Route::group(['middleware' => 'role:teacheradmin'], function() {
//defined 5 routes only accessible by teacheradmin
});
Route::group(['middleware' => 'role:teacher,teacheradmin'], function() {
//defined the other routes accessible by both teacher and teacheradmin
});
And in the role middleware:
public function handle($request, Closure $next, ...$roles)
{
dd($roles);
//Do your role checking here
return $next($request);
}
Disclaimer: ...$roles works from php 5.6 upwards.
As of Laravel 8 I would write it like:
Route::group(
['prefix' => 'v1', 'namespace' => 'Api'],
function(Router $router){
Route::get('/', function(){
return "Did you forget where you placed your keys??";
});
Route::post('/login', [LoginController::class, 'login']); //public
Route::get('/register', [LoginController::class, 'register']); //public
Route::group( //protected routes group
['middleware' => ['auth:sanctum']], //protected via some middleware
function () {
Route::get('/users', [UsersController::class, 'users']);
}
);
}
);

Redirect to Login page if ther user not logged in Laravel

I am using Laravel version 5. I have a route file for my project which contains plenty of lines. I need to put authentication like Redirect to login page if the user is not logged in. And I also want to prevent direct URL access if the user not logged in. What can I do?
And I have used below code
Route::group(array('before' => 'auth'), function(){
Route::get('/', 'HomeController#index');
});
But this prevents only for home page. I need to protect All my routes. And also suggest me how to reduce route file lines.
You can put as many routes in a Group as you like to
Route::group(array('before' => 'auth'), function(){
Route::get('/', 'HomeController#index');
Route::post('store', 'HomeController#store');
Route::get('show', 'AnotherController#index');
// ...
});
If you really need to protect all your routes, you could add
public function __construct()
{
$this->middleware('auth');
}
To your main controller class, Http/Controllers/Controller
Edit for your comment, taken from the docs, you may use
return redirect()->intended('view');
/**
* Handle an authentication attempt.
*
* #return Response
*/
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password]))
{
return redirect()->intended('dashboard');
}
}
}

Resources