Protecting some routes with auth middleware but leaving others unprotected - laravel

I have a protected route group:
Route::group(['prefix' => 'member', 'middleware' => 'auth'], function () {
Route::get('/')->name('member.home')->uses('MemberController#index');
Route::get('show')->name('member.show')->uses('MemberController#show');
// ...various additional protected member routes...
});
However, I have two routes that should not be protected:
Route::get('member/pay')->name('member.pay')->uses('MemberController#pay');
Route::get('member/confirm/{payment}')->name('member.confirm')->uses('MemberController#confirm');
So long as 'middleware' => 'auth' is applied to that separate route group, ALL of the member prefixed routes are covered by it even if I don't place them in the group.
I've tried moving the unprotected routes above and below the protected route group but I still get 401 unauthorized unless I remove the middleware entirely.
This isn't impacting any of my other routes...only the ones prefixed by member.
How can I exclude these two routes from auth?

One approach would be to remove the middleware assignment from the Route group and instead assign the middleware in your MemberController constructor. That way you can exclude which methods should not have it applied, like so:
class MemberController extends Controller
{
/**
* Instantiate a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth')->except(['pay', 'confirm']);
}
}

Use nested groups like this.
Route::group([ 'prefix' => 'member' ], function() {
// Protected routes
Route::group([ 'middleware' => 'auth' ], function() {
Route::get('/', 'MemberController#index')->name('member.home');
Route::get('show', 'MemberController#show')->name('member.show');
// ...various additional protected member routes...
});
// Non protected routes
Route::get('pay', 'MemberController#pay')->name('member.pay');
Route::get('confirm/{payment}', 'MemberController#confirm')->name('member.confirm');
// ...various additional non protected member routes...
});

how about
Route::group(['prefix' => 'member'], function () {
Route::get('/')->name('member.home')->uses('MemberController#index')->middleware('auth');
Route::get('show')->name('member.show')->uses('MemberController#show')->middleware('auth');
//
Route::get('member/pay')->name('member.pay')->uses('MemberController#pay');
Route::get('member/confirm/{payment}')->name('member.confirm')->uses('MemberController#confirm');
});

Related

Controller action is not available

I am not familiar with laravel but from what I red I made this:
My controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ChatController extends Controller
{
public function index(Request $request)
{
var_dump(123123);die;
if (!Auth::check()) {
return redirect('/');
}
return 1;
}
}
Now I am trying to request it like domain.com/open-chat. And my web.php configuration about it is:
Route::get('/open-chat', 'ChatController#index');
But I am getting redirected to the home page. I`ve checked the middleware controllers if some of it redirects me but no. The other controllers ( which were already made when I came ) works fine. What am I missing ?
EDIT
web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/clear-cache', function() {
Artisan::call('cache:clear');
return "Cache is cleared";
});
Route::get('/config-cache', function() {
Artisan::call('config:cache');
return "Config is cleared";
});
Route::get('/view', function() {
Artisan::call('view:clear');
return "View is cleared";
});
/* Route::get('/', function () {
return view('welcome');
}); */
Route::group(['prefix' => 'siteadmin', 'namespace' => 'Admin'], function () {
Route::get('/', 'Auth\LoginController#showLoginForm');
Route::post('login', 'Auth\LoginController#login')->name('admin.login');
Route::post('logout', 'Auth\LoginController#logout')->name('admin.logout');
});
Route::group(['prefix'=>'siteadmin', 'namespace' => 'Admin','middleware' => 'auth'], function () {
Route::get('/dashboard', 'DashboardController#index')->name('dashboard.index');
Route::get('/edit-profile', 'CommonController#editProfile');
Route::post('/updateprofile', 'CommonController#updateprofile');
/**
Routes for site settings
**/
Route::get('/site-settings', 'SiteSettingController#index')->name('sitesettings.index');
Route::post('/site-settings/store', 'SiteSettingController#store')->name('sitesettings.save');
Route::get('/subject-categories', 'SubjectCategoriesController#index')->name('subject-categories.index');
Route::get('/subject-categories/create', 'SubjectCategoriesController#create')->name('subject-categories.create');
Route::post('/subject-categories/store', 'SubjectCategoriesController#store')->name('subject-categories.store');
Route::get('/subject-categories/edit/{id}', 'SubjectCategoriesController#edit')->name('subject-categories.edit');
Route::post('/subject-categories/update/{id}', 'SubjectCategoriesController#update')->name('subject-categories.update');
Route::get('/subject-categories/drop/{id}', 'SubjectCategoriesController#drop')->name('subject-categories.drop');
Route::post('/subject-categories/delete-image/{id}', 'SubjectCategoriesController#deleteImage');
/**
Routes for teachers users
**/
Route::get('/users/teachers', ['middleware'=>'auth','uses'=>'UserController#getTeachersList'])->name('teachers.index');
Route::get('/users/teachers/create', ['middleware'=>'auth','uses'=>'UserController#createTeacher'])->name('teachers.create');
Route::post('/users/teachers/save', ['middleware'=>'auth','uses'=>'UserController#saveTeacher'])->name('teachers.save');
Route::get('/users/teachers/edit/{id}', ['middleware'=>'auth','uses'=>'UserController#editTeacher'])->name('teachers.edit');
Route::get('/users/teachers/show/{id}', ['middleware'=>'auth','uses'=>'UserController#showTeacher'])->name('teachers.show');
Route::post('/users/teachers/update/{id}', ['middleware'=>'auth','uses'=>'UserController#updateTeacher'])->name('teachers.update');
Route::get('/users/teachers/delete/{id}', ['middleware'=>'auth','uses'=>'UserController#deleteTeacher']);
Route::get('/users/teachers/change-status/{id}', ['middleware'=>'auth','uses'=>'UserController#changeTeacherStatus']);
Route::post('/users/get-cities-by-country', ['middleware'=>'auth','uses'=>'UserController#getCitiesByCountry']);
Route::get('/users/teachers/messages/{id}', ['middleware'=>'auth','uses'=>'UserController#getTeacherMessageThreads'])->name('teachers.messages');
Route::get('/users/teachers/view-message/{id}', ['middleware'=>'auth','uses'=>'UserController#getAllMessagesByThreadID'])->name('teacher.view-message');
Route::post('/users/teachers/delete-profile-image/{id}', ['middleware'=>'auth','uses'=>'UserController#deleteTeacherProfileImage']);
/**
Routes for driver users
**/
Route::get('/users/students', ['middleware'=>'auth','uses'=>'UserController#getStudentsList'])->name('students.index');
Route::get('/users/students/create', ['middleware'=>'auth','uses'=>'UserController#createStudent'])->name('students.create');
Route::post('/users/students/save', ['middleware'=>'auth','uses'=>'UserController#saveStudent'])->name('students.save');
Route::get('/users/students/edit/{id}', ['middleware'=>'auth','uses'=>'UserController#editStudent'])->name('students.edit');
Route::get('/users/students/show/{id}', ['middleware'=>'auth','uses'=>'UserController#showStudent'])->name('students.show');
Route::post('/users/students/update/{id}', ['middleware'=>'auth','uses'=>'UserController#updateStudent'])->name('students.update');
Route::get('/users/students/delete/{id}', ['middleware'=>'auth','uses'=>'UserController#deleteStudent']);
Route::get('/users/students/change-status/{id}', ['middleware'=>'auth','uses'=>'UserController#changeStudentStatus']);
/**
Routes for countries
**/
Route::get('/countries', ['middleware'=>'auth','uses'=>'CountryController#index'])->name('countries.index');
Route::get('/countries/create', ['middleware'=>'auth','uses'=>'CountryController#create'])->name('countries.create');
Route::post('/countries/save', ['middleware'=>'auth','uses'=>'CountryController#store'])->name('countries.save');
Route::get('/countries/edit/{id}', ['middleware'=>'auth','uses'=>'CountryController#edit'])->name('countries.edit');
Route::get('/countries/show/{id}', ['middleware'=>'auth','uses'=>'CountryController#show'])->name('countries.show');
Route::post('/countries/update/{id}', ['middleware'=>'auth','uses'=>'CountryController#update'])->name('countries.update');
Route::get('/countries/delete/{id}', ['middleware'=>'auth','uses'=>'CountryController#destroy']);
Route::get('/countries/change-status/{id}', ['middleware'=>'auth','uses'=>'CountryController#changeStatus']);
Route::post('/countries/delete-image/{id}', ['middleware'=>'auth','uses'=>'CountryController#deleteImage']);
/**
Routes for cities
**/
Route::get('/cities', ['middleware'=>'auth','uses'=>'CityController#index'])->name('cities.index');
Route::get('/cities/create', ['middleware'=>'auth','uses'=>'CityController#create'])->name('cities.create');
Route::post('/cities/save', ['middleware'=>'auth','uses'=>'CityController#store'])->name('cities.save');
Route::get('/cities/edit/{id}', ['middleware'=>'auth','uses'=>'CityController#edit'])->name('cities.edit');
Route::get('/cities/show/{id}', ['middleware'=>'auth','uses'=>'CityController#show'])->name('cities.show');
Route::post('/cities/update/{id}', ['middleware'=>'auth','uses'=>'CityController#update'])->name('cities.update');
Route::get('/cities/delete/{id}', ['middleware'=>'auth','uses'=>'CityController#destroy']);
Route::get('/cities/change-status/{id}', ['middleware'=>'auth','uses'=>'CityController#changeStatus']);
Route::post('/cities/delete-image/{id}', ['middleware'=>'auth','uses'=>'CityController#deleteImage']);
/**
Routes for subjects
**/
Route::get('/subjects', ['middleware'=>'auth','uses'=>'SubjectController#index'])->name('subjects.index');
Route::get('/subjects/create', ['middleware'=>'auth','uses'=>'SubjectController#create'])->name('subjects.create');
Route::post('/subjects/save', ['middleware'=>'auth','uses'=>'SubjectController#store'])->name('subjects.save');
Route::get('/subjects/edit/{id}', ['middleware'=>'auth','uses'=>'SubjectController#edit'])->name('subjects.edit');
Route::get('/subjects/show/{id}', ['middleware'=>'auth','uses'=>'SubjectController#show'])->name('subjects.show');
Route::post('/subjects/update/{id}', ['middleware'=>'auth','uses'=>'SubjectController#update'])->name('subjects.update');
Route::get('/subjects/delete/{id}', ['middleware'=>'auth','uses'=>'SubjectController#destroy']);
Route::get('/subjects/change-status/{id}', ['middleware'=>'auth','uses'=>'SubjectController#changeStatus']);
/**
Routes for classes
**/
Route::get('/classes', ['middleware'=>'auth','uses'=>'ClassController#index'])->name('classes.index');
Route::get('/classes/create', ['middleware'=>'auth','uses'=>'ClassController#create'])->name('classes.create');
Route::post('/classes/save', ['middleware'=>'auth','uses'=>'ClassController#store'])->name('classes.save');
Route::get('/classes/edit/{id}', ['middleware'=>'auth','uses'=>'ClassController#edit'])->name('classes.edit');
Route::get('/classes/show/{id}', ['middleware'=>'auth','uses'=>'ClassController#show'])->name('classes.show');
Route::post('/classes/update/{id}', ['middleware'=>'auth','uses'=>'ClassController#update'])->name('classes.update');
Route::get('/classes/delete/{id}', ['middleware'=>'auth','uses'=>'ClassController#destroy']);
Route::get('/classes/change-status/{id}', ['middleware'=>'auth','uses'=>'ClassController#changeStatus']);
Route::post('/classes/get-subjects-by-category', ['middleware'=>'auth','uses'=>'ClassController#getSubjectsByCategory']);
/**
Routes for sliders
**/
Route::get('/sliders', 'SliderController#index')->name('sliders.index');
Route::get('/sliders/create', 'SliderController#create')->name('sliders.create');
Route::post('/sliders/store', 'SliderController#store')->name('sliders.save');
Route::get('/sliders/edit/{id}', 'SliderController#edit')->name('sliders.edit');
Route::post('/sliders/update/{id}', 'SliderController#update')->name('sliders.update');
Route::get('/sliders/delete/{id}', 'SliderController#destroy')->name('sliders.delete');
Route::get('/sliders/change-status/{id}', ['middleware'=>'auth','uses'=>'SliderController#changeStatus']);
Route::post('/sliders/delete-image/{id}', 'SliderController#deleteImage');
/**
Routes for teacher classes
**/
Route::get('/teacher-classes', 'TeacherClassController#index')->name('teacher-classes.index');
Route::get('/teacher-classes/create', 'TeacherClassController#create')->name('teacher-classes.create');
Route::post('/teacher-classes/store', 'TeacherClassController#store')->name('teacher-classes.save');
Route::get('/teacher-classes/edit/{id}', 'TeacherClassController#edit')->name('teacher-classes.edit');
Route::post('/teacher-classes/update/{id}', 'TeacherClassController#update')->name('teacher-classes.update');
Route::get('/teacher-classes/delete/{id}', 'TeacherClassController#destroy')->name('teacher-classes.delete');
Route::post('/teacher-classes/get-subjects-by-category', 'TeacherClassController#getSubjectsByCategory');
Route::post('/teacher-classes/get-classes-by-category-and-subject', 'TeacherClassController#getClassesBySubjectAndCategory');
/**
Routes for orders
**/
Route::get('/orders', 'OrderController#index')->name('orders.index');
Route::get('/orders/show/{id}', 'OrderController#show')->name('orders.show');
Route::get('/orders/export-orders', 'OrderController#exportOrders')->name('orders.export-orders');
/**
Routes for bookings
**/
Route::get('/bookings', 'BookingController#index')->name('bookings.index');
Route::get('/bookings/teacher-bookings/{teacher_id}', 'BookingController#getTeacherAllBookings')->name('bookings.bookings');
Route::get('/bookings/show/{id}', 'BookingController#show')->name('bookings.show');
Route::get('/bookings/export-teacher-bookings/{teacher_id}', 'BookingController#exportTeacherBookings')->name('bookings.export-teacher-bookings');
/**
Routes for bookings
**/
Route::get('/messages', 'MessageController#index')->name('messages.index');
Route::get('/messages/show/{id}', 'MessageController#show')->name('messages.show');
/**
Routes for reviews
**/
Route::get('/reviews', 'ReviewController#index')->name('reviews.index');
Route::get('/reviews/show/{id}', 'ReviewController#show')->name('reviews.show');
/**
Routes for blogs
**/
Route::get('/blogs', 'BlogController#index')->name('blogs.index');
Route::get('/blogs/create', 'BlogController#create')->name('blogs.create');
Route::post('/blogs/store', 'BlogController#store')->name('blogs.save');
Route::get('/blogs/edit/{id}', 'BlogController#edit')->name('blogs.edit');
Route::post('/blogs/update/{id}', 'BlogController#update')->name('blogs.update');
Route::get('/blogs/delete/{id}', 'BlogController#destroy')->name('blogs.delete');
Route::get('/blogs/change-status/{id}', ['middleware'=>'auth','uses'=>'BlogController#changeStatus']);
Route::post('/blogs/delete-image/{id}', 'BlogController#deleteImage');
});
Auth::routes();
Route::get('{locale?}', 'HomeController#index');
Route::get('/en', 'HomeController#index');
Route::get('/open-chat', 'ChatController#index');
Route::get('/ar', 'HomeController#index');
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/get-cities-by-country', 'SearchController#getCitiesByCountry');
Route::post('/get-subjects-by-category', 'SearchController#getSubjectsByCategory');
Route::post('/register', 'CommonController#register');
Route::post('/login', 'CommonController#login');
Route::post('/forgot-password', 'CommonController#forgotPassword');
Route::get('/{locale?}/reset-password/{token}', 'CommonController#resetPassword');
Route::post('/{locale?}/resetpassword', 'CommonController#resetNewPassword')->name('reset-pass');
Route::get('/{locale?}/classes/search', 'ClassController#searchClasses')->name('search');
Route::get('/{locale?}/classes/all-cities', 'ClassController#getAllCitiesClasses');
Route::get('/{locale?}/classes/{type}/{id}', 'ClassController#getClassesByType');
Route::get('/{locale?}/view-class/{id}', 'ClassController#viewTeacherClassDetails')->name('view-class');
Route::get('/{locale?}/finish-class/{id}', 'ClassController#finishTeacherClass')->name('finish-class');
Route::post('/create-booking', 'CommonController#createBooking');
Route::post('/{locale?}/submit-review', 'CommonController#submitReview');
Route::get('/{locale?}/blogs', 'HomeController#getAllBlogs')->name('blogs');
Route::get('/{locale?}/blogs/{slug}', 'HomeController#getBlogDetails')->name('blogs.detail');
Route::get('/paypal/checkout/{order}/completed', [
'name' => 'PayPal Express Checkout',
'as' => 'paypal.checkout.completed',
'uses' => 'User\BookingController#completed',
]);
Route::get('/paypal/checkout/{order}/cancelled', [
'name' => 'PayPal Express Checkout',
'as' => 'paypal.checkout.cancelled',
'uses' => 'User\BookingController#cancelled',
]);
Route::post('/webhook/paypal/{order?}/{env?}', [
'name' => 'PayPal Express IPN',
'as' => 'webhook.paypal.ipn',
'uses' => 'User\BookingController#webhook',
]);
/**
User dashboard routes start
**/
Route::group(['prefix'=>'{locale?}/user', 'namespace' => 'User','middleware' => 'auth'], function () {
Route::get('/dashboard', 'DashboardController#index')->name('user.dashboard');
Route::get('/edit-profile', ['uses'=>'ProfileController#editProfile'])->name('user.edit-profile');
Route::post('/update-profile/{id}', ['uses'=>'ProfileController#updateProfile'])->name('user.update-profile');
Route::post('/update-image/{id}', ['uses'=>'ProfileController#updateUserImage'])->name('user.update-image');
Route::get('/change-password', ['uses'=>'ProfileController#changePassword'])->name('user.change-password');
Route::post('/update-password', ['uses'=>'ProfileController#updatePassword'])->name('user.update-password');
Route::get('/my-classes', ['uses'=>'ClassController#getTeacherClasses'])->name('user.my-classes');
Route::get('/my-classes/add-new-class', ['uses'=>'ClassController#createNewClass'])->name('user.add-new-class');
Route::post('/my-classes/save-class', ['uses'=>'ClassController#saveClass'])->name('user.save-class');
Route::get('/my-classes/edit-class/{id}', ['uses'=>'ClassController#editClass'])->name('user.edit-class');
Route::post('/my-classes/update-class/{id}', ['uses'=>'ClassController#updateClass'])->name('user.update-class');
Route::get('/my-classes/delete-class/{id}', ['uses'=>'ClassController#deleteClass']);
Route::post('/get-subjects-by-category', ['uses'=>'ClassController#getSubjectsByCategory']);
Route::post('/get-classes-by-category-and-subject', ['uses'=>'ClassController#getClassesByCategoryAndSubject']);
Route::get('/my-bookings', ['uses'=>'BookingController#getAllBookings'])->name('user.my-bookings');
Route::get('/my-bookings/view-booking-details/{id}', ['uses'=>'BookingController#viewBookingDetails'])->name('user.view-booking-details');
Route::get('/my-bookings/cancel-booking/{type}/{id}', ['uses'=>'BookingController#cancelBooking']);
Route::get('/my-bookings/accept-booking/{id}', ['uses'=>'BookingController#acceptBooking']);
Route::post('/make-a-payment', ['uses'=>'BookingController#makePayment'])->name('user.make-payment');
Route::get('/my-orders', ['uses'=>'OrderController#getAllOrders'])->name('user.my-orders');
Route::get('/messages', ['uses'=>'MessageController#getMessageThreads'])->name('user.messages');
Route::get('/messages/view-messages/{thread_id}', ['uses'=>'MessageController#getAllMessagesByThreadID'])->name('user.view-messages');
Route::post('/messages/send-message', ['uses'=>'MessageController#sendMessage']);
Route::get('/reviews', ['uses'=>'BookingController#getAllReviews'])->name('user.reviews');
});
Extended Controller.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
This rule Route::get('{locale?}', 'HomeController#index'); is catching all routes because it's always true. so Laravel follows this route.
the problem is not about Route::get('/open-chat', 'ChatController#index'); if you put any route after that one, it won't work.
we usually use this to catch all request to forward somewhere like Vuejs router or show 404 message.
Route::any('{catchall}', 'CatchAllController#handle')->where('catchall', '.*');
and these are pretty same. if you put Route::get('{locale?}', 'HomeController#index'); at the end of your router file, everything should work fine.
It's normal, var_dump doest stop the script and die should be die(). Instead, use dd(123123). Everything is fine with the controller.
Since the route doesn't have the auth middleware, we can assume that the route is open to everyone. In the controller, you are checking if the use is authenticated, if not, redirect to /.

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 except a single route from auth middleware

I have a route group which is protected by the auth middleware, and inside of this group I want to except one route. But this route is also located in another route group. So when I try to move it out of this group, it is not working.
How can I fix this problem, and except a UrlProfile function from auth middleware?.. I am using Laravel 5.1
Route::group(['middleware' => 'auth'], function () {
// some other routes ...
Route::group(['namespace' => 'Lawyer'], function() {
Route::get('profile/{name}', 'ProfileController#UrlProfile');
}
};
Can you try this?
Route::group(['namespace' => 'Lawyer'], function () {
Route::get('profile/{name}', 'ProfileController#UrlProfile');
Route::group(['middleware' => 'auth'], function() {
..
..
..
)};
)};
If I understood your problem correctly, This should also work.
You can add this in your controller.
You can insert the name of your function in the except section and it will be excluded from the middleware. [Reference]
public function __construct()
{
$this->middleware('auth')->except(['yourFunctionName']);
}

Laravel authenticated dynamic subdomain routing

I'm trying to get authenticated subdomain routing working for some specific variable subdomains:
app.example.com
staging.app.example.com
testing.app.example.com
These should be guarded by the auth middleware. They all essentially reference app.example.com but for different environments.
Everything that hits these domains should go to the guest routes:
example.com
staging.example.com
testing.example.com
This is what I've tried so far...
Created this middleware to prevent the subdomain parameter from messing up other routes and to allow successful authentication to redirect to app.example.com:
class Subdomain
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$route = $request->route();
$subdomain = $route->parameter('subdomain');
if (!empty($subdomain) && preg_match('/^(staging|testing)\.(app.\)?/', $subdomain, $m)) {
\Session::put('subdomain', $m[1]);
}
$route->forgetParameter('subdomain');
return $next($request);
}
}
Added this to Kernel.php:
protected $routeMiddleware = [
'subdomain' => \App\Http\Middleware\Subdomain::class,
];
Contents of routes.php:
Route::group(['domain' => '{subdomain?}example.com', 'middleware' => 'subdomain'], function () {
// Backend routes
Route::group(['middleware' => 'auth'], function () {
Route::get('/', ['as' => 'dashboard', 'uses' => 'Controller#dashboard']);
// ...various other backend routes...
});
// Frontend routes
Route::auth();
Route::get('/', function () {
return view('frontend');
});
});
When I access any route, I can trace that nothing hits the subdomain middleware...it just routes to the 404 page.
How would I make this work in Laravel 5.2?
Since the goal of my setup was to allow handling certain subdomain groups with optional environment prefixes, I handled it in the following way.
I dropped the Subdomain class as being unnecessary.
I added this to the .env file so that each environment can have it's own domain so the local dev server still works independent of the staging and production server:
APP_DOMAIN=example.dev
On production and staging it would simply be:
APP_DOMAIN=example.com
Within config/app.php I added:
'domain' => env('APP_DOMAIN', null),
I added these methods to \App\Http\Controllers\Controller:
public static function getAppDomain()
{
return (!in_array(\App::environment(), ['local', 'production']) ? \App::environment() . '.' : '') . 'app.' . config('app.domain');
}
public static function getAppUrl($path = '', $secure = false)
{
return ($secure ? 'https' : 'http') . '://' . static::getAppDomain() . ($path ? '/' . $path : '');
}
Within Auth\AuthController.php I added this to handle redirects to the app.example.com from example.com even if prefixed with staging or testing:
public function redirectPath()
{
if (\Auth::check()) {
return redirect()->intended(static::getAppUrl())->getTargetUrl();
} else {
return $this->redirectTo;
}
}
New contents of routes.php:
// Backend routes
Route::group(['domain' => Controller::getAppDomain(), 'middleware' => 'auth'], function () {
Route::get('/', ['as' => 'dashboard', 'uses' => 'Controller#dashboard']);
// ...various other backend routes...
});
// Frontend routes
Route::auth();
Route::get('/', function () {
return view('frontend');
});
Hope this helps if anyone tries similar!

Laravel login redirected you too many times

I have been struggling with this from quiet a time now, what i am trying is to redirect all the url's hit by non-logged in users to login page and it gives me this error, which I am sure is because it is creating a loop on /login URL. authentication is checking for authorized user in login page also. however I wish the login page should be an exception when checking the auth. I may be doing something wrong which I am not able to get. here goes my code.
routes.php
Route::post('login', 'Auth\AuthController#login');
Route::get('login' , 'Auth\AuthController#showLoginForm');
Route::get('/' , 'Auth\AuthController#showLoginForm');
kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Auth\Access\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'acl' => \App\Http\Middleware\CheckPermission::class,
];
Authenticate class
class Authenticate
{
public function handle($request, Closure $next, $guard = null) {
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}
AuthController class
class AuthController extends Controller {
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/dashboard';
protected $loginPath = '/login';
protected $redirectPath = '/dashboard';
public function __construct(){
$this->middleware('auth', ['except' =>'login']);
/* I have been trying these many things to fix this, all in loss.
// $this->middleware('acl'); // To all methods
// $this->middleware('acl', ['only' => ['create', 'update']]);
// $this->middleware('guest', ['only' => ['/login']]);
// echo "Message"; exit;
// $this->middleware('auth');
// $this->middleware('auth', ['only' => ['login']]);
// $this->middleware('auth', ['only' => ['/login']]);
// $this->middleware('auth', ['except' => 'login']);
// $this->middleware('guest');
// $this->middleware('guest', ['only' => ['logout' , 'login', '/login', '/']]);
}
Please help me, It going all above my head, seems some sort of rocket science to me. well btw I am new to laravel and may be doing some silly thing around, apologies for that. Thanks in Advance.
You need add route login outside Laravel group:
routes.php
Route::auth();
Route::group(['middleware' => 'auth'], function () {
// All route your need authenticated
});
Aditionally, you can see yours route list using:
php artisan route:list
Why you are doing all this just to redirect every non-logged in user to login form?
i think you can just do this
Routes.php
Route::post('login', 'Auth\AuthController#login');
Route::get('login' , 'Auth\AuthController#showLoginForm');
Route::get('/' , 'Auth\AuthController#showLoginForm');
Route::group(['middleware' => 'auth'], function () {
// any route here will only be accessible for logged in users
});
and auth controller construct should be like this
AuthController
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
The problem is with your routes.
When I enter and I am not logged out you send me to login(get) route. And as you are specifying the middleware in the construct function in the AuthController, every time a method of the AuthController is called, construct function is called again and sends you back at login.. and it repeats indefinitely.
like #mkmnstr say
The problem is with your routes.
When I enter and I am not logged out you send me to login(get) route. And as you are specifying the middleware in the construct function in the AuthController, every time a method of the AuthController is called, construct function is called again and sends you back at login.. and it repeats indefinitely.
to fix that u should add
Auth::logout();
Here
...
} else {
Auth::logout(); // user must logout before redirect them
return redirect()->guest('login');
}
...
If your working with custom middleware you must follow it's all rules
in my case, I have to define a custom route class in the web middleware group.
In the world of copy-paste sometime we make mistakes.
Middleware :
public function handle($request, Closure $next)
{
if(!isset(session('user'))){
return redirect('login');
}
return $next($request);
}
}
My Mistake in Kernel.php
if custom middleware class present in web $middlewareGroups will check condition 2 times so it will give error as: redirected you too many times
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\webUser::class, //Remove
],
protected $routeMiddleware = [
'webUser'=> \App\Http\Middleware\webUser::class //Keepit
]
I had same problem after creating my own route service provider. The problem was that when I tried to login, in first time login page showed and after entering credentials I encountered "redirected too many times" and redirected to my admin dashboard and login route!
the solution was: adding middleware "web" into my routes:
Route::middleware('web')->group(base_path('Admin/routes.php'));

Resources