Manual Magento User Authentication

Having just been building a webapp to work in conjunction with a Magento Store, it’s made sense to use the existing Magento login.  For my own future reference, and that of anyone else that might need it, here’s how to do it!

To get Customers authenticated,

// Or whatever the path to your app/Mage.php happens to be ...
require_once( dirname(__FILE__).'/app/Mage.php' );
// Initialize Magento ...
Mage::app("default");
// Set the variables that we care about.
$id = 1;  // The Store ID.  Since Magento can handle multiples, this may change.
$username = 'their.email@their.domain.com';  // Their email address / username (the same thing)
$password = 'theirpassword';  // Their password.
	
try{
	$blah = Mage::getModel('customer/customer')->setWebsiteId($id)->authenticate($username, $password);
}catch( Exception $e ){
	$blah = false;
}

As it will throw an exception if the authentication doesn’t actually happen, instead of simply returning false, we’ve got to catch that and convert it into a false ourselves.

Now, if you want to authenticate admins, give this bit a go:

// Or whatever the path to your app/Mage.php happens to be ...
require_once( dirname(__FILE__).'/app/Mage.php' );
// Initialize Magento ...
Mage::app("default");
// Set the variables that we care about.
$username = 'admin';  // Or whatever username we're going with.
$password = 'password'; // Obviously, replace this with whatever the actual password you're looking to validate is.

$blah = Mage::getModel('admin/user')->authenticate($username, $password);

After either of these blocks of code, depending on whether you’re validating an admin or customer, $blah will contain TRUE for it being valid, or FALSE for it being invalid!

Simple, huh?

Author: George Stephanis

Cooking, Code, Carpentry, Letterpress.