doufu5401 2014-10-13 08:15
浏览 38

服务中的Symfony2会话

I'm getting a problem with Symfony2 sessions.

I'm trying to make a service which is executed at the top of every controller. The aim of this service is to authenticate user.

I first check the session to see if there is an "auth" key. If there's not, I check if there is a cookie ...

The problem is on accessing user's session in the service. I've passed the Request object to my service parameters and I get the session using $request->getSession();. Everything seems to work but no data is stored in the session ...

I'm pretty sure the problem comes from the way I get session in the service. But, I don't know how I can do it another way.

Can someone help me please ?

Here is my services.yml file :

services:
    myBundle.authService:
        class: MyCompany\MyBundle\Services\AuthService
        scope: request
        arguments:
            request: @request
            logger: @logger
            em: @doctrine.orm.entity_manager

Here is my AuthService class :

namespace MyCompany\MyBundle\Services;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;

use Doctrine\ORM\EntityManager;
use Monolog\Logger;

use MyCompany\MyBundle\Entity\User;
use MyCompany\MyBundle\Entity\Session;

class AuthService
{
    private $_request;
    private $_logger;
    private $_em;
    private $_session;

    public function __construct(Request $request, Logger $logger, EntityManager $em)
    {
        $this->_request = $request;
        $this->_logger = $logger;
        $this->_em = $em;
        $this->_session = $this->_request->getSession();
        $this->_session->start();

        $this->_fUser = null;

        $encoders = array(new XmlEncoder(), new JsonEncoder());
        $normalizers = array(new GetSetMethodNormalizer());

        $this->_serializer = new Serializer($normalizers, $encoders);
    }

    // THIS FUNCTION IS CALLED IN CONTROLLER
    public function checkAuth()
    {
        $_return = false;

        if($this->checkSession())
        {
            $_return = true;
        }
        else
        {
            $userCookie = $this->checkCookie();
            if($userCookie)
            {
                if(is_array($userCookie) && array_key_exists('token', $userCookie) && array_key_exists('value', $userCookie))
                {
                    $fUser = $this->findUserBySession($userCookie['token'], $userCookie['value']);
                    if($fUser)
                    {
                        $_return = $this->updateSession($fUser);
                    }
                }
            }
        }

        return $_return;
    }

    // CHECK IF SESSION HAS 'FUSER' KEY AND 'AUTH' KEY
    private function checkSession()
    {
        $_return = false;

        if($this->_session && $this->_session->has("FUSER") && $this->_session->has("AUTH") && preg_match("/[0-9a-zA-Z]{58}/", $this->_session->get("AUTH")) === true)
        {
            // I NEVER GO HERE
            $this->_logger->info("OK \o/");
            $_return = $this->_session->get('FUSER');
        }

        return $_return;
    }

    // CHECK IF AUTH COOKIE IS SET
    private function checkCookie()
    {
        $_return = false;

        $cookies = $this->_request->cookies;
        if($cookies && count($cookies) > 0)
        {
            foreach($cookies as $key => $val)
            {               
                if(preg_match("/[0-9a-zA-Z]{58}/", $key) && preg_match("/[0-9a-zA-Z]{58}/", $val))
                {
                    $_return = array('token' => $key, 'value' => $val);
                }
            }
        }

        return $_return;
    }

    // FIND SESSION IN DB AND USER ASSOCIATED
    private function findUserBySession($token, $value)
    {
        $_return = false;

        $fSessionRepository = $this->_em->getRepository("MyCompanyBundle:FSession");
        if($fSessionRepository)
        {
            $fSession = $fSessionRepository->findOneBy(array('token' => $value));
            if($fSession)
            {
                $fUser = $fSession->getUser();
                if($fUser)
                {                    
                    if($fUser->getToken() === $token)
                    {
                        $_return = $fUser;
                    }
                }
            }
        }

        return $_return;
    }

    // UPDATE SESSION TO REGISTER 'USER' AND 'AUTH' KEYS
    public function updateSession(User $fUser)
    {
        $_return = false;

        if($this->_session)
        {
            $this->_session->set('FUSER', $this->serialize($fUser, 'json'));
            $this->_session->set('AUTH', User::generateToken());

            // THIS WORKS FINE
            $this->_logger->info("OK !!! _o/");

            $_return = $this->serialize($fUser, 'json');
        }

        return $_return;
    }

    // SERIALIZE OBJECT
    public function serialize($JSONObject, $format)
    {
        return $this->_serializer->serialize($JSONObject, $format);
    }

    // DESERIALIZE OBJECT
    public function deserialize($JSONObject, $entity, $format)
    {
        return $this->_serializer->deserialize($JSONObject, $entity, $format);
    }
}

Thank you in advance for your time and help.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 基于卷积神经网络的声纹识别
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
    • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
    • ¥15 CSAPPattacklab
    • ¥15 一直显示正在等待HID—ISP
    • ¥15 Python turtle 画图
    • ¥15 stm32开发clion时遇到的编译问题