I have a simple users table which I define and admin by having a 1 in the type column.
I have the following setup in my middleware but this still doesn't stop non admins accessing admin only areas.
Middleware:
<?php
namespace App\Http\Middleware;
use Closure;
class Admin {
public function handle($request, Closure $next)
{
if (Auth::user()->isAdmin())
{
return redirect('home');
}
return $next($request);
}
}
Kernal:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'admin' => App\Http\Middleware\Admin::class,
];
Routes:
Route::group(['middleware' => 'auth', 'admin'], function () {
Route::get('admin/dashboard', 'AdminController#dashboard');
Route::get('admin/orders', 'AdminController#orders');
});
Function in my User class:
public function isAdmin()
{
if (Auth::user()->type == '1')
{
return true;
}
else
{
return false;
}
}
You need to pass multiple middleware as an array:
Route::group(['middleware' => ['auth', 'admin']]
Related
I followed this site on how to create user types and restrict page access. Everything works as expected, but I wanted the admin to also have access to the users pages.
The app has several hierarchical levels and I don't want to have to repeat the same Route several times, how can I do that?
Im using this: (short version)
routes/web.php
...
Route::middleware(['auth', 'user-access:usr'])->group(function () {
Route::get('/', function () {
return view('pages.activityHome');
});
});
Route::middleware(['auth', 'user-access:adm'])->group(function () {
Route::get('activity/{id}/edit', [App\Http\Controllers\activityController::class, 'editActivity'])->name('edit.activity');
});
Models/User.php
...
protected function type(): Attribute
{
return new Attribute(
get: fn ($value) => ["usr", "adm"][(int) $value],
);
}
Http/Middleware/UserAccess.php
...
public function handle(Request $request, Closure $next, $userType)
{
if(auth()->user()->type == $userType){
return $next($request);
}
// return response()->view('errors.check-permission');
}
Http/Kernel.php
...
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'user-access' => \App\Http\Middleware\UserAccess::class,
];
This way the adm doesn't have access to /, but he should, how can I do it?
I tried how to place more elements in the array and put several groups separated by a comma, but it doesn't work.
Like this: ['auth', 'user-access:usr', 'user-access:adm'], ['auth', 'user-access:usr,adm']
I tried a different way and it worked.
Http/Middleware/UserAccess.php
...
public function handle(Request $request, Closure $next, $userType)
{
if(in_array(auth()->user()->type, explode('.', $userType))){
return $next($request);
}
return response()->json(['You do not have permission to access for this page.']);
}
routes/web.php
...
Route::middleware(['auth', 'user-access:usr.adm'])->group(function () {
Route::get('/', function () {
return view('pages.activityHome');
});
});
I'm basically checking to see if any of the user types are in the array.
When I try to redirect to the file I need, it displays an error that the Admin class does not exist, how to fix it?
Auth::routes();
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
if (Auth::user()->role == 'Admin')
return redirect('admin');
elseif (Auth::user()->role == 'User')
return redirect('user');
else
return redirect('error');
});
Route::get('error', function () {
return "Sorry, you are unauthorized to access this page.";
});
Route::group(['prefix' => 'admin', 'middleware' => 'admin'], function () {
Route::view('/', 'role.admin');
});
Route::group(['prefix' => 'user', 'middleware' => 'user'], function () {
Route::view('/', 'role.user');
});
});
After creating middleware you need to register it in app/http/Kernel.php file in protected $routeMiddleware array. Then you can use this middleware in your routes(web.php/api.php):
protected $routeMiddleware = [
'admin' => 'App\Http\Middleware\Admin',
];
I'd like to pre check two different Route Groups by the auth:admin middleware. This works perfectly for the first Route Group inside but not for the second which is in an other Namespace.
My Routes file looks like this:
Route::group(['middleware' => ['auth:admin']], function(){
Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.'], function(){
Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});
Route::group(['prefix' => 'team/{team_id}', 'namespace' => 'Team', 'as' => 'team.'], function(){
Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});
});
If I'm not logged in and try to go to admin/dashboard, I'm redirected to login/admin. But if I try to go to team/1/dashboard it says Error 'Trying to get property 'headers' of non-object'.
How can I get the auth:admin Middleware to work with my Team Routes too?
create a middleware
class IsAdmin
{
public function handle($request, Closure $next)
{
if (Auth::user()->permission == 'admin') {
return $next($request);
}
return redirect()->route('some.route'); // If user is not an admin.
}
}
Register in kernel.php
protected $routeMiddleware = [
....
'is.admin' => \App\Http\Middleware\IsAdmin::class,
];
So your routes:
Route::group(['middleware' => 'is.admin'], function () {
Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.'], function(){
Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});
Route::group(['prefix' => 'team/{team_id}', 'namespace' => 'Team', 'as' => 'team.'], function(){
Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});
});
check app/Http/Controllers/Middleware/RedirectIfAuthenticated.php file and
update the code for different guard use
// app/Http/Controllers/Middleware/RedirectIfAuthenticated.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if ($guard == "admin" && Auth::guard($guard)->check()) {
return redirect('/admin');
}
if ($guard == "writer" && Auth::guard($guard)->check()) {
return redirect('/writer');
}
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}
I'm having a strange issue with my laravel app .
I have a route defined as :
web.php
Route::get('/', ['as' => '/', 'uses' => 'LoginsController#getLogin']);
Route::post('/login', ['as' => 'login', 'uses' => 'LoginsController#postLogin']);
Route::group(['middleware' => ['authenticate', 'roles']], function (){
Route::get('/logout', ['as' => 'logout', 'uses' => 'LoginsController#getLogout']);
Route::get('/dashboard','DashboardController#dashboard')->name('dashboard');
});
In a controller , i'm trying to redirect to this route
LoginController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginsController extends Controller
{
use AuthenticatesUsers;
protected $username = 'username';
protected $redirectTo = '/';
protected $guard = 'web';
public function getLogin()
{
if (Auth::guard('web'))
{
return redirect()->route('dashboard');
}
return view('login');
}
public function postLogin(Request $request)
{
$auth = Auth::guard('web')->attempt([
'username' => $request->username,
'password' => $request->password,
'active' => 1]);
if ($auth)
{
return redirect()->route('dashboard');
}
return redirect()->route('/');
}
public function getLogout()
{
Auth::guard('web')->logout();
return redirect()->route('/');
}
}
Where I am typing http://localhost:8000 in address bar of browser. I see.
I am using laravel for my web application,in login I am asking for username ,password and I want to check the email of the logged in user is verified or not. If the verified status is 0 I want to sent the error message to the login page using the verifiedemail named middleware.
route.php
Route::group(['middleware' => 'auth', 'superadmin'], function () {
Route::resource('/users', 'UserController');
});
Route::get('/', function () {
if (Auth::guest())
return view('/auth/login');
else
return redirect('/tests');
});
Route::resource('/tests', 'TestController');
Route::get('/sites', 'SiteController#index');
Auth::routes();
Route::get('/home', 'HomeController#index');
Redirectedifauthenticated.php <--- middleware file
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
verifiedemail.php <--- middleware file
public function handle($request, Closure $next)
{
if ( Auth::check() && Auth::user()->isVerifiedEmail() )
{
return redirect('/login');
}
return $next($request);
}
kernel.php
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'superadmin' => 'App\Http\Middleware\SuperAdmin',
'verifiedemail' => 'App\Http\Middleware\VerifiedEmail',
];
}
I think these are the files where i have to change but what and where I have to change that's the question for me .please help thanks in advance.
If you're using the default laravel authentication you can add a listener on the Illuminate\Auth\Events\Attempting which is fired on every login attempt and do your validation in the listener.
More about fired event on Auth
More about event listeners