简体   繁体   中英

[Symfony2]current user in service

Hell,

i try to use clankbundle for websocket use but i can't get my current user in my service

Call to a member function getUser() on a non-object in ...\\NotificationTopic.php

my code :

-Service.YML

services:
    service_Default:
        class: Nuwland\WebBundle\Controller\CentreinteretController
        arguments: [ @doctrine.orm.entity_manager ]
    nuwland.web.notification:
        class: Nuwland\WebBundle\Topic\NotificationTopic
        arguments: ["@security.context"]
    kernel.listener.clank.client_event:
        class: Nuwland\WebBundle\EventListener\NuwlandClientEventListener
        arguments: ["@security.context"]
        tags:
            - { name: kernel.event_listener, event: clank.client.connected, method: onClientConnect }
            - { name: kernel.event_listener, event: clank.client.disconnected, method: onClientDisconnect }
            - { name: kernel.event_listener, event: clank.client.error, method: onClientError }

-NotificationTopic.php

<?php

namespace Nuwland\WebBundle\Services;

use JDare\ClankBundle\Topic\TopicInterface;
use Ratchet\ConnectionInterface as Conn;
use Symfony\Component\Security\Core\SecurityContext;


class NotificationTopic implements TopicInterface
{

   private $context;

    public function __construct(SecurityContext $securityContext){
        $this->context= $securityContext;
    }

    private function getUser(){
            return $this->context->getToken()->getUser();
    }
    /**
     * This will receive any Subscription requests for this topic.
     *
     * @param \Ratchet\ConnectionInterface $conn
     * @param $topic
     * @return void
     */
    public function onSubscribe(Conn $conn, $topic)
    {

     $userId = $this->getUser();
     var_dump($userId);
}

if anyone can help me, Thanks

Always check getToken() for null. The user isn't authenticated in the system

You cant get user by calling:

$this->context->getToken()->getUser()

Websocket server doesn't know anything about your application users. In this case - you must insert a 'clientManipulator' service into your topic and after it you can

$user = $this->clientManipulator->getClient($connection);

Do not forget to check that result is 'instanceof' your User object. And remeber that websocket server has access to your session cookies (it must be in the same domain, or has access to another domain name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM