How to get the connected user in a handler with Scheduler in Symfony

I Have tried to get the connected user by injecting the security dependancy but it return null all time.I have used Docker for mercure Hub server, it’s working well (get above this question to get the configuration of mercure Hub).

Can you give me a solution ?

Here is my message

<?php

namespace AppSchedulerMessage;


class ResetPasswordNotification
{
}

Here is my messageHandler

<?php

namespace AppSchedulerHandler;


use SymfonyComponentMercureUpdate;
use SymfonyComponentMercureHubInterface;
use AppSchedulerMessageResetPasswordNotification;
use AppServiceUserService;
use SymfonyComponentMessengerAttributeAsMessageHandler;
use SymfonyBundleSecurityBundleSecurity;

#[AsMessageHandler]
class ResetPasswordNotificationHandler
{

    public function __construct(private HubInterface $hub, private Security $security)
    {
    }

    public function __invoke(ResetPasswordNotification $message)
    {
        dump($this->security->getUser());  // getting null all time
        dump('hello');
        //dd($this->security->getUser()); // getting null all time
        $update = new Update(
            'notifPasswordReset',
            'Veuillez modifier votre mot de passe'
        );
        $this->hub->publish($update);

        //     dd('ok');

        //     $user = $this->security->getUser(); // L"utilisateur connecté n'est pas reconnu et je ne sais pas pourquoi
        //     dd($user);

        //     if ($user) {
        //         $intervals = ['P0D', 'P83D', 'P85D', 'P87D', 'P90D'];
        //         $lastUpdatedPassword = $user->getLastUpdatedPassword();
        //         $today = new DateTime();

        //         foreach ($intervals as $interval) {
        //             $dateToCheck = clone $lastUpdatedPassword;
        //             $dateToCheck->add(new DateInterval($interval));
        //             if ($dateToCheck->format('Y-m-d') === $today->format('Y-m-d')) {
        //                 $update = new Update(
        //                     'notifPasswordReset',
        //                     'Veuillez modifier votre mot de passe'
        //                 );

        //                 $this->hub->publish($update);
        //                 //  return new Response('Notif envoyé!');
        //             }
        //         }
        //     } else {
        //         throw new ErrorException("Aucun utilisateur connecté");
        //     }
    }
}

Here is my scheduler program of automatisation of task

<?php

namespace AppScheduler;

use AppSchedulerMessageResetPasswordNotification;
use SymfonyComponentSchedulerAttributeAsSchedule;
use SymfonyComponentSchedulerRecurringMessage;
use SymfonyComponentSchedulerSchedule;
use SymfonyComponentSchedulerScheduleProviderInterface;
use SymfonyContractsCacheCacheInterface;

#[AsSchedule]
final class MainSchedule implements ScheduleProviderInterface
{
    public function __construct(
        private CacheInterface $cache,
    ) {
    }

    public function getSchedule(): Schedule
    {
        return (new Schedule())
            ->add(
                // @TODO - Create a Message to schedule
                // RecurringMessage::every('1 hour', new AppMessageMessage()),
                RecurringMessage::every('1 second', new ResetPasswordNotification())
            )
            ->stateful($this->cache);
    }
}

//////////////////////// CONFIGURATION OF MERCURE HUB ////////////////////////////////////////////

“/compose.yaml” file

version: '3.8'

services:
  mercure:
    image: dunglas/mercure
    restart: unless-stopped
    environment:
      SERVER_NAME: ':80'
      MERCURE_PUBLISHER_JWT_KEY: '!ChangeThisMercureHubJWTSecretKey!'
      MERCURE_SUBSCRIBER_JWT_KEY: '!ChangeThisMercureHubJWTSecretKey!'
      MERCURE_EXTRA_DIRECTIVES: |
        cors_origins *
    command: /usr/bin/caddy run --config /etc/caddy/Caddyfile.dev --adapter caddyfile
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/healthz"]
      timeout: 5s
      retries: 5
      start_period: 60s
    volumes:
      - mercure_data:/data
      - mercure_config:/config
      - ./config/docker/dev.Caddyfile:/etc/caddy/Caddyfile.dev:ro
    ports:
      - "80:80"
      - "443:443"

volumes:
  database_data:
  mercure_data:
  mercure_config:

“/compose.override.yaml” file

version: '3.8'
services:
###> symfony/mercure-bundle ###
  mercure:
    ports:
       - "3000:80"
###< symfony/mercure-bundle ###

“/env.local” file

DATABASE_URL="mysql://root:connexion_2024&@127.0.0.1:3306/opera?serverVersion=8.3.0&charset=utf8mb4"
MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=0
MERCURE_URL=http://127.0.0.1:3000/.well-known/mercure 
# The public URL of the Mercure hub, used by the browser to connect 
MERCURE_PUBLIC_URL=http://127.0.0.1:3000/.well-known/mercure 
# The secret used to sign the JWTs 
MERCURE_JWT_SECRET="!ChangeThisMercureHubJWTSecretKey!" 

I have tried to inject Security dependancy, i have also tried to create my own service to get the connected user like this :

The service

<?php

namespace AppService;

use AppEntityUser;
use SymfonyBundleSecurityBundleSecurity;

class UserService
{
    private ?Security $security = null;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }


    public function getUser(): ?User
    {
        return $this->security->getUser();
    }
}

Declaration of the service in “config/services.yaml”

  `AppServiceUserService:`

Using the service in the handler of scheduler


<?php

namespace AppSchedulerHandler;


use SymfonyComponentMercureUpdate;
use SymfonyComponentMercureHubInterface;
use AppSchedulerMessageResetPasswordNotification;
use AppServiceUserService;
use SymfonyComponentMessengerAttributeAsMessageHandler;
use SymfonyBundleSecurityBundleSecurity;

#[AsMessageHandler]
class ResetPasswordNotificationHandler
{

    public function __construct(private HubInterface $hub, private UserService $userService, private Security $security)
    {
    }

    public function __invoke(ResetPasswordNotification $message)
    {
        dump($this->userService->getUser()); // getting null all time
        dump($this->security->getUser()); // getting null all time
        dump('hello');
        //dd($this->security->getUser());  // getting null all time
        $update = new Update(
            'notifPasswordReset',
            'Veuillez modifier votre mot de passe'
        );
        $this->hub->publish($update);

        //     dd('ok');

        //     $user = $this->security->getUser(); // L"utilisateur connecté n'est pas reconnu et je ne sais pas pourquoi
        //     dd($user);

        //     if ($user) {
        //         $intervals = ['P0D', 'P83D', 'P85D', 'P87D', 'P90D'];
        //         $lastUpdatedPassword = $user->getLastUpdatedPassword();
        //         $today = new DateTime();

        //         foreach ($intervals as $interval) {
        //             $dateToCheck = clone $lastUpdatedPassword;
        //             $dateToCheck->add(new DateInterval($interval));
        //             if ($dateToCheck->format('Y-m-d') === $today->format('Y-m-d')) {
        //                 $update = new Update(
        //                     'notifPasswordReset',
        //                     'Veuillez modifier votre mot de passe'
        //                 );

        //                 $this->hub->publish($update);
        //                 //  return new Response('Notif envoyé!');
        //             }
        //         }
        //     } else {
        //         throw new ErrorException("Aucun utilisateur connecté");
        //     }
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật