I also needed to log in a user programatically myself. Afaik existing code of neither Weblogin nor WebloginPE can do this.
The default Weblogin snippet is indeed way too complicated to use as an inspiration. By far the easier way was to go the WebloginPE route.
I found it needed to be extended to offer this function. So I made a new class which extends WebLoginPE and provides a function called "TriggerLogin".
How to install: Simply create a file called webloginpe.extended.class.php with the following code in it and store it in assets/snippets/webloginpe:
require 'webloginpe.class.php';
class WebloginPEextended extends WebloginPE
{
/**
* TriggerLogin
* Perform all the necessary functions to establish a secure user session with permissions
* Similar to Login() but works manually
* (instead of processing username/password from $_POST it takes username/password arguments)
*
* @param string $username
* @param string $password
* @return void
* @author Johan "MrDutchy" van den Broek
*/
function TriggerLogin($username, $password, $customTable = 'web_user_attributes_extended')
{
global $modx;
$this->CustomTable($customTable,'');
$this->Username = $modx->db->escape(strip_tags($username));
$this->Password = $modx->db->escape(strip_tags($password));
if ($this->Username == '' || $this->Password == '')
return;
$this->OnBeforeWebLogin();
$this->User = $this->QueryDbForUser($this->Username);
if ($this->User == false)
return;
$this->UserIsBlocked();
$this->Authenticate();
$this->SessionHandler('start');
$this->OnWebLogin();
$this->ActiveUsers();
$this->UserDocumentGroups();
}
}
To demonstrate this works I wrote a simple snippet which has a button to trigger a login. For simplicity’s sake I use hardcoded username/password. If these exist in your install it will authenticate by them. This can easily be integrated into plugins or snippets in any cases you need it.
include_once MODX_BASE_PATH.'assets/snippets/webloginpe/lang/de.php';
include_once MODX_BASE_PATH.'assets/snippets/webloginpe/webloginpe.extended.class.php';
if (count($_POST) > 0 && isset($_POST['doDummy']))
{
$wlpe = new WebLoginPE($wlpe_lang);
return $wlpe->TriggerLogin('mywebuser', 'mypassword');
}
else
{
return
'<form action="" method="post">
<input type="submit" name="doDummy" value="doDummy" />
</form>';
}