CakePHP3 Auth redirectURL route broken - authentication

I have a controller with a particular method to login:
public function login() {
if ($this->request->is('post')){
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
// not logged
$this->Flash->error('Your username or password is incorrect');
}
}
and default route looks like
Router::scope('/', function (RouteBuilder $routes) {
$routes->fallbacks(DashedRoute::class);
});
after user is logged in CakePHP throws an error
Error: A route matching "/" could not be found.
None of the currently connected routes match the provided parameters.
Add a matching route to config/routes.php
when IMO it should to redirect to the page (based on a related controller) from where login method was executed.
Login code is based on that tutorial.
Any thoughts?

To solve this issue:
Please update the below lines in routes.php file
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/', ['controller' => 'users', 'action' => 'index']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
Please do create index() in users controller.
Let me know if any issue.

Related

Laravel 8 Route not Defined Error Caused by Auth Middleware

I am attempting to access a route defined in my routes/web.php file:
Route::get('/dashboard', [ConsoleController::class, 'dashboard'])->middleware('auth');
I am not logged in. The Authenticate.php middleware file attempts to redirect me back to the login page:
class Authenticate extends Middleware
{
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('');
}
}
}
I have also tried using return route('/'); in the Authenticate.php middleware.
My routes/web.php file has a default route which works fine if I go to the page manually:
Route::get('/', [ConsoleController::class, 'loginForm'])->middleware('guest');
However, the Authenticate.php is causing the following error:
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [] not defined.
http://localhost:8888/dashboard
And it points to the following line of code:
public function route($name, $parameters = [], $absolute = true)
{
if (! is_null($route = $this->routes->getByName($name))) {
return $this->toRoute($route, $parameters, $absolute);
}
throw new RouteNotFoundException("Route [{$name}] not defined.");
}
I have found many similar posts on and off Stack Overflow, but none of those solutions have helped.
Am I naming my default route wrong? Can I not use this route in my Authenticate.php middleware? Any help would be appreciated.
Issue is, you are using route() method of Laravel, which expect route name as a parameter but you are passing actual url.
In your routes/web.php file, add name to your route as
Route::get('/dashboard', [ConsoleController::class, 'dashboard'])->middleware('auth')->name('dashboard');
Then in your Authenticate middleware file,
class Authenticate extends Middleware
{
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('dashboard');
}
}
}

user auth Laravel 5.2

in my project I need to protect some views.
I create a router group:
Route::group(['middleware' => ['auth']], function (){
//Spot
Route::get('administrator/spot-new', 'SpotController#create');
Route::post('administrator/spot-new', 'SpotController#store');
}
in my Spot Controller:
public function __construct()
{
$this->middleware('auth');
}
but when I try to access to spot view I can't see the login page.
I have this error:
Sorry, the page you are looking for could not be found.
Laravel 5.2 have added Middleware Groups.
https://laravel.com/docs/5.2/middleware#middleware-groups
Web middleware group is responsible for Start Session / Encrypt Cookies / Verify CSRF Token etc.. see below
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
You're required to add when working with sessions and any other stuff
in that group.
So to solve your problem add 'web' to your middleware
Route::group(['middleware' => ['web', 'auth']], function (){
Route::get('administrator/spot-new', 'SpotController#create');
Route::post('administrator/spot-new', 'SpotController#store');
}
And in your controller constructor
public function __construct()
{
//$this->middleware('auth'); (No need for this one)
}

Auth Filter Not Working

Trying to use auth filter to keep users from accessing certain routes without being logged in. The code below redirects regardless of the user's status. I was unable to find anywhere what to put within the function. I'm using http://laravel.com/docs/security#protecting-routes for reference. Not sure if I should have an if statement or not. Not sure what to do at all.
Route:
Route::get('/account', ['before' => 'auth', function()
{
// continue to /account
}]);
Standard 'auth' filter from app/filters:
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
//return Redirect::guest('login');
}
}
});
The way I understand it the code within the function should only be loaded if the user is logged in. Otherwise give 401 error.
Thanks for help.
With some help from my friend I fixed it. Some important information, Route filters will continue with intended purpose unless something is returned from filter. Also, the standard auth filter will not work. Must be modified. After that it was cake. Code is below.
Route:
Route::get('/account', ['before' => 'auth', 'uses' => 'SiteController#account']);
Auth Filter:
Route::filter('auth', function()
{
if (Auth::guest())
{
return Response::make('Unauthorized', 401);
}
});

