Skip to content
Snippets Groups Projects
ShibAuthPlugin.php 13.5 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
<?php

/**
 * Version 1.2.3 (Works out of box with MW 1.7 or above)
 *
 * Authentication Plugin for Shibboleth (http://shibboleth.internet2.edu)
 * Derived from AuthPlugin.php
 * Much of the commenting comes straight from AuthPlugin.php
 *
 * Portions Copyright 2006, 2007 Regents of the University of California.
 * Portions Copyright 2007, 2008 Steven Langenaken
 * Released under the GNU General Public License
 *
 * Documentation at http://www.mediawiki.org/wiki/Extension:Shibboleth_Authentication
 * Project IRC Channel: #sdcolleges on irc.freenode.net
 *
 * Extension Maintainer:
 *      * Steven Langenaken - Added assertion support, more robust https checking, bugfixes for lazy auth, ShibUpdateUser hook
 * Extension Developers:
 *      * D.J. Capelis - Developed initial version of the extension
 */

require_once('AuthPlugin.php');

class ShibAuthPlugin extends AuthPlugin {
        var $existingUser = false;

        /**
         * Check whether there exists a user account with the given name.
         * The name will be normalized to MediaWiki's requirements, so
         * you might need to munge it (for instance, for lowercase initial
         * letters).
         *
         * @param string $username
         * @return bool
         * @access public
         */
        function userExists( $username ) {
                return true;
        }


        /**
         * Check if a username+password pair is a valid login.
         * The name will be normalized to MediaWiki's requirements, so
         * you might need to munge it (for instance, for lowercase initial
         * letters).
         *
         * @param string $username
         * @param string $password
         * @return bool
         * @access public
         */
        function authenticate( $username, $password) {
                global $shib_UN;

                return $username == $shib_UN;
        }

        /**
         * Modify options in the login template.
         *
         * @param UserLoginTemplate $template
         * @access public
         */
        function modifyUITemplate( &$template ) {
                $template->set( 'usedomain', false );
        }

        /**
         * Set the domain this plugin is supposed to use when authenticating.
         *
         * @param string $domain
         * @access public
         */
        function setDomain( $domain ) {
                $this->domain = $domain;
        }

        /**
         * Check to see if the specific domain is a valid domain.
         *
         * @param string $domain
         * @return bool
         * @access public
         */
        function validDomain( $domain ) {
                return true;
        }

        /**
         * When a user logs in, optionally fill in preferences and such.
         * For instance, you might pull the email address or real name from the
         * external user database.
         *
         * The User object is passed by reference so it can be modified; don't
         * forget the & on your function declaration.
         *
         * @param User $user
         * @access public
         */
        function updateUser( &$user ) {
                wfRunHooks('ShibUpdateUser', array($this->existingUser, $user));

                //For security, set password to a non-existant hash.
                if ($user->mPassword != "nologin"){
                        $user->mPassword = "nologin";
                }

                $user->setOption('rememberpassword', 0);
                $user->saveSettings();
                return true;
        }


        /**
         * Return true if the wiki should create a new local account automatically
         * when asked to login a user who doesn't exist locally but does in the
         * external auth database.
         *
         * If you don't automatically create accounts, you must still create
         * accounts in some way. It's not possible to authenticate without
         * a local account.
         *
         * This is just a question, and shouldn't perform any actions.
         *
         * @return bool
         * @access public
         */
        function autoCreate() {
                return true;
        }

        /**
         * Can users change their passwords?
         *
         * @return bool
         */
        function allowPasswordChange() {
                global $shib_pretend;

                return $shib_pretend;

        }

        /**
         * Set the given password in the authentication database.
         * Return true if successful.
         *
         * @param string $password
         * @return bool
         * @access public
         */
        function setPassword( $password ) {
                global $shib_pretend;

                return $shib_pretend;
        }

        /**
         * Update user information in the external authentication database.
         * Return true if successful.
         *
         * @param User $user
         * @return bool
         * @access public
         */
        function updateExternalDB( $user ) {
                //Not really, but wiki thinks we did...
                return true;
        }

