<?php

$cookiedomain 
= ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;

define'COOKIE_DOMAIN'$cookiedomain );
define'COOKIE_PATH''/' );
define'COOKIE_AUTH''auth_example' );

define'SECRET_KEY''dk;l1894!851éds-fghjg4lui:è3afàzgq_f4fá.' );

class 
Authenticate {

    public function 
__construct$email$password$remember ) {
    
        
$this->authenticate$email$password$remember );
        
    }
    
    private function 
authenticate$email$password$remember ) {

        
$sql "SELECT `id`,  `password` FROM `user_table` WHERE `email` = '%s'";

        
$db Database::getInstance();
        
$result $db->getRecords sprintf $sql$db->makeSafe$email ) ) );

        if ( 
$db->getAffectedRows() == ) {

            
$user $result[0];

        } else {
            
            throw new 
AuthException"This e-mail address was not found in the database." );

        }

        require_once( 
CLASS_PATH "PasswordHash.class.php" );

        
$hasher = new PasswordHash8TRUE );

        if ( !
$hasher->CheckPassword$password$user["password"] ) ) {
            
            throw new 
AuthException"Invalid password." );
            
        }
        
        
$this->setCookie$user["id"], $remember );

    }
    
    private function 
setCookie$id$remember false ) {

        if ( 
$remember ) {

            
$expiration time() + 1209600// 14 dagen

        
} else {

            
$expiration time() + 172800// 48 uur

        
}

        
$cookie $this->generateCookie$id$expiration );

        if ( !
setcookieCOOKIE_AUTH$cookie$expirationCOOKIE_PATHCOOKIE_DOMAINfalsetrue ) ) {
        
            throw new 
AuthException"Could not set cookie." );
        
        }

    }
    
    private function 
generateCookie$id$expiration ) {

        
$key hash_hmac'md5'$id $expirationSECRET_KEY );
        
$hash hash_hmac'md5'$id $expiration$key );

        
$cookie $id '|' $expiration '|' $hash;

        return 
$cookie;

    }

    public static function 
logOut( ) {

        
setcookieCOOKIE_AUTH""time() - 1209600COOKIE_PATHCOOKIE_DOMAINfalsetrue );

    }

    public static function 
validateAuthCookie() {

        if ( empty(
$_COOKIE[COOKIE_AUTH]) )
            return 
false;

        list( 
$id$expiration$hmac ) = explode'|'$_COOKIE[COOKIE_AUTH] );

        if ( 
$expiration time() )
            return 
false;

        
$key hash_hmac'md5'$id $expirationSECRET_KEY );
        
$hash hash_hmac'md5'$id $expiration$key );

        if ( 
$hmac != $hash )
            return 
false;

        return 
true;

    }

    public static function 
getUserId() {

        list( 
$id$expiration$hmac ) = explode'|'$_COOKIE[COOKIE_AUTH] );

        return 
$id;

    }

}

class 
AuthException extends Exception {}

?>