Authenticating a user role in Laravel and protecting a route

I have taken advice from people here and given Laravel a try, I have been trying to create a user authentication system. I am having trouble translating what I know works in PHP to Laravel using Eloquent.
What I am trying to do here is identify a user, their roles, if the user has a role of admin they can access the route /admin
I know I can use a package such as Entrust but that is not really helping me learn.
I have created Models for both User and Role. I also have a lookup table called role_user with a user_id and role_id.
In User.php I have
public function roles(){
return $this->belongsToMany('Role', 'users_roles');
}
In Role.php I have
public function users()
{
return $this->belongsToMany('User', 'users_roles');
}
I know if I used
$roles = user::find(1)->roles;
return ($roles);
It will and does return the correct user id (1) and the roles assigned to that user. Now what I am struggling with is how to pick out the admin role and only if the user has this will it allow access to /admin
The route should essentially be
Route::get('admin', function()
{
return View::make('admin.index');
})->before('auth');
What I can't figure how/where/should I check for the admin role first and how to then apply that to the auth check to only permit an admin access to the route.
Any help appreciated.
Lee
For Laravel 5, use Middleware:
Create new middleware
# php artisan make:middleware RoleMiddleware
Check the user role - redirect if invalid role
// app/Http/Middleware/RoleMiddleware.php
class RoleMiddleware
{
public function handle($request, Closure $next, $role)
{
if (! $request->user()->hasRole($role)) {
// Redirect...
}
return $next($request);
}
}
Add key in order to assign to routes - can also make global
// app/Http/Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'role' => \App\Http\Middleware\RoleMiddleware::class, // new
];
Protect the routes
// app/Http/routes.php
Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) {
// routes for editor
}]);
You have used auth filter so you should check in the auth filter in app/filters.php file:
Route::filter('auth', function($route, $request)
{
// Login check (Default)
if (Auth::guest()) return Redirect::guest('login');
// Admin check
if(!in_array('admin', Auth::user()->roles->toArray())) {
return Redirect::to('/'); // Redirect home page
}
});
You may use a different filter, for example:
Route::get('admin', function()
{
return View::make('admin.index');
})->before('isAdmin');
Declare the custom isAdmin filter in app/filters.php:
Route::filter('isAdmin', function($route, $request)
{
if(!Auth::check()) return Redirect::guest('login');
if( !in_array('admin', Auth::user()->roles->toArray()) ) {
return Redirect::to('/'); // Redirect home page
}
});

Laravel 4 Auth Filter: Unable to generate a URL for the named route as such route does not exist

I am trying to restrict a resource that I have named Artists (run by an ArtistsController). I tried doing this directly with the constructor in the controller:
public function __construct()
{
$this->beforeFilter('auth', array('except' => array()));
}
And in my filters, I have:
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::route('fans/landing');
});
In my routes, I have:
Route::get('fans/landing', array('uses' => 'FansController#getIndex'))->before('guest');
However, when I run this (trying to go to one of the resource pages), I get the following error:
Unable to generate a URL for the named route "fans/landing" as such route does not exist.
This is strange, because when I remove the construct function, the fans/landing page loads fine. Also, it redirects another page (not part of the resource), fine to fans/landing, when I have:
Route::get('/fans/home', array('uses' => 'FansController#getHome'))->before('auth');
change
Route::get('fans/landing', array('uses' => 'FansController#getIndex'))->before('guest');
to
Route::get('fans/landing', array('as' => 'fans.landing', 'uses' => 'FansController#getIndex'))->before('guest');
and change
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::route('fans/landing');
});
to
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::route('fans.landing');
});