2015-08-21 37 views
0

代码如下。我有一个loginAction方法,我想通过我的twig文件中的会话访问用户名。如何在symfony2中的应用程序中存储会话并访问它?

public function loginAction(Request $request) 
{ 
    $session= $this->getRequest()->getSession(); 

    if($request->getMethod()=='POST') 
    { 

     $username=$request->get('username'); 
     $password=$request->get('password'); 

     $em= $this->getDoctrine()->getEntityManager(); 
     $repository = $em->getRepository('MWANRegisterBundle:User'); 

     $user= $repository->findOneBy(array('userName'=>$username, 'userPassword'=> $password)); 
     if($user) 
     { 
     $login= new Session(); 

    // Session is in the same class as getter setter functions 
    // for username and password 

     $login->setUsername($username); 
     $session->set('login', $login); 
      if($session->has('login')) 
      { 
      $login = $session->get('login'); 
      $username = $login->getUsername(); 
      // var_dump($username); exit(); 

     // in show_home I redirect to twig file list.html.twig 

      return $this->redirect($this->generateUrl('show_home')); 
      } 

     } 
     else 
     { 
     echo("wrong username OR password"); 
     exit(); 
     } 
    } 

    return $this->render('MWANRegisterBundle:Default:login.html.twig'); 
} 

---------------------这里是注销方法----------------- ---------

public function logoutAction(Request $request) 
{ 
    $session= $this->getRequest()->getSession(); 
    $session->clear(); 
    return $this->render('MWANRegisterBundle:Default:login.html.twig'); 
} 

    // listAction is action to render list.html.twig i want username of  session here 

public function listAction (Request $request) 
{ 
    $session= $this->getRequest()->getSession(); 

     return $this->render('MWANRegisterBundle:Default:list.html.twig'); 

} 

请指引我一步一步......

回答

0

你不需要这个“黑客”来检索记录的用户名,即使在树枝。如果你想确保用户当前登录

只需使用的代码

{{ app.user.username }} 

这个片段中,你可以添加一些明确的控制

{% if app.user %} 
    {{ app.user.username }} 
{% endif %} 

对于一个完整的答案,我想补充也从会议树枝检索

{{ app.session.get('parameterName') }} 
0

您可以通过使用访问您的会话在树枝中和设置会话{{app.session.set("name","value")}}

为用户同治,我建议你使用FOSUserBundle有一个最好的和SECUR应用

+0

===============一个问题=== ================ $ plainPassword = $ this-> get('request') - > request-> get('password'); $ encoder = $ this-> container-> get('security.password_encoder'); $ encoded = $ encoder-> encodePassword($ entity,$ plainPassword); $ entity-> setPassword($ encoded); –

+0

是什么问题? – mgh

+0

Gholami 当我在Security.yml中使用bcrypt。它在动态编码后不会与存储在数据库中的密码相匹配。 –

相关问题