        /**
         * Check to see if external accounts can be created.
         * Return true if external accounts can be created.
         * @return bool
         * @access public
         */
        function canCreateAccounts() {
                return false;
        }

        /**
         * Add a user to the external authentication database.
         * Return true if successful.
         *
         * @param User $user
         * @param string $password
         * @return bool
         * @access public
         */
        function addUser( $user, $password ) {
                return false;
        }


        /**
         * Return true to prevent logins that don't authenticate here from being
         * checked against the local database's password fields.
         *
         * This is just a question, and shouldn't perform any actions.
         *
         * @return bool
         * @access public
         */
        function strict() {
                return false;
        }

        /**
         * When creating a user account, optionally fill in preferences and such.
         * For instance, you might pull the email address or real name from the
         * external user database.
         *
         * The User object is passed by reference so it can be modified; don't
         * forget the & on your function declaration.
         *
         * @param User $user
         * @access public
         */
        function initUser( &$user, $autocreate ) {
                $this->updateUser($user);
        }

        /**
         * If you want to munge the case of an account name before the final
         * check, now is your chance.
         */
        function getCanonicalName( $username ) {
                return $username;
        }
}

function ShibGetAuthHook() {
        global $wgVersion;
        if ($wgVersion >= "1.13") {
                return 'UserLoadFromSession';
        } else {
                return 'AutoAuthenticate';
        }
}
/*
 * End of AuthPlugin Code, beginning of hook code and auth functions
 */

$wgExtensionFunctions[] = 'SetupShibAuth';
$wgExtensionCredits['other'][] = array(
                        'name' => 'Shibboleth Authentication',
                        'version' => '1.2.3',
                        'author' => "Regents of the University of California, Steven Langenaken",
                        'url' => "http://www.mediawiki.org/wiki/Extension:Shibboleth_Authentication",
                        'description' => "Allows logging in through Shibboleth",
                        );

function SetupShibAuth()
{
        global $shib_UN;
        global $wgHooks;
        global $wgAuth;
        global $wgCookieExpiration;

        if($shib_UN != null){
                $wgCookieExpiration = -3600;
                $wgHooks[ShibGetAuthHook()][] = "Shib".ShibGetAuthHook();
                $wgHooks['PersonalUrls'][] = 'ShibActive'; /* Disallow logout link */
                $wgAuth = new ShibAuthPlugin();
        } else {
                $wgHooks['PersonalUrls'][] = 'ShibLinkAdd';
        }
}

/* Add login link */
function ShibLinkAdd(&$personal_urls, $title)
{
        global $shib_WAYF, $shib_LoginHint, $shib_Https, $shib_AssertionConsumerServiceURL;
        global $shib_WAYFStyle;
        if (! isset($shib_AssertionConsumerServiceURL) || $shib_AssertionConsumerServiceURL == '')
                $shib_AssertionConsumerServiceURL = "/Shibboleth.sso";
        if (! isset($shib_Https))
                $shib_Https = false;
        if (! isset($shib_WAYFStyle))
                $shib_WAYFStyle = 'WAYF';
        if ($shib_WAYFStyle == 'WAYF')
                $shib_ConsumerPrefix = 'WAYF/';
        else
                $shib_ConsumerPrefix = '';
        $pageurl = $title->getLocalUrl();
        if (! isset($shib_LoginHint))
                $shib_LoginHint = "Login via Single Sign-on";

        $personal_urls['SSOlogin'] = array(
                        'text' => $shib_LoginHint,
                        'href' => ($shib_Https ? 'https' :  'http') .'://' . $_SERVER['HTTP_HOST'] .
                        $shib_AssertionConsumerServiceURL . "/" . $shib_ConsumerPrefix . $shib_WAYF .
                        '?target=' . (isset($_SERVER['HTTPS']) ? 'https' : 'http') .
                        '://' . $_SERVER['HTTP_HOST'] . $pageurl, );
        return true;
}

