an authentication class
Posted: Wed Feb 02, 2005 10:01 am
I'm trying to build a (flexible) class for authentication in PHP5.
If you have any suggestions or hints or whatever, feel free to share them with me so i can improve the code
If you have any suggestions or hints or whatever, feel free to share them with me so i can improve the code
Code: Select all
<?php
// +---------------------------------------------------------------------------
// | Author: Tim Van Wassenhove <timvw@users.sourceforge.net
// |
// | Secure authentication mechanism (preventing session fixation).
// +---------------------------------------------------------------------------
// start session if it is'nt already there
if (!isset($_SESSION))
{
session_start();
}
abstract class Authentication
{
private $name;
private $credentials;
/**
* Method to validate credentials.
* @param $credentials an array with name=value credentials
* @return true if valid
*/
abstract protected function isValidCredentials($credentials);
/**
* Default constructor.
* @param $name the name of this authentication object.
*/
public __construct($name = null)
{
if (is_null($name))
{
$name = md5(uniqid());
}
$this->name = $name;
$this->credentials = null;
}
/**
* Get the registered credentials.
* @return the credentials, null if they don't exist
*/
public function getCredentials()
{
return $this->credentials;
}
/**
* Login with the given credentials.
* @param $credentials an array with name=value credentials
* @return true if success
*/
public function login($credentials)
{
session_regenerate_id();
if (isValidCredentials($credentials))
{
$this->credentials = $credentials;
$_SESSIONї$this->name . 'authenticated'] = true;
$_SESSIONї$this->name . 'fingerprint'] = $this->getFingerprint();
return true;
}
return false;
}
// logout
function logout()
{
$this->credentials = null;
session_regenerate_id();
$_SESSIONї$this->name . 'authenticated'] = false;
}
// test if user is authenticated
function isAuthenticated()
{
if (array_key_exists($this->name . 'authenticated', $_SESSION)) && $_SESSIONї$this->name . 'authenticated'] === true)
{
if ($_SESSIONї$this->name . 'fingerprint'] == $this->getFingerprint())
{
session_regenerate_id();
$_SESSIONї$this->name . 'fingerprint'] = $this->getFingerprint();
return true;
}
}
return false;
}
// get the fingerprint of the user
function getFingerprint()
{
$fingerprint = 'secretstring';
if (array_key_exists('HTTP_USER_AGENT', $_SERVER))
{
$fingerprint .= $_SERVERї'HTTP_USER_AGENT'];
}
if (array_key_exists('HTTP_ACCEPT_CHARSET', $_SERVER))
{
$fingerprint .= $_SERVERї'HTTP_ACCEPT_CHARSET'];
}
$fingerprint .= session_id();
$fingerpring = md5($fingerprint);
return $fingerprint;
}
}
?>