Search code examples
phpeventspyrocms

Programaticly log in a user (PyroCMS + PHP)


In PyroCMS 2.2.3, I want to programaticly login a user once they have activated.

To handle the event I created this in the events file.

But I want to know how to login this user after they activate. I have the $id, but what other variables need to be set?

//inside constructor
Events::register('post_user_activation', array($this, 'evt_post_user_activation'));

....

public function evt_post_user_activation($id) 
{

     $this->ci->current_user = $this->log_in_user($id);

}

private function log_in_user($id)
{

     $this->ci->current_user->id = $id;
}

Solution

  • I did something similiar however I was able to activate automatically because the users were paying customers. I created a new registration controller and actually duplicated the registration funciton from the user controller. Then the following function made this very easy.

    $this->ion_auth->login($user->email, $user->password);

    By digging into the ion_auth library and module in "systems/cms/modules/users/" THe ion_auth login function ultimatly sets the following session data

    $this->session->set_userdata(array(
                'username'             => $user->username,
                'email'                => $user->email,
                'id'                   => $user->id, //kept for backwards compatibility
                'user_id'              => $user->id, //everyone likes to overwrite id so we'll use user_id
                'group_id'             => $user->group_id,
                'group'                => $group_row->name
    ));
    

    It creates the user object with the following query

    $this->db->select('username, email, id, password, group_id')
        ->where(sprintf('(username = "%1$s" OR email = "%1$s")', $this->db->escape_str($identity)));
    
    if (isset($this->ion_auth->_extra_where))
    {
        $this->db->where($this->ion_auth->_extra_where);
    }
    
    $query = $this->db->where('active', 1)
        ->limit(1)
        ->get($this->tables['users']);
    
    $user = $query->row();