Tengo un sistema de rutas en laravel que protegen a los usuarios guests de entrar al admin dashboard, el problema es que solo puedo bloquear a los visitantes y no a los usuarios "normales" (Es decir los usuarios que compran cosas, los visitantes no pueden comprar).
Intente hacer un middleware que los bloquea pero no funciona bien, me gustaría saber como arreglarlo.
Esta es la ruta que quiero proteger
Route::get('/admin', [
'uses' => 'AdminController@getAdmin',
'as' => 'admin.dashboard',
'middleware' => 'auth', 'admin' //Es el modulo de entrar al admin, solo usuarios registrados lo pueden usar
]);
El middleware de auth que viene por default en Laravel solo logra proteger el dashboard de los usuarios no registrados, es decir un usuario que se registró normalmente puede entrar escribiendo la url y necesito evadir eso, pero no se como
Este es mi código de insertar usuarios, usando en UserController, por si necesitan información de este
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
use Redirect;
class UserController extends Controller
{
public function getSignup(){
return view('user.signup'); //Manda al usuario al signup
}
public function postSignup(Request $request){ //Crear el usuario
$this->validate($request, [
'email' => 'email|required|unique:users',
'password' => 'required|min:4'
]); //Valida al usuario deacuerdo si es unico y su clave es mayor a 4
$user=new User([
'email' => $request->input('email'),
'password' => bcrypt($request->input('password')),
]);
$user->save(); //Salva al usuario
Auth::login($user); //Arranca la sesion
return redirect()->route('user.profile');
}
public function getSignin(){
return view('user.signin');
}
public function postSignin(Request $request){ //Inicio de sesion
$this->validate($request, [
'email' => 'email|required',
'password' => 'required|min:4'
]); //Valida los campos
if(Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password'), 'type' => 'cliente'])){
return redirect()->route('user.profile');
} //Valida si el usuario es un cliente
if(Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password'), 'type' => 'admin'])){
return redirect()->route('admin.dashboard');
} //Valida si el usuario es un admin
return redirect()->back();
}
public function getProfile(){
return view('user.profile');
}
public function getLogout(){
Auth::logout();
return redirect()->route('product.index');
}
}
Este es el código que tengo en el Middleware de Authentication
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('user.signin');
}
}
}
Esto es lo que tengo en el AdminMiddleware
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Redirect;
class AdminMiddleware
{
/**
* Handel an Incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure
* @return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::user()->type == 'admin')
{
return redirect()->route('admin.dashboard');
}
else
{
return redirect('product.index');
}
}
}
Esto es lo que tengo en Kernel.php, el middleware si esta iniciado
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::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' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
\Illuminate\Auth\Middleware\Authorize::class,
\App\Http\Middleware\AdminMiddleware::class,
];
}
Así es que como tengo la tabla de users, por alguna razon el AdminMiddleware no se comunica con ella, o no sabe como hacerlo
CREATE TABLE `users` (
`id` bigint(20) UNSIGNED NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'cliente',
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
'middleware' => 'auth', 'admin'
, debería ser:'middleware' => ['auth', 'admin']