laravel how to make middleware redirect - php

I have create form for user to comment in my post but I want need check Auth has Login before submit the form. How can i do that ?
For me I have use middleware to protect it, But If use not login it redirect to Login Form when user has been login it is not redirect back to posts route/show-posts/{post},It redirect to back to route/comments . How can i solve this ?
URL Show Single Post
Route::get( '/show-post/{post}', 'HomePageController#single_show')
->name('home.post.show' );
URL form Comments form
Route::resource('/comments', 'CommentsController');
CommentsController
public function __construct() {
$this->middleware( 'auth')->except(['index', 'show']);
}

You can create a middleware class and redirect like so:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectToComments
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::check()) {
return redirect()->route('comments');
}
return $next($request);
}
}
That is the general form of redirection through middleware, simply modify which route to redirect to or add more conditional logic as needed.

Related

middleware keeps directing me to the login page

I'm working on a website where I have designed an authentication system. The client logs in through email and password. If it is correct it should proceed to the dashboard and should not be able to go back to the login page as long as he/she is logged in. However, middleware keeps directing to the login page saying that 'you have to login first'. Both middleware are registered properly in kernel.php
Kernel.php
protected $routeMiddleware = [
'alreadyLoggedIn' => \App\Http\Middleware\AlreadyLoggedIn::class,
'isLoggedIn' => \App\Http\Middleware\AuthCheck::class ];
Web.php
Route::post('/signin', [customAuthController::class,'loginClient']);
Route::get('/client',[customAuthController::class,'dashboard'])->middleware('isLoggedIn');
Route::get('/signin', [customAuthController::class, 'login'])->middleware('alreadyLoggedIn');
Route::get('/sign_up',[customAuthController::class,'registration'])>middleware('alreadyLoggedIn');
AlreadyLoggedIn (1st Middleware)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class AlreadyLoggedIn
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if(Session()->has('loginId')&& (url('signin')==$request->url()|| url('sign_up')==$request->url()))
return $next($request);
return back();
}
}
IsloggedIn (2nd Middleware)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class AuthCheck
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if(Session()->has('loginId'))
return redirect('signin')->with('fail','You have to login first');
return $next($request);
}
}
customAuthCheck Controller
class customAuthController extends Controller
{
public function dashboard(){
$data = array();
if(Session::has('loginId')){
$data = client::where('id','=',Session::get('loginId'))->first();
}
return view('auth.client', compact('data'));
}
public function logout(){
if(Session::has('loginId')){
Session::pull('loginId');
return redirect('signin');
}
}
}
https://github.com/faaiz99/web-tech-project
In your AuthCheck class (as you named it isLoggedIn in your kernel) first condition is not what you really want to check .
you want to redict user to login if hes not already logged in .
so condition should be something like :
if(!Session()->has('loginId'))
{
return redirect('signin')->with('fail','You have to login first');
}
addition : Its really better if you use laravel auth .
i strongly suggest you to see laravel auth docs
with laravel authentication you can simply use auth facade in your middleware and that would be something like :
if(!auth()->check())
{
return redirect('signin')->with('fail','You have to login first');
}
Hope that helps .

I get redirected to login page every time i try to access the admin dashboard page

When I'm logged as Admin( I'm setting a column which has utype="ADM" to verify me as admin in a session).And when I try to access the admin dashboard page I get redirected to login page and so on without accessing the dashboard eventually.
This is my AuthAdmin.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class AuthAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
if(session('utype') === 'ADM') {
return $next($request);
}else{
session()->flush();
return redirect()->route('login');
}
return $next($request);
}
}
This is my web.php:
Route::middleware(['auth:sanctum', 'verified', 'authadmin'])->group(function() {
Route::get('/admin/dashboard',AdminDashboardComponent::class)->name('admin.dashboard');
I think the issue is mainly focused on the 'authadmin' argument in the route , please provide some tips and help .Thank you

Once go to login page it redirecting to the 404 page using Laravel

I developed the backend function with Laravel and my URL call like https://www.exapmle.com/admin
so it will check already login means it will go to the dashboard otherwise login page https://www.exapmle.com/login it's working fine but after login is success close the browser tab and again go to https://www.exapmle.com/login URL it's going to 404 error and if I go to this URL https://www.exapmle.com/admin it's going to the dashboard without any issue page I don't know why it's happening please help mean to fix this issue.
Login Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/admin';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function logout(Request $request)
{
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/login');
}
}
I found the solution to this issue
RedirectIfAuthenticated.php file
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
// if (Auth::guard($guard)->check()) {
// return redirect('/home');
// }
if (Auth::guard($guard)->check())
{
return redirect()->route('admin');
}
return $next($request);
}
}
Not sure because of insufficient detail maybe you have problem in your web.php. Maybe you don't have apply auth on admin route something like that

Call to a member function setCookie() on null in middleware web

i used from modular structure in laravel that all module in Module folder that routes registerd in ModuleService provider with:
$this->loadRoutesFrom(__DIR__.'/../Routes/web.php');
when i not use from middleware('web') in route then csrf token return null and when i use from this middleware then when user not logined and try to show dashboard page then show error:
Call to a member function setCookie() on null in middleware
Route
Route::get('account/dashboard', [StaffController::class, 'dashboard'])
->middleware(['web','staff'])->name('staff-dashboard');
middleware:staff
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class staff
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
if(Auth::guard('staff')->check() == false)
{
return view('staffauth::login');
}
return $next($request);
}
}
how to resolve this problem?

multiple authentications on laravel

I have built in laravel an authentication system on user table.
I have to make two login pages for admin and normal user on same users table.
I have use spatie roles and permission but it does not stop admin login from normal user login page and vice versa.
I have add checkmaster middleware just for accepting my question on stackoverflow.
namespace App\Http\Middleware;
use Closure;
class CheckMaster
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (\Auth::user()->hasRole('master')) {
return $next($request);
}
return redirect('home');
return $next($request);
}
}
The middleware is working only when user try to go in certain route.
Therefore, the middleware CheckMaster only takes place when logon user tried to go in certain route.
If you are implementing with Auth\LoginController.php, you can override the function authenticated when user is authenticated, example code:
protected function authenticated(Request $request, $user)
{
if ($user->hasRole('master')) {
return redirect('master-home');
}
return redirect('home');
}

Categories