MaharaAuthPlugin.php 11.9 KB
Newer Older
Brett Wilkins's avatar
Brett Wilkins committed
1 2
<?php
/**
Brett Wilkins's avatar
Brett Wilkins committed
3
 *Mediawiki Authentication Plugin for Mahara
4
 *Copyright (C) 2004 Brion Vibber <brion@pobox.com>
Brett Wilkins's avatar
Brett Wilkins committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *Copyright (C) 2010, 2011 Catalyst IT (http://www.catalyst.net.nz)
 *
 *This program is free software; you can redistribute it and/or
 *modify it under the terms of the GNU General Public License
 *as published by the Free Software Foundation; either version 2
 *of the License, or (at your option) any later version.
 *
 *This program is distributed in the hope that it will be useful,
 *but WITHOUT ANY WARRANTY; without even the implied warranty of
 *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *GNU General Public License for more details.
 *
 *You should have received a copy of the GNU General Public License
 *along with this program; if not, write to the Free Software
 *Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/
21
require_once('includes/AuthPlugin.php');
Brett Wilkins's avatar
Brett Wilkins committed
22

23 24 25 26 27 28 29
$wgExtensionCredits['other'][] = array(
    'name' => 'Mahara Authentication Plugin',
    'author' => 'Brett Wilkins',
    'url' => 'http://gitorious.org/mahara-contrib/mediawiki-auth-mahara',
    'description' => 'Authenticates against users in the Mahara database'
    );

30
class MaharaAuthPlugin extends AuthPlugin {
Brett Wilkins's avatar
Brett Wilkins committed
31 32 33
	/**
	 * Check whether there exists a user account with the given name.
	 * The name will be normalized to MediaWiki's requirements, so
34
     * you might need to munge it (for instance, for lowercase initial
Brett Wilkins's avatar
Brett Wilkins committed
35 36 37 38 39 40
	 * letters).
	 *
	 * @param $username String: username.
	 * @return bool
	 */

41 42 43 44 45 46
	var $dbname;
	var $host;
	var $prefix;
	var $dbtype;
	var $dbuser;
	var $dbpass;
47
	var $passwordsaltmain;
Brett Wilkins's avatar
Brett Wilkins committed
48

