Search code examples
symfonysymfony-1.4sfguard

Symfony 1.4 - Login to frontend(as client) from backend


I'm using SfGuardPlugin and on the backend of my site I have the full list of users and I want to be able to login on the frontend with the user that I choose from the list.

I've tried this method:

public function executeListLogin(sfWebRequest $request) {

    // client that I've selected from list
    $client = $this->getRoute()->getObject();

    // create instance if doesn't exist
    if(!sfContext::hasInstance('frontend')){   
        sfContext::createInstance(ProjectConfiguration::getApplicationConfiguration('frontend', 'prod', false));
    }

    // switch to frontend
    sfContext::switchTo('frontend');

    // also tried with: sfContext::getInstance('frontend')
    sfContext::getInstance()->getUser()->signin($client->getSfGuardUser(), true);

    // redirect to frontend homepage
    $this->redirect('@homepage');
}

It redirects me to the frontend homepage, but I'm not logged in.

After more digging I've found out that I'm logged out from backend and now I'm logged in on frontend with admin instead of the user I choose. So the sfContext::switchTo doesn't work correctly.


Solution

  • I've found a workaround.

    1. Create a new column(login_frontend_key) on the users table.
    2. Create a new frontend route with a required parameter(named key)
    3. Create the action in frontend controller witch is responsible for sign in the user, ex:

      public function executeLoginClientKey(sfWebRequest $request){
      
      // get the client by key
      $this->forward404Unless($user = ClientPeer::getByLoginFrontendKey($request->getParameter("key")));
      
      // if you already logged in with another user, signout
      if($this->getUser()->isAuthenticated()) 
      {
        $this->getUser()->signOut();
      }
      
      // signin with the new user
      $this->getUser()->signIn($user->getsfGuardUser(), false);
      $user->setLoginFrontendKey(null); // delete the key from DB
      $user->save();
      
      $this->redirect('@homepage');
      }
      
    4. Use this to generate cross application links http://symfony.com/blog/cross-application-links

    5. Create the object action on the backend users page:

      public function executeListLogin(sfWebRequest $request)
      {
      
      // get the selected client
      $client = $this->getRoute()->getObject();
      
      $key = $client->generateLoginFrontendKey(); // generate a random key
      $client->setLoginFrontendKey($key); // store the key in DB
      $client->save();
      
      // generate the frontend url for login
      $url = $this->getContext()->getConfiguration()->generateFrontendUrl('login_frontend_key', array('key' => $key, 'sf_culture' => 'nb'));
      
      
      $this->redirect($url);
      }