简体   繁体   English

如何在Symfony控制器中初始化会话并在视图中访问它

[英]How to initialize session in symfony controllers and access it in views

I am using symfony 2.7 and I would like to show site navbars like login/logout depending a condition. 我正在使用symfony 2.7,并且想根据条件显示类似登录/注销的站点导航栏。

I am not using a database to log in users, but rather a session that is enitialized in a controller. 我不是使用数据库登录用户,而是使用控制器中已启用的会话。

Anyway, how can I tie this session and make sure users see login/logout pages? 无论如何,我如何绑定此会话并确保用户看到登录/注销页面?

Let's say this is a nav 假设这是一台导航仪

<a href='{{ path('login') }}'> login </a>
<a href='{{ path('logout') }}'> logout </a>

And this is my controller 这是我的控制器

public function checkSessionAction(Request $request){
    $session = $request->getSession(); 

    if ( some logic ){
        $session->set('user_ID', $someData);
    }
}

Now, in simple terms I need a way to see if user_ID is set in twig so to show which nav link I want 现在,简单来说,我需要一种方法来查看是否在树枝中设置了user_ID,以便显示我想要的导航链接

If the login was successful, you could initialize the session in the controller 如果登录成功,则可以在控制器中初始化会话

$this->get('session')->set('IsAuth', true);

In the view using template engine Twig you could check session value: 在使用模板引擎Twig的视图中,您可以检查会话值:

  {% if app.session.get('IsAuth')  %}
         <a href='{{ path('login') }}'> login </a>
   {% else %}
         <a href='{{ path('logout') }}'> logout </a>
  {% endif %} 

Answering your comment, you could use Symfony2 authentication trying something like that: 回答您的评论,您可以使用Symfony2身份验证尝试执行以下操作:

Use the namespace: UsernamePasswordToken in your controller: 在控制器中使用名称空间:UsernamePasswordToken:

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

Retrieve your roles from database and store it in $aRoleNameToken 从数据库中检索您的角色并将其存储在$ aRoleNameToken中

 $aRoleNameToken = array('ROLE_ADMIN','ROLE_USER');

Set token if authentication was successful: 如果身份验证成功,则设置令牌:

$token = new UsernamePasswordToken($username, null,'secured_area',$aRoleNameToken);

$this->get('security.context')->setToken($token);

In the view, you could check if that rol has been assigned to the current user: ( http://symfony.com/doc/2.8/security.html ) 在视图中,您可以检查该角色是否已分配给当前用户:( http://symfony.com/doc/2.8/security.html

 {% if is_granted('ROLE_ADMIN') %}
         <a href="...">Delete</a>
 {% endif %}

Log out action: 注销操作:

 /**
 * @Route("/logout", name="logout")
 */
public function logoutAction() {
   $this->get('security.token_storage')->setToken(null);
   $this->get('request')->getSession()->invalidate();
   return new RedirectResponse($this->generateUrl('login'));
}

In security.yml file, you could do some configurations about the session. 在security.yml文件中,您可以对会话进行一些配置。

    access_control:
    - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin, roles: [ROLE_ADMIN] }   
    - { path: ^/home, roles: [ROLE_ADMIN,ROLE_USER] } 
    - { path: ^/login, roles: [ROLE_ADMIN,ROLE_USER]}
    - { path: /, roles: [ROLE_ADMIN,ROLE_USER]}   

As you can see ^/login has the value 'IS_AUTHENTICATED_ANONYMOUSLY', it means that the login page is the only one that you could see without authentication, if you try to acces to another path for example '/home' or '/admin' and you don't have autenticathion(that was previously setted in your login action), you will be redirected to login page. 如您所见^ / login的值为'IS_AUTHENTICATED_ANONYMOUSLY',这意味着如果您尝试访问其他路径(例如'/ home'或'/ admin'),则登录页面是唯一无需身份验证即可看到的页面。并且您没有autenticathion(先前在登录操作中设置的),您将被重定向到登录页面。

   - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }

For example the next sentence means that you must have the role ROLE_ADMIN, if you want to access to the path: /admin 例如,如果要访问路径,则下一句话意味着您必须具有ROLE_ADMIN角色:/ admin

- { path: ^/admin, roles: [ROLE_ADMIN] } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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