LiveUser

PEAR::LiveUser authentication and permission framework

AdvancedSearch | AreaMap ]

Search:

  Welcome to LiveUser   Documentation   RoadMap   Wishlist   About  
   

Username:

Password:


Areas In
This Wiki

BEPHPUG

Conferences

emPHPower

LiveUser

Main

MDB2

PDO

PEARThinkTank

PHPSVN

PHPTODO

RDBMS

WebBuilder2

Example 1

Example 1 comprises 3 main files:

  • Auth_XML.xml
  • conf.php
  • example.php

There is also an index.html (just a link to example.php really) as well as a README file in the example directory. These can be ignored.

Auth_XML.xml

Auth_XML.xml must have read and write permission for the web server user. 666 would be the best permission .... chmod 666 Auth_XML.xml (Applies only on linux and unix). This is simple enough -- it is just an XML file containing user IDs, user names, and password hashes. The passwords are hashed using MD5 (use the PHP md5() function or any other MD5 handler, e.g. MySQL? or perl).

<?xml version="1.0"?>
<liveuserAuthXML>
  <user>
    <userId>c4ca4238a0b923820dcc509a6f75849b</userId>
    <handle>father</handle>
    <password>0de959beaa82daa7df6ef2286d071a6d</password>
    <currentLogin>1047658848</currentLogin>
    <lastLogin>1122549561</lastLogin>
    <isActive>Y</isActive>
    <name>Bob</name>
  </user>
  <user>
    <userId>c81e728d9d4c2f636f067f89cc14862c</userId>
    <handle>mother</handle>
    <password>6ee6a213cb02554a63b1867143572e70</password>
    <currentLogin>1047658859</currentLogin>
    <lastLogin>1095528658</lastLogin>
    <isActive>Y</isActive>
    <name>Jane</name>
  </user>
  <user>
    <userId>eccbc87e4b5ce2fe28308fd9f2a7baf3</userId>
    <handle>child</handle>
    <password>1b7d5726533ab525a8760351e9b5e415</password>
    <currentLogin>1047565777</currentLogin>
    <lastLogin>1047565686</lastLogin>
    <isActive>Y</isActive>
    <name>Michael</name>
  </user>
</liveuserAuthXML>

conf.php

conf.php contains the configuration settings for LiveUser. Note that LiveUser can be configured in many ways -- see ConfiguringLiveUser?. In this case we have simply decided to define a static array containing all of LiveUser's parameters. This can be passed to the LiveUser factory method.

For more information on the parts ofthe LiveUser configuration array, see under "factory" on the auto-generated documentation page here: http://pear.php.net/package/LiveUser/docs/latest/LiveUser/LiveUser.html#methodfactory


<?php
//
// This is a common "BC Hack" to define the normal PATH_SEPARATOR variable
// in PHP -- normally defined in versions of PHP later than 4.3.0.  So this
// code gets activated on earlier versions.
//
if (!defined('PATH_SEPARATOR')) {
    if (defined('DIRECTORY_SEPARATOR') && DIRECTORY_SEPARATOR == '') {
        define('PATH_SEPARATOR', ';');
    } else {
        define('PATH_SEPARATOR', ':');
    }
}

//
// set this to the path in which the directory for liveuser resides
// or remove the following two lines to test LiveUser in the standard
// PEAR directory
//
# $path_to_liveuser_dir = 'PEAR/'.PATH_SEPARATOR;
# ini_set('include_path', $path_to_liveuser_dir.ini_get('include_path') );

//
// Include the required LiveUser classes.
//
require_once 'LiveUser.php';
require_once 'Log.php';

