"$request->ajax()" why is not working in laravel middleware? - ajax

$request->ajax(); is not working in laravel 5.5 i want to hendel session redirection for ajax
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Closure;
use Session;
//use Request;
class IsLogin
{
public function handle(Request $request, Closure $next)
{
if($request->ajax())
{
return response()->json(['Session_error'=>'Session Expired'], 401);
//throw new AuthenticationException('Unauthenticated');
}
}

Related

How to trigger event handler when session timeout in laravel?

Is there a way to call event handler when session is up? below is my eventhandler for logout.
class AuthLogoutEventHandler
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
public function __construct($user)
{
$this->user = $user;
}
}
Already registered my Eventhandler and listener in EventServiceProvider.php

Controller return `false` while DashboardController return `true`

I am running laravel 6.11
and by default we have this
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function __construct()
{
dd(Auth::check());
}
}
and I have defined my controller like this,
class DashboardController extends Controller
{
/**
* Display dashboard
*
* #return \Illuminate\Http\Response
*/
public function index()
{
dd(Auth::check());
}
}
Now the user successfully login,
and visiting same page, dashboard at different time
Controller return false while DashboardController return true
Why is that?
As of Laravel 5.3, you can't access the session (including Auth) in the controller constructor. You can, however, define a middleware closure in the constructor that will have access to the session.
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function __construct()
{
$this->middleware(function ($request, $next) {
dd(Auth::check());
});
}
}

Can #RequestMapping in Springboot be omitted?

I want to make the method name be the 'value' of #RequestMapping.
That means how to make the code1 be the code2?
//Code1
#RequestMapping("hello")
public Object hello() {
//...
}
//Code2
public Object hello() {
//...
}
-----add more to make it clear ---2019-2-27 15:47:50
TO make it clear, I want to get two API user/hello, user/bye by code:
#RestController
#RequestMapping(value="/user")
public class UserController {
//no requestmapping annotation here, that is what I say 'omitted'
public object hello() {
// your code
}
//no requestmapping annotation here
public object bye() {
// your code
}
```
Suppose you have one common URL in your request.
Let's say you have /user in your all requests then instead of your writing /user in all your method, you can use #RequestMapping(value="/user") as below. You can have multiple methods inside your controller
#RestController
public class UserController {
#RequestMapping(value="/user/hello",method=RequestMethod.yourMethod)
public object hello() { // your code
}
#RequestMapping(value="/user/bye",method=RequestMethod.yourMethod)
public object bye() { // your code
}
Solution:
#RestController
#RequestMapping(value="/user")
public class UserController {
#RequestMapping(value="/hello",method=RequestMethod.yourMethod)
public object hello() { // your code
}
#RequestMapping(value="/bye",method=RequestMethod.yourMethod)
public object bye() { // your code
}

ASP.NET core - middleware on MVC

I try to create an asp.net core web api on macOS.
But my middleware isn't called on mvc-call.
My Config:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, BackendDbContext context)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
//app.UseStaticFiles();
app.UseMvc();
app.UseMiddleware<AuthMiddleware>();
BackendDbInitializer.Init(context);
}
And my Middleware:
public class AuthMiddleware
{
private readonly RequestDelegate _next;
public AuthMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
Console.WriteLine("Invoke......................");
await _next.Invoke(context);
}
}
When i do a HTTP-request, that doesn't match a controller request. The middleware class is called.
How can i set up that the middleware class is only called on a mvc-request.
You can use middleware as MVC filters:
public class HomeController : Controller
{
[MiddlewareFilter(typeof(AuthMiddleware))]
public IActionResult Index()
{
return View();
}
}
In this case, AuthMiddleware will run each time the action method Index is called.
PS: You need to install this package (Microsoft.AspNetCore.Mvc.Core)
more info (see Middleware as MVC filters section)

How can I register custom error handler in laravel 5?

I'm developing a Laravel package, have a service provider with views and everything, but I need to have custom error messages. How can I register custom error handler in my service provider?
You can register custom handler by binding it with Laravel's exception handler class on service provider.
Create Custom Handler
First you have to create custom exception handler class.
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class CustomHandler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* #var array
*/
protected $dontReport = [
\Illuminate\Auth\AuthenticationException::class,
\Illuminate\Auth\Access\AuthorizationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Session\TokenMismatchException::class,
\Illuminate\Validation\ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* #param \Exception $exception
* #return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $exception
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
if ($exception instanceof NotFoundHttpException) {
return response()->view('errors.404', [], 404);
}
return parent::render($request, $exception);
}
/**
* Convert an authentication exception into an unauthenticated response.
*
* #param \Illuminate\Http\Request $request
* #param \Illuminate\Auth\AuthenticationException $exception
* #return \Illuminate\Http\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest('login');
}
}
Register Your Handler
Now register the class on your AppServiceProvider
<?php
namespace App\Providers;
use App\Exceptions\CustomHandler;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
/**
* Do not forget to import them before using!
*/
$this->app->bind(
ExceptionHandler::class,
CustomHandler::class
);
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
}
}
For more information check this blog http://blog.sarav.co/registering-custom-exception-handler-laravel-5/
Since Laravel 8.0 you can use the built-in renderable and reportable methods on the Handler class that is bound to the ExceptionHandler contract (https://laravel.com/docs/8.x/errors#rendering-exceptions).
So for example:
<?php
namespace App\Providers;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
/** #var ExceptionHandler $exceptionHandler */
$exceptionHandler = resolve(ExceptionHandler::class);
$exceptionHandler->renderable(function (NotFoundHttpException $e, $request) {
if ($request->wantsJson()) {
return response()->json([
'success' => false,
'message' => 'Endpoint not found'
], 404);
}
});
}
}

Resources