/* Kill logout link */
function ShibActive(&$personal_urls, $title)
{
        global $shib_logout;
        global $shib_RN;
        global $shib_map_info;

        if($shib_logout == null)
                $personal_urls['logout'] = null;
        else
                $personal_urls['logout']['href'] = $shib_logout;

        if ($shib_RN && $shib_map_info)
                $personal_urls['userpage']['text'] = $shib_RN;

        return true;
}

function ShibAutoAuthenticate(&$user) {
        ShibUserLoadFromSession($user, true);
}
/* Tries to be magical about when to log in users and when not to. */
function ShibUserLoadFromSession($user, &$result)
{
        global $wgContLang;
        global $wgAuth;
        global $shib_UN;
        global $wgHooks;
        global $shib_map_info;
        global $shib_map_info_existing;
        global $shib_pretend;

        ShibKillAA();

        //For versions of mediawiki which enjoy calling AutoAuth with null users
        if ($user === null) {
                $user = User::loadFromSession();
        }

        //They already with us?  If so, nix this function, we're good.
        if($user->isLoggedIn())
        {
                ShibBringBackAA();
                return true;
        }

        //Is the user already in the database?
        if (User::idFromName($shib_UN) != null && User::idFromName($shib_UN) != 0)
        {
                $user = User::newFromName($shib_UN);
                $user->load();
                $wgAuth->existingUser = true;
                $wgAuth->updateUser($user); //Make sure password is nologin
                $user->setupSession();
                $user->setCookies();
                return true;
        }

        //Place the hook back (Not strictly necessarily MW Ver >= 1.9)
        ShibBringBackAA();

        //Okay, kick this up a notch then...
        $user->setName($wgContLang->ucfirst($shib_UN));

        /*
         * Since we only get called when someone should be logged in, if they
         * aren't let's make that happen.  Oddly enough the way MW does all
         * this is simply to use a loginForm class that pretty much does
         * most of what you need.  Creating a loginform is a very very small
         * part of this object.
         */
        require_once('specials/SpecialUserlogin.php');

        //This section contains a silly hack for MW
        global $wgLang;
        global $wgContLang;
        global $wgRequest;
        $wgLangUnset = false;

        if(!isset($wgLang))
        {
                $wgLang = $wgContLang;
                $wgLangUnset = true;
        }

        ShibKillAA();

        //This creates our form that'll do black magic
        $lf = new LoginForm($wgRequest);

        //Place the hook back (Not strictly necessarily MW Ver >= 1.9)
        ShibBringBackAA();

        //And now we clean up our hack
        if($wgLangUnset == true)
        {
                unset($wgLang);
                unset($wgLangUnset);
        }

        //The mediawiki developers entirely broke use of this the
        //straightforward way in 1.9, so now we just lie...
        $shib_pretend = true;

        //Now we _do_ the black magic
        $lf->mRemember = false;
        $user->loadDefaults($shib_UN);
        $lf->initUser($user, true);

        //Stop pretending now
        $shib_pretend = false;

        //Finish it off
        $user->saveSettings();
        $user->setupSession();
        $user->setCookies();
        return true;
}
function ShibKillAA()
{
        global $wgHooks;
#       global $wgAuth; //looks unuseful here

        //Temporarily kill The AutoAuth Hook to prevent recursion
        foreach ($wgHooks[ShibGetAuthHook()] as $key => $value)
        {
                if($value == "Shib".ShibGetAuthHook())
                        $wgHooks[ShibGetAuthHook()][$key] = 'ShibBringBackAA';
        }
}
/* Puts the auto-auth hook back into the hooks array */
function ShibBringBackAA()
{
        global $wgHooks;
#       global $wgAuth; //looks unuseful here

        foreach ($wgHooks[ShibGetAuthHook()] as $key => $value)
        {
                if($value == 'ShibBringBackAA')
                        $wgHooks[ShibGetAuthHook()][$key] = "Shib".ShibGetAuthHook();
        }
        return true;
}
?>