Archive

Archive for December, 2011

Authentication Using WordPress and Zend Framework

December 19th, 2011 Comments off

I recently had the need to implement a Zend Framework web app that could authorize against WordPress without necessarily using WordPress as the front end. I was very relieved to find out it was quite easy to do!

In your application’s index.php (typically found at public/index.php) you need to include the WordPress header file to make sure you have access to the WordPress functions later in your application:

defined('WORDPRESS_DIR') || define('WORDPRESS_DIR', realpath(dirname(__FILE__) . '/wordpress'));
require_once(WORDPRESS_DIR . '/wp-blog-header.php');

I have the following code in my LoginController.php (application/modules/public/controllers/LoginController.php) file.

doWordpressAuth function

protected function doWordpressAuth($username, $password)
{

    // Optional - Sanitize user input in this method
    // or handle it before calling authenticate
    $username = sanitize_user($username);
    $password = trim($password);

    $creds = array('user_login' => $username,
                   'user_password' => $password,
                   'remember' => true
            );
    $user = wp_signon($creds, false);

    if($user == null)
    {
        // Invalid username or password
        return null;
    }

     $ignore = array('empty_username', 'empty_password');
     if((is_wp_error($user))&&(!(in_array($user->get_error_code(),$ignore))))
     {
        // Login failed due to some error...
        return null;
     }

     return $user;
}

IndexAction

public function indexAction()
{
    $request = $this->getRequest();
    if(!$request->isPost()){ return $this->render('index'); }

    $username = $request->getParam('username');
    $password = $request->getParam('userpass');

    if((is_null($username))||(is_null($password)))
    {
        $this->addError('Missing username or password');
        return $this->render('index');
    }
    // Enforce username and password minimum lengths
    elseif((strlen($username) < 4)||(strlen($password) < 6))
    {
        $this->addError('Invalid username or password');
        return $this->render('index');
    }

    // Use wordpress for authentication
    if(AC_Utilities::getApplicationSetting('use_wp_auth') == true)
    {
        $user = $this->doWordpressAuth($username, $password);
        /**
         * ...
         * Various user detail handling procedures...
         * ...
         */
        $session->user = $user;
    }
    // Use built-in authentication mechanism
    else
    {
        /**
         * ...
         * Use built in login mechanism ...
         * ...
         */
    }
    // Logged in, redirect to the IndexController
    $this->_helper->redirector('index','index');
}