Removing a route from Auth::routes() - laravel

I have these routes:
Auth::routes();
Route::get('/home', 'LibraryController#home');
Route::get('/', 'LibraryController#index');
Auth::routes() is generated by the command php artisan make::auth. But, i don't want the index page to be under auth middleware group, the third route in the above list.
Here is the controller methods. index() is for everyone and home() for authenticated users.
public function index()
{
return view('index');
}
public function home()
{
return view('home')->with('message','Logged in!');
}
the login users is redirected to home url:
protected $redirectTo = '/home';
But whenever i run the third route the login page appears. so, how can i remove that route from auth middleware group.

In your LibraryController before index where your controllers start you need to write
public function __construct()
{
$this->middleware('auth', ['except' => ['index']]);
}
Now every user will be able to go to index method without authentication
Documentation Reference https://laravel.com/docs/5.0/controllers#controller-middleware

Since Laravel 7.7 you can use excluded_middleware property eg:
Route::group([
'excluded_middleware' => ['auth'],
], function () {
Route::get('/home', 'LibraryController#home');
Route::get('/', 'LibraryController#index');
});

Related

Laravel auth middleware returns route not defined

I'm new to laravel and I'm trying to secure some routes wherein only authenticated users can access it.
I've followed instructions on grouping my web routes on an auth middle ware, so I did my routes/web.php it like this...
Route::group(['middleware' => 'auth'], function () {
Route::get('/feed', [FeedController::class, 'feed']);
Route::get('/profile', [ProfileController::class, 'profile']);
});
Route::get('/', [LandingController::class, 'landing']);
and my App/Http/Middleware/Authenticate.php like this....
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('/');
}
}
but when I access these guarded routes unauthenticated, it gives me error saying
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [/] not defined.
Can someone point me on the right way here?

Prevent role-specific users from accessing route

I have 2 roles, which is admin and user. Now when logging in, the admin goes to the dashboard route while the user goes to home. When user is logged in and changes the url to http://127.0.0.1:8000/dashboard it can access the admin's panel and I don't want that. How can I do achieve this?
PS. I'm new to Laravel
The good practice for this is usage of Middewares.
Create middlewares for admins and users (I'll do that only for admins, you can do that similarly for users):
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class AdminMiddleware
{
public function handle($request, Closure $next)
{
if(Auth::check()){
// check auth user role (I don't know how you can implement this for yourself, this is just for me)
if(Auth::user()->role->name == 'admin'){
return $next($request);
} else {
return redirect()->route('admin.dashboard'); // for admins
}
}
return redirect()->route('main'); // for users
}
}
In "app/Http/Kernel.php" in $routeMiddleware array register that (add to end of that array).
'Admin' => \App\Http\Middleware\AdminMiddleware::class,
Now if you are using all requests in "routes/web.php" (actually I think it does), then you can use routes like this for admins:
// USER ROUTES
Route::get('/', 'FrontController#main')->name('main');
// ADMIN ROUTES
Route::group([
'as' => 'admin.',
'middleware' => [ 'Admin' ],
], function () {
Route::get('dashboard', 'AdminController#dashboard');
});
Refresh caches via "php artisan config:cache".
Try it!
Use middleware to admin route or inside the controller
like this:
Route::put('post/{id}', function ($id) {
//
})->middleware('role:editor');
or
Route::middleware(['auth', 'admin'])->group(function (){
Route::get('dashboard', 'HomeController#index')->name('home.index');
});
or inside the controller like this:
public function __construct()
{
$this->middleware(['auth', 'admin'])->except(['index']);
}
or you can use this for middleware roles.

Laravel: Redirect login & register if logged in?

I'm struggling to get the login/register pages to redirect the user if already logged in.
in routes.php
Route::group(array('before' => 'auth'), function()
{
Route::get('hud', 'HomeController#index')->name('hud');
Route::get('search', 'HomeController#search')->name('search');
Route::get('profile', 'UsersController#index')->name('profile');
Route::get('clients', 'ClientsController#index')->name('clients');
Route::delete('clients/{id}', 'ClientsController#destroy');
Route::resource('projects', 'ProjectsController', array('only' => array('show')));
});
I've tried no_auth and it just breaks. Am I missing something?
You should set the redirect path for when a given visitor is authenticated user.
You can do so in: App\Http\Middleware\RedirectIfAuthenticated
Example:
public function handle($request, Closure $next)
{
if ($this->auth->check()) {
return redirect('/dashboard');
}
return $next($request);
}
Stackoverflow: laravel redirect if logged in
You want to redirect already registered user to Homepage whenever they try to hit /login.
Here's how laravel tries to achieve that.
Firstly this is achieved through App\Http\Middleware\RedirectIfAuthenticated.
However a key to this middleware is registered to guest in this file app\Http\Kernel.php under array protected $routeMiddleware.
Then in your login controller presumably at app\Http\Controllers\Auth\LoginController.php
In the construct method, We have something like this:
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}

Laravel 5.4 redirect to specific page if user is not authenticated using middleware

I want to redirect user, if not authenticated, to my index page (which is the login page)
Can't seem to make it work and i really got confused with the routing.
HomeController
class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return redirect()->guest('/');
}
}
Routing
// Index
Route::get('/', [
'as' => 'index',
'uses' => 'UserController#index'
]);
UserController
The routing as you see redirects to a User Controller at index function, which is the below :
*has __construct() so it uses the middleware 'auth'.
public function __construct()
{
$this->middleware('auth');
}
public function index(){
// If user is logged
if(Auth::check()) {
// If user has NOT submitted information form redirect there, otherwise to categories
if(!Auth::user()->submitted_information)
return redirect()->route('information');
else
return redirect()->route('categories');
}
else
return view('index', ['body_class' => 'template-home']);
}
Handler.php
And the unauthenticated function inside middleware of auth (Exceptions/Handler.php)
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->route('index');
}
The error i get right now is the below :
InvalidArgumentException in UrlGenerator.php line 304:
Route [index] not defined.
This error happens because of the line of
return redirect()->route('index'); in the above unauthenticated function.
What am i missing here? If you need any more information please feel free to ask.
EDIT : Until now, if i remove from UserController the __construct() method, and insert in web.php to all the routes what middleware to use, it works.
For example
Route::get('/categories', [
'as' => 'categories',
'uses' => 'UserController#showCategories'
])->middleware('auth');
But i am trying to find, without specifying there what middleware to use, to use it automatically.
Build your route like below code:
Route::group(['middleware' => ['auth']], function() {
// uses 'auth' middleware
Route::resource('blog','BlogController');
});
Route::get('/mypage', 'HomeController#mypage');
Open your middleware class named RedirectIfAuthenticated and then in handle fucntion
you write below code:
if (!Auth::check()) {
return redirect('/mypage'); // redirect to your specific page which is public for all
}
Hope it will work for you.
Your route should be like
// Index
Route::get('/','UserController#index')->name('index);
see here for more about routing.
Try
Route::get('/','UserController#index',['middleware'=>'auth'])->name('index);

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