如何在symfony2中显示所有用户会话?以及如何杀死他们中的一些?

时间:2015-10-29 15:04:34

标签: php symfony session

我需要在Symfony2中管理用户会话。

我的项目有很长的会话期。

  1. 显示所有活动用户会话的列表。 例如:当有人使用我的登录名/密码时,我想看到它。

  2. 删除一些会话。 例如:如果我理解某些会话是犯罪分子,我可以将其删除。

  3. 我在官方Symfony文档中找到了如何安装custom session handler,但我无法理解如何通过此参数设置user_id来搜索会话。

    默认情况下,Db会话处理程序的表结构:

    "CREATE TABLE ".$dbh->quote_identifier($table)." (column VARCHAR(17));"
    

1 个答案:

答案 0 :(得分:1)

行。我找到了解决方案!)我接受了pdo处理程序,然后添加了两个字段(user_id和agent),以查找当前用户的会话并显示有关他的信息。

  1. 创建自定义处理程序
  2. config.yml

    framework:
           handler_id: session.handler.pdo.custom
    

    services.yml

    services:
        session.handler.pdo.custom:
            class: YourBundle\HttpFoundation\Session\Storage\Handler\UserIdPdoSessionHandler
            public:    true
            arguments:
                - "pgsql:host=%database_host%;dbname=%database_name%"
                - { db_username: %database_user%, db_password: %database_password% }
                - @security.token_storage
    

    表格的SQL

    CREATE TABLE sessions (sess_id VARCHAR(128) NOT NULL, sess_data BYTEA NOT NULL, sess_time INT NOT NULL, sess_lifetime INT NOT NULL, user_id INT DEFAULT NULL, server_addr VARCHAR(255) DEFAULT NULL, agent TEXT DEFAULT NULL, PRIMARY KEY(sess_id)) 
    

    创建控制器操作以显示会话:

    /**
     * @Route(name="user_profile_sessions_list", path="/sessions")
     *
     * @param Request $request
     *
     * @return Response
     */
    public function sessionsListAction(Request $request)
    {
        $user = $this->getUser();
        $sessions = $this->get('session.handler.pdo.custom')->getSessionsByUserId($user->getId());
        return $this->render('YourBundle:Profile:sessions.html.twig', array(
            'sessions' => $sessions,
        ));
    }
    

    创建控制器操作以删除会话:

    /**
     * @Route(name="user_profile_sessions_delete", path="/sessions/delete/{sessionId}")
     *
     * @param Request $request
     *
     * @return Response
     */
    public function sessionDeleteAction(Request $request, $sessionId)
    {
        $em = $this->getDoctrine()->getManager();
    
        //Удалим сессию из БД (если это текущая сессия, то сделаем logout)
        if ($sessionId == $this->get('session')->getId()) {
            $redirect = $this->redirect($this->generateUrl('fos_user_security_logout'));
        } else {
            $this->get('session.handler.pdo.custom')->destroy($sessionId, $this->getUser()->getId());
            $redirect = $this->redirect($this->generateUrl('user_profile_sessions_list'));
        }
    
        return $redirect;
    }
    

    如果您愿意,可以创建实体:

    <?php
    
    namespace Uip\UserBundle\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * Sessions
     *
     * @ORM\Table(name="sessions")
     * @ORM\Entity
     */
    class Sessions
    {
        /**
         * @var string
         * @ORM\Id
         * @ORM\Column(name="sess_id", type="string", length=128, nullable=false)
         */
        private $sessId;
    
        /**
         * @var string
         * @ORM\Column(name="sess_data", type="blob", nullable=false)
         */
        private $sessData;
    
        /**
         * @var integer
         * @ORM\Column(name="sess_time", type="integer", nullable=false)
         */
        private $sessTime;
    
        /**
         * @var integer
         * @ORM\Column(name="sess_lifetime", type="integer", nullable=false)
         */
        private $sessLifetime;
    
        /**
         * @var integer
         * @ORM\Column(name="user_id", type="integer", nullable=true)
         */
        private $userId;
    
        /**
         * @var string
         * @ORM\Column(name="server_addr", type="string", nullable=true)
         */
        private $serverAddr;
    
        /**
         * @var string
         * @ORM\Column(name="agent", type="text", nullable=true)
         */
        private $agent;
    
    
        /**
         * Get sessId
         *
         * @return string
         */
        public function getSessId()
        {
            return $this->sessId;
        }
    
        /**
         * Get sessData
         *
         * @return string
         */
        public function getSessData()
        {
            return $this->sessData;
        }
    
        /**
         * Set sessData
         *
         * @param string $sessData
         * @return Sessions
         */
        public function setSessData($sessData)
        {
            $this->sessData = $sessData;
    
            return $this;
        }
    
        /**
         * Get sessTime
         *
         * @return integer
         */
        public function getSessTime()
        {
            return $this->sessTime;
        }
    
        /**
         * Set sessTime
         *
         * @param integer $sessTime
         * @return Sessions
         */
        public function setSessTime($sessTime)
        {
            $this->sessTime = $sessTime;
    
            return $this;
        }
    
        /**
         * Get sessLifetime
         *
         * @return integer
         */
        public function getSessLifetime()
        {
            return $this->sessLifetime;
        }
    
        /**
         * Set sessLifetime
         *
         * @param integer $sessLifetime
         * @return Sessions
         */
        public function setSessLifetime($sessLifetime)
        {
            $this->sessLifetime = $sessLifetime;
    
            return $this;
        }
    
        /**
         * Get userId
         *
         * @return integer
         */
        public function getUserId()
        {
            return $this->userId;
        }
    
        /**
         * Set userId
         *
         * @param integer $userId
         * @return Sessions
         */
        public function setUserId($userId)
        {
            $this->userId = $userId;
    
            return $this;
        }
    
        /**
         * Get serverAddr
         *
         * @return string
         */
        public function getServerAddr()
        {
            return $this->serverAddr;
        }
    
        /**
         * Set serverAddr
         *
         * @param string $serverAddr
         * @return Sessions
         */
        public function setServerAddr($serverAddr)
        {
            $this->serverAddr = $serverAddr;
    
            return $this;
        }
    
        /**
         * Get agent
         *
         * @return string
         */
        public function getAgent()
        {
            return $this->agent;
        }
    
        /**
         * Set agent
         *
         * @param string $agent
         * @return Sessions
         */
        public function setAgent($agent)
        {
            $this->agent = $agent;
    
            return $this;
        }
    }
    

    和twig文件:

    {% extends '@Your/layout.html.twig' %}
    {% block content %}
        <h3>{{ 'user.sessions.list' | trans }}</h3>
    
        <div class="panel panel-default">
            <div class="panel-body">
                <table class="table table-striped">
                    {% for session in sessions %}
                        <tr>
                            <td>{{ session.sess_time|date('d.m.Y H:i:s') }}</td>
                            <td>{{ (session.sess_time + session.sess_lifetime)|date('d.m.Y H:i:s') }}</td>
                            <td>{{ session.server_addr }}</td>
                            <td>{{ session.agent }}</td>
                            {% if session.sess_id == app.session.id %}
                                <td><a href="{{ path('fos_user_security_logout') }}" type="button" class="btn btn-danger">Удалить</a>
                                    Текущая
                                </td>
                            {% else %}
                                <td><a href="{{ path('user_profile_sessions_delete', {'sessionId' : session.sess_id}) }}"
                                       type="button" class="btn btn-danger">Delete</a></td>
                            {% endif %}
                        </tr>
                    {% endfor %}
                </table>
    
            </div>
        </div>
    {% endblock %}