How to trigger event handler when session timeout in laravel? - 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

Related

Is there a way to send websocket message from regular method in spring

I am building web application. There are admin and user roles provided. When user making some action admin is recieving a message that something happened. Websocket connection establishing when user logged. Is there a way to not create ws connection for user and use only HHTP protocol to sending message and send WS message from controller method only?
Now i have theese settings:
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOriginPatterns("*").withSockJS();
}
}
#Controller
public class NotificationController {
#MessageMapping("/notification")
#SendTo("/topic/test")
public Notification getNotification(Notification notification) {
return notification;
}
}
Yes it is possible.
You have to inject SimpleMessagintTemplate, with #Autowire or with constructor.
private final SimpMessagingTemplate simpMessagingTemplate;
public ConstructorName(SimpMessagingTemplate simpMessagingTemplate){
this.simpMessagingTemplate = simpMessagingTemplate;
}
In your controller, or function where you want to send the message to the client use the convertAndSendToUser function.
simpMessagingTemplate.convertAndSendToUser("userId","/private", messageData);
On javascript client side.
var Sock = new SockJS('http://localhost:8080/ws');
stompClient = over(Sock);
stompClient.connect({}, onConnected, onError);
stompClient.subscribe('/topic/' + userId + '/private', onMessageReceived);

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());
});
}
}

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

$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');
}
}

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);
}
});
}
}

How do I return result from a spirngEventListener

I was trying to use spring's eventLisnter in spring-boot 1.3.5.RELEASE.
I was wondering if there is a standard way to return saved object back, or return more information after event was processed.
I may use event as a container to set my saved object back, but I am not sure if this is the best practice, any advice will be appreciated:)
Here is the example:
public class StoreOrderEvent extends ApplicationEvent {
private OrderBean orderBean;
/**
* Create a new ApplicationEvent.
*
* #param source the object on which the event initially occurred (never {#code null})
*/
public StoreOrderEvent (Object source, OrderBean orderBean) {
super(source);
this.orderBean = orderBean;
}
public OrderBean getOrderBean() {
return this.orderBean;
}
}
#Component
public class OrderEventListener{
#Autowired
private OrderRepository orderRepository;
#Order(5000)
#TransactionalEventListener
public void processStoreOrderEvent(StoreOrderEvent event) {
OrderBean orderbean = orderRepository.save(event.getOrderBean());
// return orderBean
}
}
#Service
public class OrderService{
#Autowired
private ApplicationContext applicationContext;
public OrderBean storeOrder(OrderVO vo) {
vo -> orderBean;
applicationContext.publishEvent(new StoreOrderEvent(this, orderBean));
// get my saved orderBean
}
}
As discussed with OrangeDog on comments. it's good to use service and then post event.
or Might use service and use ServiceLocatorFactoryBean to get custom service.

Resources