It's better when it's simple

User Tools

Site Tools


Working Example of trustExternal()

After spending way too much time trying to make this work, I finally figured it out. Here are the details you need to know that the docs don't tell you:

  1. The trustExternal method will be called on every page load. However, the $user and $pass parameters are only present when the user first logs in. On all subsequent page loads, they will be empty.
  2. You must fill in the $USERINFO array on every page load

So my solution is to first check the $_SESSION for the previous login. If found, fill the $USERINFO array and return true. Only if this is not found, do we go the database to look for a login.

Here is my complete solution. This example checks a mongodb database, but you should be able to easily change this to use any other datastore.

class auth_mongodb extends auth_basic {
	var $connection = null;
	function __construct() {
		global $config_cascade;
		global $connection;
		$this->cando['external'] = true;
		$this->cando['logout'] = true;
		$connection = new Mongo("server_ip");
	function trustExternal($user, $pass, $sticky = false) {
		global $USERINFO;
		global $conf;
		global $connection;
		$sticky ? $sticky = true : $sticky = false; //sanity check
		if (!empty($_SESSION[DOKU_COOKIE]['auth']['info'])) {
			$USERINFO['name'] = $_SESSION[DOKU_COOKIE]['auth']['info']['name'];
			$USERINFO['mail'] = $_SESSION[DOKU_COOKIE]['auth']['info']['mail'];
			$USERINFO['grps'] = $_SESSION[DOKU_COOKIE]['auth']['info']['grps'];
			$_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
			return true;
		if (!empty($user)) {
			// do the checking here
			$collection = $connection->DatabaseName->admins;
			$login = $collection->findOne(array('name' => $user));
			if ($login == null) return false;
			if ($login['password'] != sha1($login['_id'] . $pass)) {
				msg('Incorrect username or password.');
				return false;
			// set the globals if authed
			$USERINFO['name'] = $login['name'];
			$USERINFO['mail'] = $login['email'];
			$USERINFO['grps'] = $login['name'] == 'Admin' ? array('admin','user'): array( 'user');
			$_SERVER['REMOTE_USER'] = $login['name'];
			$_SESSION[DOKU_COOKIE]['auth']['user'] = $login['name'];
			$_SESSION[DOKU_COOKIE]['auth']['mail'] = $login['email'];
			$_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
			$_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
			return true;
		} else {
			return false;
devel/working_example_of_trustexternal.txt · Last modified: 2018-08-01 12:14 by java4life

Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 4.0 International
CC Attribution-Share Alike 4.0 International Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki