将用户ID设置为Joomla中的当前用户

I have a userId - $uid.

I wanted to make this user as logged in to the s/m in joomla.

I've tried this -

$currentUser = new JUser($uid);

$mainframe = JFactory::getApplication('site');
$credentials = array();
$credentials['username'] = $currentUser->username;
$credentials['password'] = $currentUser->password; //this is the hashed password

//perform the login action
$mainframe->login($credentials);

$newuser = JFactory::getUser(); //this doesn't get updated to the new user ($uid) details

How can I make the user as the current user by using the uid itself?

Update: I just found that user can be loaded with JUser::load()

Trial 2-

$user = JUser::getInstance($uid);
$user->load($uid); //this should load the new user.

$newuser = JFactory::getUser(); //still i get the anonymous details here 
            //($newuser->id = 0)

As there is wp_set_current_user($uid); for wordpress user_load_by_name() in drupal, is there any similar function for joomla ? Please help.!!!

Thanks!

I don't have much knowledge about Joomla so I was not able to implement it but here is my idea:

I remembered that there was a switch user plugin for joomla. I searched for it and found this. It should be possible to port this code to change user by user-id, like you need it. Noting else they are doing after clicking on the link in admin-cp.

A bit late, but it can help someone in the future. In order to set the user for JFactory::getUser(), you need to set it in the session:

JFactory::getSession()->set('user', JFactory::getUser($uid));