49
    public function __construct($dbname, $host='localhost',$dbtype='', $user='', $password='', $prefix='', $passwordsaltmain='') {
Brett Wilkins's avatar
Brett Wilkins committed
50 51 52
        $this->dbname = $dbname;
        $this->host = $host;
        $this->prefix = $prefix;
53
	    $this->dbtype = $dbtype;
Brett Wilkins's avatar
Brett Wilkins committed
54 55
        $this->dbuser = $user;
        $this->dbpass = $password;
56
        $this->passwordsaltmain = $passwordsaltmain;
Brett Wilkins's avatar
Brett Wilkins committed
57 58 59
    }

	public function userExists( $username ) {
60
        $username = strtolower($username);
61
        $db = $this->getDatabase();
62 63
        // This will only work for the "internal" auth plugin, where the user's password is stored locally.
        $sql = "SELECT username FROM ".$this->prefix."usr u inner join {$this->prefix}auth_instance ai on u.authinstance=ai.id where ai.authname='internal' and LOWER(username) = '".$username."'";
Brett Wilkins's avatar
Brett Wilkins committed
64
        $res = $db->query($sql);
65
        $val = $db->fetchObject($res);
Brett Wilkins's avatar
Brett Wilkins committed
66
        $db->close();
67
        if (!empty($val)) {
Brett Wilkins's avatar
Brett Wilkins committed
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
            return true;
        }
		return false;
	}

	/**
	 * 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 $username String: username.
	 * @param $password String: user password.
	 * @return bool
	 */
	public function authenticate( $username, $password ) {
84 85
	$username = strtolower($username);
        $db = $this->getDatabase();
86
	    $sql = "SELECT username, password, salt FROM ".$this->prefix."usr where LOWER(username) = '".$username."' and deleted != 1";
87
        $res = $db->query($sql);
88
        $val = $db->fetchObject($res);
89
        $db->close();
90
        if (!empty($val)) {
91
            return $this->_validate_password($password, $val->password, $val->salt);
92
        }
Brett Wilkins's avatar
Brett Wilkins committed
93 94 95
		return false;
	}

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
    /**
     * Given a password that the user has sent, the password we have for them
     * and the salt we have, see if the password they sent is correct.
     *
     * @param string $theysent The password the user sent
     * @param string $wehave   The salted and hashed password we have in the database for them
     * @param string $salt     The salt we have.
     * @returns int     0 means not validated, 1 means validated, 2 means validated but needs updating
     */
    private function _validate_password($theysent, $wehave, $salt) {

        if ($salt == '*') {
            // This is a special salt that means this user simply CAN'T log in.
            // It is used on the root user (id=0)
            return false;
        }

        if (empty($wehave)) {
            // This means the user has not been set up completely yet
            // Common cause is that still in registration phase
            return false;
        }

        $sitesalt = $this->passwordsaltmain;
        $bcrypt = substr($wehave, 0, 4) == '$2a$';
        if ($bcrypt) {
            $alg = substr($wehave, 0, 7);
            $hash = $this->encrypt_password($theysent, $salt, $alg, $sitesalt);
        }
        else {
            $alg = substr($wehave, 0, 3);
            $hash = $this->encrypt_password($theysent, $salt, $alg, $sitesalt);
        }
        if ($hash == $wehave) {
            return true;
        }
        // See http://docs.moodle.org/20/en/Password_salting#Changing_the_salt
        if (!empty($sitesalt)) {
            // There is a sitesalt set, try without it, and update if passes
            $hash = $this->encrypt_password($theysent, $salt, $alg, '');
            if ($hash == $wehave) {
                return 2;
            }
        }
        // Nothing works, fail
        return 0;
    }

   /**
    * Given a password and an optional salt, encrypt the given password.
    *
    * Passwords are stored in SHA1 form.
    *
    * @param string $password The password to encrypt
    * @param string $salt     The salt to use to encrypt the password
    * @param string $alg      The algorithm to use, defaults to $6$ which is SHA512
    * @param string $sitesalt A salt to combine with the user's salt to add an extra layer or salting
    * @todo salt mandatory
    */
    private function encrypt_password($password, $salt='', $alg='$6$', $sitesalt='') {
        if ($salt == '') {
            $salt = substr(md5(rand(1000000, 9999999)), 2, 8);
        }
        if ($alg == '$6$') { // $6$ is the identifier for the SHA512 algorithm
            // Return a hash which is sha512(originalHash, salt), where original is sha1(salt + password)
            $password = sha1($salt . $password);
            // Generate a salt based on a supplied salt and the passwordsaltmain
            $fullsalt = substr(md5($sitesalt . $salt), 0, 16); // SHA512 expects 16 chars of salt
        }
        else { // This is most likely bcrypt $2a$, but any other algorithm can take up to 22 chars of salt
            // Generate a salt based on a supplied salt and the passwordsaltmain
            $fullsalt = substr(md5($sitesalt . $salt), 0, 22); // bcrypt expects 22 chars of salt
        }
        $hash = crypt($password, $alg . $fullsalt);
        // Strip out the computed salt
        // We strip out the salt hide the computed salt (in case the sitesalt was used which isn't in the database)
        $hash = substr($hash, 0, strlen($alg)) . substr($hash, strlen($alg)+strlen($fullsalt));
        return $hash;
    }

    /**
Brett Wilkins's avatar
Brett Wilkins committed
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
	 * Modify options in the login template.
	 *
	 * @param $template UserLoginTemplate object.
	 */
	public function modifyUITemplate( &$template ) {
		# Override this!
		$template->set( 'usedomain', false );
	}

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

	/**
	 * Check to see if the specific domain is a valid domain.
	 *
	 * @param $domain String: authentication domain.
	 * @return bool
	 */
	public function validDomain( $domain ) {
		# Override this!
		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
	 */
	public function updateUser( &$user ) {
217

218
        $db = $this->getDatabase();
219
	    $sql = "SELECT * FROM ".$this->prefix."usr where LOWER(username) = LOWER('".$user->mName."')";
220
        $res = $db->query($sql);
221
        $val = $db->fetchObject($res);
222 223
        $db->close();
		$user->setOption('nickname',$val->username);
224 225
		$user->setEmail($val->email);
		$user->setRealName($val->firstname.' '.$val->lastname);
226 227
        if ($val->admin == 1) {
            $user->addGroup('sysop');
228
        } else if (in_array('sysop',$user->getGroups())) {
229 230
            $user->removeGroup('sysop');
        }
Brett Wilkins's avatar
Brett Wilkins committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
		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
	 */
	public function autoCreate() {
249
		return true;
Brett Wilkins's avatar
Brett Wilkins committed
250 251 252 253 254 255 256 257
	}

	/**
	 * Can users change their passwords?
	 *
	 * @return bool
	 */
	public function allowPasswordChange() {
258
		return false;
Brett Wilkins's avatar
Brett Wilkins committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
	}

	/**
	 * Set the given password in the authentication database.
	 * As a special case, the password may be set to null to request
	 * locking the password to an unusable value, with the expectation
	 * that it will be set later through a mail reset or other method.
	 *
	 * Return true if successful.
	 *
	 * @param $user User object.
	 * @param $password String: password.
	 * @return bool
	 */
	public function setPassword( $user, $password ) {
274
		return false;
Brett Wilkins's avatar
Brett Wilkins committed
275 276 277 278 279 280 281 282 283 284
	}

	/**
	 * Update user information in the external authentication database.
	 * Return true if successful.
	 *
	 * @param $user User object.
	 * @return bool
	 */
	public function updateExternalDB( $user ) {
285
		return false;
Brett Wilkins's avatar
Brett Wilkins committed
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
	}

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

	/**
	 * Add a user to the external authentication database.
	 * Return true if successful.
	 *
	 * @param User $user - only the name should be assumed valid at this point
	 * @param string $password
	 * @param string $email
	 * @param string $realname
	 * @return bool
	 */
	public function addUser( $user, $password, $email='', $realname='' ) {
308
		return false;
Brett Wilkins's avatar
Brett Wilkins committed
309 310 311 312 313 314 315 316 317 318 319 320
	}


	/**
	 * 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
	 */
	public function strict() {
321
		return true;
Brett Wilkins's avatar
Brett Wilkins committed
322 323 324 325 326 327 328 329 330 331
	}

	/**
	 * Check if a user should authenticate locally if the global authentication fails.
	 * If either this or strict() returns true, local authentication is not used.
	 *
	 * @param $username String: username.
	 * @return bool
	 */
	public function strictUserAuth( $username ) {
332
		return true;
Brett Wilkins's avatar
Brett Wilkins committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346
	}

	/**
	 * 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 object.
	 * @param $autocreate bool True if user is being autocreated on login
	 */
	public function initUser( &$user, $autocreate=false ) {
347
        return $this->updateUser($user);
Brett Wilkins's avatar
Brett Wilkins committed
348 349 350 351 352 353 354 355 356
	}

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

Brett Wilkins's avatar
Brett Wilkins committed
358 359 360 361 362 363 364 365 366
	/**
	 * Get an instance of a User object
	 *
	 * @param $user User
	 * @public
	 */
	public function getUserInstance( User &$user ) {
		return new AuthPluginUser( $user );
	}
367 368 369 370 371 372 373 374 375 376 377 378 379 380

	private function getDatabase() {
		if (empty($this->dbtype)) {
			return false;
		}
		switch ($this->dbtype) {
			case 'mysql':
				return new DatabaseMysql($this->host,$this->dbuser,$this->dbpass,$this->dbname);
			case 'postgres':
			default:
				return new DatabasePostgres($this->host,$this->dbuser,$this->dbpass,$this->dbname);
		}
		return false;
	}
Brett Wilkins's avatar
Brett Wilkins committed
381
}