//
// Define the LiveUser configuration, only if the file Auth_XML.xml is
// present and can be written to.
//
if (is_readable('Auth_XML.xml') && is_writable('Auth_XML.xml')) {

    //
    // Create a Log object.
    //
    $logger =& Log::factory('win', 'liveuserlog');

    //
    // LiveUser configuration array.
    //
    $liveuserConfig = array(
        'debug' => &$logger,
        //
        // One or more authentication containers can be defined.
        //
        'authContainers' => array(
            0 => array(
                //
                // In this case we are only going to define one container,
                // that is of type "XML".  We set up some basic parameters
                // for that container.
                //
                'type' => 'XML',
                'expireTime'   => 3600,
                'idleTime'     => 1800,
                'allowDuplicateHandles'  => false,
                'passwordEncryptionMode' => 'MD5',
                'storage' => array(
                    //
                    // Set up a storage container.  In this case we are going
                    // to use an XML file on the disk, in the current directory.
                    //
                    'file' => 'Auth_XML.xml',
                    'alias' => array(
                        'auth_user_id' =>   'userId',
                        'passwd' =>         'password',
                        'lastlogin' =>      'lastLogin',
                        'is_active' =>      'isActive',
                        'name' =>           'name'
                    ),
                    'tables' => array(
                        'users' => array(
                            'fields' => array(
                                'lastlogin'         => false,
                                'is_active'         => false,
                                'owner_user_id'     => false,
                                'owner_group_id'    => false,
                                'name'              => false,
                            ),
                        ),
                    ),
                    'fields' => array(
                        'lastlogin'         => 'timestamp',
                        'is_active'         => 'boolean',
                        'owner_user_id'     => 'integer',
                        'owner_group_id'    => 'integer',
                        'name'              => 'text',
                    ),
                ),
            ),
        ),
    );
}
?>

example.php

This is the actual code that uses LiveUser.

This example sets up an authorization system using the LiveUser class. You don't have to use this to use the LiveUser class(es), but this way you don't need to take care of the login-process, storing the user object in a session and more...

The important methods used here are:

login
http://pear.php.net/package/LiveUser/docs/latest/LiveUser/LiveUser.html#methodlogin
logout
http://pear.php.net/package/LiveUser/docs/latest/LiveUser/LiveUser.html#methodlogout
isLoggedIn?
http://pear.php.net/package/LiveUser/docs/latest/LiveUser/LiveUser.html#methodisLoggedIn
getProperty
http://pear.php.net/package/LiveUser/docs/latest/LiveUser/LiveUser.html#methodgetProperty

<?php
/**
 * Test for the LiveUser class
 * ===============================
 *
 * @author Bj&#65533;n Kraus <krausbn@php.net>
 * @version $Id: example.php,v 1.12 2005/12/18 12:41:10 lsmith Exp $
 **/
error_reporting(E_ALL);

// Get LiveUser configuration array
require_once 'conf.php';

if (!isset($liveuserConfig)) {
    die('<p style="color: red; text-align: center;">' .
      "The XML file isn't readable/writable. Add the right " .
      'permissions to it and then try again.</p>');
}

// The error handling stuff is not needed and used only for debugging
// while LiveUser is not yet mature
PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'eHandler');

function eHandler($errObj)
{
    echo('<hr /><span style="color: red">' . $errObj->getMessage() . ':<br />'. $errObj->getUserInfo() . '</span><hr />');
}

//
// Create an extension of the log class.  Not exactly sure why this
// is here or required.
//
class Log_liveuserlog extends Log
{
    function Log_liveuserlog($name = '', $ident = '', $conf = array(),
                            $level = PEAR_LOG_DEBUG)
    {
        $this->_id = md5(microtime());
        $this->_ident = $ident;
        $this->_mask = Log::UPTO($level);
    }

    function log($msg, $level)
    {
        echo "message: $msgn";
    }
}

//
// Create an observer for the LiveUser class.
//
class LU_Default_observer
{
    function notify(&$notification)
    {
        echo "observer called on event: " . $notification->getNotificationName() . " n";
    }
}

// Create new LiveUser (LiveUser) object.
// Well only use the auth container, permissions are not used.
$LU =& LiveUser::factory($liveuserConfig);

$obs = new LU_Default_observer();

//
// Add the observer created above on the dispatcher object in
// LiveUser.  The dispatcher object is of type Event_Dispatcher,
// which is documented here:
// http://pear.php.net/manual/en/package.event.event-dispatcher.php
//
$LU->dispatcher->addObserver(array(&$obs, 'notify'));

//
// Initialise the LiveUser class and abort if there are any errors.
//
if (!$LU->init()) {
    var_dump($LU->getErrors());
    die();
}

//
// Fetch the user name, password, and logout request from the $_REQUEST
// array, so that login and logout requests can be handled.
//
$username = (array_key_exists('handle', $_REQUEST)) ? $_REQUEST['handle'] : null;
$password = (array_key_exists('passwd', $_REQUEST)) ? $_REQUEST['passwd'] : null;
$logout = (array_key_exists('logout', $_REQUEST)) ? $_REQUEST['logout'] : false;

