Extension:Auth viaMySQL

From MediaWiki.org

Jump to: navigation, search

             

Manual on MediaWiki Extensions
List of MediaWiki Extensions
Crystal Clear action run.png
Auth_viaMySQL

Release status: stable

Implementation  User identity
Description Auto-authenticates users using MySQL database
Author(s)  John Derby Russell (DerbyRussellTalk)
Last Version  1.1 (02-08-2009)
MediaWiki  1.14.0rc1
License GPL
Download no link

check usage (experimental)

Contents

[edit] What can this extension do?

This extension will automatically Authenticate (Login) a user with data provided from an existing MySQL database. Another web page or program can be used to login an existing user from that web page or program upon entry to the MediaWiki associated with that web page or program. Logout is accomplished by clearing the database global variable and associated cookie.

The Login and Create Account and the Logout url's in the Personal Tools tool box will not be shown using Auth_viaMySQL extension.

[edit] Usage

To Use this extension you need to adjust your LocalSettings.php as shown below, and create Three separate PHP files included in the code listed below in the code section of this page.

Create PHP file: MySQLActiveUser.php save to your web page directory Create PHP file: Auth_viaMySQL.php save to the MediaWiki/extension/Auth_viaMySQL directory Create PHP file: CacheTimer_viaMySQL.php save to the MediaWiki/extension/Auth_viaMySQL directory

[edit] Installation

To install this extension, add the following to LocalSettings.php:

require_once("$IP/extensions/Auth_viaMySQL/Auth_viaMySQL.php");
require_once("$IP/extensions/Auth_viaMySQL/CacheTimer_viaMySQL.php");
 
$local_var_login_time = CacheTimer_viaMySQL() ;
 
# All Page Caching Must Be Turned Off For Auth_viaMySQL to work.
# The following ensures all page caching is turned off
# Find the next line and comment out:
# $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', @filemtime( __FILE__ ) ) );

# Add the following line instead:
$wgCacheEpoch = max( $wgCacheEpoch, $local_var_login_time ) ;
 
# Dis-Allow client-side caching of pages by setting wgCachePages to false
$wgCachePages = false ;

[edit] Configuration parameters

Page caching must be turned off or else MediaWiki will cache and save the database username and the user will appear to always be logged in even if the user has logged out.

Setting wgCacheEpoch the way I have shown above will cause MediaWiki to expire the cache epoch at user log in. This way all pages get rebuilt for the new user.

Setting wgCachePages to false will cause MediaWiki to NOT cache all client side pages.

I found the settings set in this manner was the only way Auth_viaMySQL would work properly.

[edit] Code

Copy this first section of code to a file called MediaWiki/extensions/Auth_viaMySQL/Auth_viaMySQL.php

<?php
/**
 * Auth_viaMySQL MediaWiki extension MediaWiki version 1.14.0rc1
 *
 * @file
 * @ingroup Extensions
 * @version 1.0
 * @author John Derby Russell
 * @link http://www.mediawiki.org/w/index.php/Extension:Auth_viaMySQL
 */
 
# Not a valid entry point, skip unless MEDIAWIKI is defined
if( !defined( 'MEDIAWIKI' ) )
{
	echo "Auth_viaMySQL extension";
	die();
}
 
// Extension credits that will show up on Special:Version
$wgExtensionCredits['other'][] = array(
      'name' => 'MySQL Auto Authentication -> Auth_viaMySQL',
      'version' => '1.0',
      'author' => 'John Derby Russell',
      'url' => 'http://www.mediawiki.org/w/index.php/Extension:Auth_viaMySQL',
      'description' => 'Auto-authenticates users using MySQL database',
);
 
/**
 *
 * MySQL Login Database Integration
 *
 */
 
require_once('../MySQLActiveUser.php') ;
 
$wgHooks['UserLoadFromSession'][] = 'Auth_viaMySQL';
 
// Kill logout url
$wgHooks['PersonalUrls'][] = 'PersonalUrls_killLogout'; /* Disallow logout link */
 
function Auth_viaMySQL( &$user, &$result ) {
    global $MySQLActiveUserData;
    $MySQLActiveUserData->distribute_cookie_data() ;
 
    wfSetupSession();
 
    /**
     * A lot of this is from User::newFromName
     */
    // Force usernames to capital
    global $wgContLang;
 
    $name = $wgContLang->ucfirst( $MySQLActiveUserData->active_user_name );
 
    // Clean up name according to title rules
    $t = Title::newFromText( $name );
    if( is_null( $t ) ) {
        return(true) ;
    }
 
    $canonicalName = $t->getText();
 
    if( !User::isValidUserName( $canonicalName ) ) {
        return(true) ;
    }
 
    $user->setName( $canonicalName );
 
    $user_id_fromMW_DB = $user->idFromName( $MySQLActiveUserData->active_user_name ) ;
 
    $user->setId( $user_id_fromMW_DB );
    if ( $user->getID() == 0 ) {
        /**
        * A lot of this is from LoginForm::initUser
        * LoginForm in in the file called SpecialUserLogin.php line 342 (version 1.14.0rc1)
        */
        $canonicalName = $t->getText();
        $user->setName( $canonicalName );
        $user->addToDatabase();
 
        $user->setEmail( $MySQLActiveUserData->active_user_email );
        $user->setRealName( '' );
        $user->setToken();
 
        $user->saveSettings();
    } else {
        if ( !$user->loadFromDatabase() ) {
            // Can't load from ID, user is anonymous
            return(true) ;
        }
        $user->saveToCache();
    }
 
    $result = 1; // This causes the rest of the authentication process to be skipped.
    return(false);   // As should this, according to the internal error report:
}
 
