I'm using Laravel Breeze + Inertia (React) and want to implement custom auth.
I'm having infinite redirection (ERR_TOO_MANY_REDIRECTS) when visiting /dashboard on this middleware.
Route::get('register', [RegisteredUserController::class, 'create'])
->name('register');
Route::post('register', [RegisteredUserController::class, 'store']);
Route::get('login', [AuthenticatedSessionController::class, 'create'])
->name('login');
Route::post('login', [AuthenticatedSessionController::class, 'store']);
Route::middleware(['custom_auth'])->group(function () {
Route::get('/dashboard', function () {
return Inertia::render('Dashboard');
})->name('dashboard');
});
class CustomAuthMiddleware
{
public function handle(Request $request, Closure $next)
{
if (session()->has('user_data')) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
}
This works:
namespace App\Http\Middleware;
class RedirectIfAuthenticated
{
public function handle(Request $request, Closure $next, ...$guards)
{
if (session()->has('user_data')) {
return redirect()->route('users.index');
}
return $next($request);
}
}
namespace App\Http\Middleware;
class CustomAuthMiddleware
{
public function handle(Request $request, Closure $next)
{
if (session()->has('user_data')) {
return $next($request);
}
return redirect('login');
}
}
Route::middleware('guest')->group(function () {
Route::get('register', [AuthController::class, 'register'])
->name('register');
Route::post('register', [AuthController::class, 'registerPost']);
Route::get('login', [AuthController::class, 'login'])
->name('login');
Route::post('login', [AuthController::class, 'loginPost']);
});
Route::middleware('custom_auth')->group(function () {
Route::get('/', function () { return redirect()->route('users.index'); });
Route::resource('users', UserController::class);
});
Related
Define the four routes with different middleware role wise.
Issue arrive is call DepartmentStaff Route every time.if i login Admin or Customer.
Call last written route every time.
//admin Route
Route::get('edit_profile', [UserController::class, 'edit_profile'])->name('edit_profile')->middleware(CheckAdminRole::class);
Route::post('profile_update', [UserController::class, 'profile_update'])->name('profile_update')->middleware(CheckAdminRole::class);
Route::get('change_password', [UserController::class, 'change_password'])->name('change_password')->middleware(CheckAdminRole::class);
Route::post('password_update', [UserController::class, 'password_update'])->name('password_update')->middleware(CheckAdminRole::class);
// Customer Route
Route::get('edit_profile', [UserController::class, 'edit_profile'])->name('edit_profile')->middleware(CheckCustomerRole::class);
Route::post('profile_update', [UserController::class, 'profile_update'])->name('profile_update')->middleware(CheckCustomerRole::class);
Route::get('change_password', [UserController::class, 'change_password'])->name('change_password')->middleware(CheckCustomerRole::class);
Route::post('password_update', [UserController::class, 'password_update'])->name('password_update')->middleware(CheckCustomerRole::class);
//DepartmentStaff Route
Route::get('edit_profile', [UserController::class, 'edit_profile'])->name('edit_profile')->middleware(CheckDepartmentStaffRole::class);
Route::post('profile_update', [UserController::class, 'profile_update'])->name('profile_update')->middleware(CheckDepartmentStaffRole::class);
Route::get('change_password', [UserController::class, 'change_password'])->name('change_password')->middleware(CheckDepartmentStaffRole::class);
Route::post('password_update', [UserController::class, 'password_update'])->name('password_update')->middleware(CheckDepartmentStaffRole::class);
//admin middleware
public function handle(Request $request, Closure $next)
{
if (auth()->user()->role == 1) {
return $next($request);
}
return redirect('error/404');
}
//customer middleware
public function handle(Request $request, Closure $next)
{
if (auth()->user()->role == 4) {
return $next($request);
}
return redirect('error/404');
}
//Department middleware
public function handle(Request $request, Closure $next)
{
if (auth()->user()->role == 2) {
return $next($request);
}
return redirect('error/404');
}
You can use only one middleware to check routes like:
//middleware
public function handle(Request $request, Closure $next)
{
if (in_array(auth()->user()->role, [1, 2, 3])) {
return $next($request);
}
return redirect('error/404');
}
And routes:
Route::get('edit_profile', [UserController::class, 'edit_profile'])->name('edit_profile')->middleware(CheckRole::class);
Route::post('profile_update', [UserController::class, 'profile_update'])->name('profile_update')->middleware(CheckRole::class);
Route::get('change_password', [UserController::class, 'change_password'])->name('change_password')->middleware(CheckRole::class);
Route::post('password_update', [UserController::class, 'password_update'])->name('password_update')->middleware(CheckRole::class);
I'm trying to config an user/admin environment in my laravel page, and whenever I try group the routes, I'll get one of the mentioned error back. What am I doing wrong? I tried both formats, same error.
web.php
//supposed user dashboard
Route::group(['middleware' => ['auth', 'user']], function () {
Route::get('/dashboard', 'DashboardController#index')->name('dashboard');
});
//supposed admin dashboard
Route::group(['middleware' => ['auth', 'admin']], function () {
Route::get('/dashboard', [AdminDashController::class, 'index']);
});
eg AdminDashController:
public function index()
{
return view("admin_dashboard");
}
DashboardController does the same, but returning user view.
I'm new to laravel, I appriciate any help!
Update:
I tried the solution below, my result is that I'm now getting "Route [user.dashboard] not defined." error...
My web.php
Route::group(['middleware' => ['auth', 'user']], function () {
Route::get('/dashboard', [UserDashController::class, 'index'])->name('user.dashboard');
});
// admin dashboard
Route::group(['middleware' => ['auth', 'admin']], function () {
Route::get('/dashboard', [AdminDashController::class, 'index'])->name('admin.dashboard');
});
my AdminDashController and UserDashController:
public function index()
{
return view('user_dashboard');
}
AND
public function index()
{
return view('admin_dashboard');
}
I have a RedirectIfAuthenticated.php
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
/** #var User $user */
$user = Auth::guard($guard);
// to admin dashboard
if ($user->hasRole('admin')) {
return redirect()->route('admin.dashboard');
}
// to user dashboard
else if ($user->hasRole('user')) {
return redirect(route('user.dashboard'));
}
}
}
return $next($request);
}
Also having an Admin and User redirect:
AdminAuthenticated.php:
public function handle(Request $request, Closure $next)
{
if( Auth::check() )
{
/** #var User $user */
$user = Auth::user();
// if user is not admin take him to his dashboard
if ( $user->hasRole('user') ) {
return redirect()->route('user.dashboard');
}
// allow admin to proceed with request
else if ( $user->hasRole('admin') ) {
return $next($request);
}
}
abort(403); // permission denied error
}
UserAuthenticated
public function handle(Request $request, Closure $next)
{
if( Auth::check() )
{
/** #var User $user */
$user = Auth::user();
// if user is admin take him to his dashboard
if ( $user->hasRole('admin') ) {
return redirect(route('admin.dashboard'));
}
// allow user to proceed with request
else if ( $user->hasRole('user') ) {
return $next($request);
}
}
abort(403); // permission denied error
}
Update 2:
I replaced the routing in web.php as follows:
Route::middleware(['auth','user'])->group(function () {
Route::prefix('user')->group(function () {
Route::get('/dashboard', [UserDashController::class, 'index'])->name('user.dashboard');
});
});
Route::middleware(['auth','admin'])->group(function () {
Route::prefix('admin')->group(function () {
Route::get('/dashboard', [AdminDashController::class, 'index'])->name('admin.dashboard');
});
});
Still same error: "Route [user.dashboard] not defined."
The problem may be in your route name. One route has a named dashboard another was not. Use the below code hope this will resolve your problem
// user dashboard
Route::group(['middleware' => ['auth', 'user']], function () {
Route::get('/dashboard', 'DashboardController#index')->name('user.dashboard');
});
// admin dashboard
Route::group(['middleware' => ['auth', 'admin']], function () {
Route::get('/dashboard', 'DashboardController#index')->name('admin.dashboard);
})
use the route name in stead of url.
in my case, instead using your code below :
Route::group(['middleware' => ['auth', 'user']], function () {
Route::get('/dashboard', [UserDashController::class, 'index'])->name('user.dashboard');
});
// admin dashboard
Route::group(['middleware' => ['auth', 'admin']], function () {
Route::get('/dashboard', [AdminDashController::class, 'index'])->name('user.dashboard');
});
i use my own code, so define the middleware first and use prefix on it :
Route::middleware(['auth','user'])->group(function () {
Route::prefix('user')->group(function () {
Route::get('/dashboard', [UserDashController::class, 'index'])->name('user.dashboard');
});
});
Route::middleware(['auth','admin'])->group(function () {
Route::prefix('admin')->group(function () {
Route::get('/dashboard', [AdminDashController::class, 'index'])->name('admin.dashboard');
});
});
maybe you should differentiate routing between dashboard for admin and user. you can use like this : /admin/dashboard and /user/dashboard
edit :
i think there's some typo on your code :
// to admin dashboard
if ($user->hasRole('admin')) {
return redirect(route('admin.dashboard'));
}
return redirect route should typed like this : return redirect()->route('admin.dashboard)
I'm doing authorization using laravel:sanctum for the API. But, when calling the logout() method, I get the following error: Call to a member function tokens() on null. Please help me get rid of this error
AuthController
public function auth(UserLoginRequest $request){
$user = User::query()->where('login', $request->get('login'))->first();
if (!$user || !Hash::check($request->get('password'), $user->password)) {
return response()->json(['message'=>'Попытка входа не удалась'], 400);
}
$token = $user->createToken('api_token')->plainTextToken;
$user->api_token = $token;
$user->save();
return response()->json(['message'=>$user->api_token], 200);
}
public function logout(Request $request) {
$request->user()->tokens()->delete();
return response()->json(['message' => 'Вы вышли из системы'], 200);
}
api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::middleware('auth:sanctum')->get('user', function (UserLoginRequest $request) {
return response()->json(['login' => $request->user()->login]);
});
Route::post('auth', [AuthController::class, 'auth']);
Route::post('authStore', [AuthController::class, 'store']);
Route::get('authLogout', [AuthController::class, 'logout'])->middleware('auth:sanctum');
Route::get('application/{id}', [ApplicationController::class, 'showById']);
Route::get('application', [ApplicationController::class, 'show']);
Route::post('applicationStore', [ApplicationController::class, 'store']);
Route::post('applicationDelete', [ApplicationController::class, 'delete']);
Route::post('userDelete/{user}', [UserController::class, 'delete']);
Route::post('userStore', [UserController::class, 'store']);
Route::post('review', [ReviewController::class, 'show']);
Route::post('reviewCreate', [ReviewController::class, 'create']);
solved this by adding my logout Route inside :-
Route::group(['middleware' => ['auth:sanctum']], function () {
// logout route api code here
}
Use auth('sanctum') instead auth() because of you used to sanctum auth
It should be:
auth('sanctum')->user()->tokens()->delete();
The code should be like following
public function logout(Request $request) {
if ($request->user()) {
$request->user()->tokens()->delete();
}
return response()->json(['message' => 'Вы вышли из системы'], 200);
}
use currentAccessToken() instead of tokens().
I'm using Laravel 5.3 and Auth by default with this roles package. How can i do the normal user redirection after the user login if i have similar roles and also pages for them. For example i have AdminRole and after the Login i want to redirect user to /admin/dashboard.
I have tried something like this in the LoginController but it doesn't make sense:
protected function redirectTo()
{
if (Auth::user()->isRole('admin'))
return redirect()->route('admin');
return redirect()->route('home');
}
Or maybe there is a better way to use middleware for redirecting?
Here is my routes (web.php):
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::resource('company', 'CompanyController');
Route::group(['prefix' => 'admin'], function () {
Route::get('login', function () {
return view('admin.pages.admin-login');
});
Route::group(['middleware' => 'role:admin'], function () {
Route::get('/', function () {
return view('admin.admin-main');
});
});
});
use it like this way:
return Redirect::to('admin');
And note that:
route:Route::get('company', 'CompanyController#show');
controller:
this works fine:
function show(){
return Redirect::to('home');
}
but this not
function show(){
$this->redirectto();
}
function redirectto()
{
return Redirect::to('home');
}
route.php
Route::get('home', ['as' => 'admin_home', 'uses' => 'HomeController#index']);
Route::get('login'['as'=>'admin_login','uses'=>'LoginController#admin_login']);
LoginController.php
use Illuminate\Support\Facades\Redirect;
public function index(){
$User=new User();
if(isset(AUTH::user()->id)){
$User->id=AUTH::user()->id;
$auth_user_role=$User->auth_user_role();
$rl_title=$auth_user_role[0]->rl_title;
if(isset(Auth::user()->id) && isset($rl_title) && $rl_title == 'Admin'){
return view('home.admin',$this->param);
}
else if(isset(Auth::user()->id) && isset($rl_title) && $rl_title == 'Moderator'){
return view('home.moderator',$this->param);
}
else{
return Redirect::route('admin_login');
}
}else{
return Redirect::route('admin_login');
}
}
Views
-> views
-> home
-> admin.blade.php
-> member.blade.php
I needed to do something like this in Auth/LoginController:
protected function authenticated()
{
if(Auth::user()->isRole('admin')) {
return redirect()->intended('/admin');
}
return redirect()->intended('/home');
}
i have a middleware, i want it to pass $role to the route.php
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
$role= "normal";
$user_roles = AssignedRoles::join('roles','role_user.role_id','=','roles.id')
->where('user_id', $this->auth->user()->id)->select('roles.is_admin', 'roles.is_vendor')->get();
foreach($user_roles as $item)
{
//var_dump($item->is_vendor);
//die();
if($item->is_admin==1)
{
$role = "admin";
}
if($item->is_vendor==1)
{
$role = "vendor";
}
}
if($role=="normal"){
return $this->response->redirectTo('/');
}
//$request->attributes->add(['admin' => $admin, 'vendor' => $vendor]);
$request->attributes->add(['role' => $role]);
View::share ('role', $role);
return $next($request);
}
return $this->response->redirectTo('/');
}
is there any way to do that?
My route:
Route::group(['prefix' => 'admin', 'middleware' => ['auth']], function() {
Route::auth();
Route::pattern('id', '[0-9]+');
Route::pattern('id2', '[0-9]+');
#Admin Dashboard
Route::get('dashboard', 'Admin\DashboardController#index');
Route::get('vendor/{id}/edit', 'Admin\VendorController#getEdit');
Route::post('vendor/{id}/edit', 'Admin\VendorController#postEdit');
});
You can do something like this:
// In your middleware
$request->offsetSet('role', $role);
Then in the routes.php:
use Illuminate\Http\Request;
Route::get('test', ['middleware' => 'auth', function(Request $request) {
dd($request->get('role'));
}]);