//
// If a logout has been requested then log the user out.
//
if ($logout) {
    $LU->logout(true);
} elseif($username && (!$LU->isLoggedIn() || $LU->getProperty('handle') != $username)) {

//
// If a login has been requested then log the user in.
//
    $LU->login($username, $password);
}

//
// Print some HMTL to the browser.  For heaven's sake people, if you are
// doing this in real life then use a template class.  Please!
//
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>Example 1</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <style type="text/css">
    <!--
    body {
        font-family: Verdana, Arial, Helvetica, sans-serif;
        font-size: 12px;
        color: #000000;
        background-color: #FFFFFF
    }

    table {
        border: 1px solid #000;
        border-top: 0px;
        border-right: 0px;
        border-spacing: 0px;
        border-collapse: collapse;
    }

    table td {
        width: 100px;
        border-top: 1px solid #000;
        border-right: 1px solid #000;
        padding: 5px;
    }

        .center {
           text-align: center;
    }
    .center table {
           margin: auto;
    }
    -->
    </style>
</head>

<body>
<?php

//
// Check if the user has logged in successfully.  If the user has
// not logged in and no login name has been sent, then draw a login
// form.
//
if (!$LU->isLoggedIn()) {
    if (!$username) {
?>
    <form name="loginform" method="post" action="example.php">
    <div class="center">
        <table width="300" border="0" cellspacing="0" cellpadding="5">
            <tr>
                <td colspan="2"><b>Example login</b></td>
            </tr>
            <tr>
                <td>Handle:</td>
                <td>
                    <input type="text" name="handle" maxlength="80" value="" />
                </td>
            </tr>
             <tr>
                <td>Password:</td>
                <td>
                    <input type="password" name="passwd" maxlength="80" value="" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <div class="center">
                        <input type="submit" value="Login" />
                    </div>
                </td>
            </tr>
        </table>
    </div>
    </form>
<?php
    //
    // The user has not logged in, but a login name has been sent.
    // First let's check if the reason was that the user has not
    // yet been declared "valid" by an administrator.
    //
    } else if ($LU->isInactive()) {
?>
        <h3>Sorry kid, but one of our admins has yet approved
       your user status. Please be patient. Don't call us -
       we'll call you.</h3>
      <p align="center"><a href="example.php?logout=1">Logout</a></p>
<?php
    } else {

    //
    // The user has not logged in, a login name is present, and
    // the user is valid.  So this is probably a failed login
    // attempt.
    //
?>
      <h3>Sorry, we can't let you in. Check if the spelling of
      your handle and password is correct.</h3>
      <p align="center"><a href="example.php?logout=1">Logout</a></p>
<?php
    }

//
// And finally we draw some useful information for this example.  Note
// that in a real system you don't normally write all of the user names
// and passwords to the login screen.  I'm preaching to the converted, yes?
// Please tell me I am.  Thanks.
//
?>
        <p>&nbsp;</p>
        <p><i>Login Data for this Example:</i></p>
        <table>
            <tr>
                <td style="text-align: center; font-weight: bold;">Handle</th>
                <td style="text-align: center; font-weight: bold;">Password</th>
            </tr>
            <tr>
            <td>father</td>
                <td>father</td>
            </tr>
            <tr>
            <td>mother</td>
                <td>mother</td>
            </tr>
            <tr>
                <td>child</td>
                <td>child</td>
    </tr>
    </table>
<?php
} else {

//
// The user has successfully logged in.  So write some useful information
// to the screen, including the user's login name (handle).
//
?>
    <h2 align="center">User logged in: <?php echo $LU->getProperty('handle'); ?></h2>
    <h3>Congrats, you're in</h3>
    <p align="center"><a href="example.php?logout=1">Logout</a></p>
<?php
}

//
// Just some more debug output with no further relevance
//
echo '<hr />Handle:';
print_r($LU->getProperty('handle'));
echo '<hr />Name:';
print_r($LU->getProperty('name'));

echo '<hr /><pre>';
print_r($LU);
echo '<hr />';
print_r($_SESSION);
echo '<hr />';
print_r($_REQUEST);
echo '<hr />';
echo 'Observer<br />';
var_dump($GLOBALS['obs']);
echo '</pre>';
?>
</body>
</html>
?>
LiveUser:Example1 (lsmith)
Wed, 21 Jun 2006, 23:26
[ Links | Source | History | RSS ]

This site powered by YaWiki 0.22 beta.