Middleware to check if ajax request is authenticated is not working - ajax

I am trying to handle ajax request that were initiated from idle/expired session(maybe the page was left open and the session got expired). I wrote the below middleware but it's not working as expected:
namespace App\Http\Middleware;
use Closure;
class AjaxSessionCheck
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(!\Auth::check())
{
if($request->ajax())
{
return response()->json(['Session_error'=>'Session Expired'], 401);
//throw new AuthenticationException('Unauthenticated');
}
}
return $next($request);
}
}
To check if this worked i logged into the same page that contains the form from two separate tabs and then logged out from one of the tab, making the session invalid on the other tab as well. Then i initiated an ajax request(user clicks a delete button).
Any help to the right direction will be much appreciated!

for better coverage use if ($request->isJson() || $request->wantsJson()) {

Related

Laravel redirection to https

Hi i ve an app made with laravel and this address http://example.com/check/.
I wanted to redirect to https so i created this middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
class HttpsProtocol
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!$request->secure()) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Then i added
\App\Http\Middleware\HttpsProtocol::class
to Kernel in App/Http in protected $middlewareGroups
Redirection seems to work but redirect to this address https://example.com/check/check
with repeated URI (check)
Why
Thx a lot
It looks like you don't need to append the request URI, that is happening already so try:
if (!$request->secure()) {
return redirect()->secure();
}

Redirect to intended url after visiting many page in Laravel

I want my website visitors' to redirect to the intended url after login. Suppose, I've a protected page dashboard. If any guest tries to access to dashboard, he get redirected to login page. Now, Instead of login he visited other pages and then returned to login page intentionally. How can I redirect him to the previously intended dashboard page after this login?
It would depend on how you're handling the login action, for example if using the RedirectIfAuthenticated middleware you can make the following change:
<?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');
return redirect()->intended('dashboard');
}
return $next($request);
}
}
This will redirect the user to whatever page they intended on accessing and send them to /dashboard by default. You could further extend this by using a different fallback URL depending on the users role in case guests or administrators need to land at a different page after login.

Detecting unauthenticated ajax requests in Laravel

I am trying to handle ajax request that were initiated from idle/expired session(maybe the page was left open and the session got expired). I wrote the below middleware but it's not working as expected:
namespace App\Http\Middleware;
use Closure;
class AjaxSessionCheck
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(!\Auth::check())
{
if($request->ajax())
{
return response()->json(['Session_error'=>'Session Expired'], 401);
}
}
return $next($request);
}
}
I also tried to add this code to the Auth middleware with no luck.
Strangely enough authenticated(user logged in) ajax requests are detected by this.
Lost 2 days finding solutions. Desperate call here.
use optimised code for performance use both auth::check and request->ajax() in same if condition by AND operator. just try session expiry in configuration file
It's because session runs after middleware, you can see the reference here. If you want to check that session expired, I think you should use after middleware instead of before middleware

New registered user to be redirected to the password reset screen

I'm quite new to Laravel and have been stumped on a problem for 2 days - I'd be grateful for some guidance.
I'm using the default out-of-the-box User authentication system with Laravel 5.3. A new user is created automatically behind the scenes by an existing Admin user - I will in time hide the user registration page. I have also successfully set up middleware to check if a user is newly registered (by looking for a null 'last_logged_in_date' that I've added to the migration).
All I want to happen is for a new registered user to be redirected to the password reset screen that ships with Laravel (again, in time I will create a dedicated page). I would like this to happen within the middleware file. So far, my middleware looks like this:
<?php
namespace App\Http\Middleware;
use Closure;
use App\Http\Controllers\Auth;
class CheckIfNewUser
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = $request->user();
if (! is_null($user->last_logged_in_date )) {
return $next($request);
}
// This is where I'm stuck!!!
}
}
I'm not sure what code to enter at the location indicated by the comments above. I've tried sendResetLinkEmail($request); etc and have imported what I though were the correct classes but I always end up with a Call to undefined function App\Http\Middleware\sendResetLinkEmail() message irregardless of what I 'use' at the top of my class.
Where am I going wrong? Thanks!
Well that happens because you have not defined your sendResetLinkEmail($request) function yet. You can do it like this, or you can create a new class with that and then call the class.
Call the trait SendsPasswordResetEmails and then access it with $this since traits are not classes and you cannot access their members directly.
<?php
namespace App\Http\Middleware;
use Closure;
use App\Http\Controllers\Auth;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
class CheckIfNewUser
{
use SendsPasswordResetEmails;
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = $request->user();
if (! is_null($user->last_logged_in_date )) {
return $next($request);
}
// This is where I'm stuck!!!
//EDIT
//return $this->SendsPasswordResetEmails->sendResetLinkEmail($request);
return $this->sendResetLinkEmail($request);
}
}

Laravel v5.2 moving middleware from web group to global?

I was logging request for my site, for guest users and authenticated users, but then i faced a problem that if a user is logged in and a 404 exception kick in then in that case i Auth::user() was null,
class LoggingMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
public function terminate($request, $response)
{
$info = [];
//$info = get everything i need from request and response.
$info['user_detail'] = Auth::user()->id;
var_dump(Auth::user());
dispatch(new LogRequests($info));
}
}
what i did then moved the StartSession middle ware from web group to global middle ware group. Now it is working fine. Is there any issue that can arise by moving the middleware from web group to global?
Global middleware is run every time an HTTP request is made to your application, so if the context of your LoggingMiddleware works with this in mind, then there should be no problem.

Resources