// Kill logout url
function PersonalUrls_killLogout(&$personal_urls, $title) {
    $personal_urls['logout'] = null ;
    $personal_urls['login'] = null ;
    $personal_urls['anonlogin'] = null ;
    return true ;
}

Save this next piece of code to a file called MediaWiki/extensions/Auth_viaMySQL/CacheTimer_viaMySQL.php

<?php
/**
 * CacheTimer_viaMySQL MediaWiki extension
 *
 * @file
 * @ingroup Extensions
 * @version 1.0
 * @author John Derby Russell
 * @link http://www.mediawiki.org/w/index.php/Extension:Auth_viaMySQL
 */
 
// Extension credits that will show up on Special:Version
$wgExtensionCredits['other'][] = array(
      'name' => 'MySQL Cache Timer',
      'version' => '1.0',
      'author' => 'John Derby Russell',
      'url' => 'http://www.mediawiki.org/w/index.php/Extension:Auth_viaMySQL',
      'description' => 'Tells Wiki when to regenerate client cache for users',
);
 
require_once('../MySQLActiveUser.php') ;
 
/**
 *
 * The MySQL cache epoche timer is for when to rebuild the cache stored on the client side.
 * This is ussually done at login.
 *
 */
 
function CacheTimer_viaMySQL( ) {
    global $MySQLActiveUserData ;
    $MySQLActiveUserData->distribute_cookie_data() ;
 
    return $MySQLActiveUserData->active_user_login_time ;
}

Save this next piece of code to a file called ../MediaWiki/MySQLActiveUser.php

Note: This file is to be stored in the directory just BEFORE the MediaWiki installation directory!

<?php
 
class MySQLActiveUser
{
    var $active_user_id ;
    var $active_user_name ;
    var $active_user_password;
    var $active_user_email ;
    var $active_user_login_time ;
 
    function MySQLActiveUser()  {
    }
 
    function set_cookie($username, $user_id, $password_hash, $user_email, $login_time) {
        setcookie("mysql_active_user",
                  serialize(array($username, $user_id, $password_hash, $user_email, $login_time)), time()+60*60*24*100, "/") ;
 
        $this->active_user_name = $username ;
        $this->active_user_id = $user_id ;
        $this->active_user_password = $password_hash ;
        $this->active_user_email = $user_email ;
        $this->active_user_login_time = $login_time ;
    }
 
    function clear_cookie() {
        $this->active_user_name = "" ;
        $this->active_user_id = 0 ;
        $this->active_user_password = 0 ;
        $this->active_user_email = "" ;
        $this->active_user_login_time = 0 ;
        setcookie("mysql_active_user",
                serialize(array("", "", "", "")), time()-60*60*24*100, "/") ;
    }
 
    function distribute_cookie_data() {
        $mysql_cookie_name = "mysql_active_user" ;
 
        if (isset($_COOKIE[$mysql_cookie_name]))
                list($this->active_user_name,
                     $this->active_user_id,
                     $this->active_user_password,
                     $this->active_user_email,
                     $this->active_user_login_time) = @unserialize($_COOKIE[$mysql_cookie_name]);
    }
}
 
$MySQLActiveUserData = new MySQLActiveUser();

In your login scripts for your web page add something like:

    require_once('MySQLActiveUser.php');
    global $MySQLActiveUserData ;
    global $DBConnection ;
 
    $userName = $_POST['user'] ;
    $command = "SELECT * FROM users WHERE Name='".$userName."';" ;
    $result = mysql_query($command, $DBConnection);
    $account = mysql_fetch_assoc($result) ;
    if ($account)
    {
        $current_mw_timecode = gmdate( 'YmdHis' ) ;
        $MySQLActiveUserData->set_cookie($account['Name'],
                                         $account['id'],
                                         $account['password'],
                                         $account['email'],
                                         $current_mw_timecode) ;
    }

The next step is very important if you also require LOGOUT!

In your logout scripts for your web page add something exactly like:

    require_once('MySQLActiveUser.php');
    global $MySQLActiveUserData ;
 
    // Add this line AFTER all other cookies
    // have been cleared for your web page
    $MySQLActiveUserData->clear_cookie() ;

Note: When I refer to MediaWiki as a directory I mean the default directory you have installed MediaWiki to.

[edit] See also

Extension:PunBB Authentication, Extension:Siteminder Authentication