Gallery:LDAP认证

来自站长百科
跳转至: 导航、​ 搜索

Gallery2中的LDAP认证 ...

安装指导[ ]

...

论坛讨论[ ]


代码实例[ ]

注意此代码是来自用户而不是Gallery开发者的。这是我注解的版本,应该能很好地为我们所使用。我认为这不会太难的 --Jkuter 2007年11月27日,06:25 (PST)

使用ldap认证的index.php嵌入脚本[ ]

  • 此代码是针对无密码登入模式的
  • SESSION在logout.inc中被unset
  • login.php为另一个input发布至index.php的小文件
<?php
// look for a user id in the session, if its not there start the session so we can make one
if (!isset($_SESSION['emAppUserId'])) {
	session_name('GalleryOnInside'); // Choose session name
	session_set_cookie_params(1209600);
	session_start(); // Initialize a session
}
// triggers embed classes for gallery so the below will work
require_once('embed.php');

// pull in gallery content and trigger user functions
$data = runGallery();

// set page title
$data['title'] = (isset($data['title']) && !empty($data['title'])) ? $data['title'] : 'Gallery';
//set up page html
if (isset($data['bodyHtml'])) {
	print <<<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>{$data['title']}</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
{$data['javascript']}
{$data['css']}
</head>

<body>
{$data['bodyHtml']}
</body>
</html>
EOF;
}
// Close Gallery Connection
GalleryEmbed::done();

function runGallery() {
	// required configuration of embed vars	
	$embedUri = '/phpapps/gallery2/index.php';
	$g2Uri = '/phpapps/gallery2/main.php';
	$loginRedirect = '/phpapps/gallery2/login.php';
	// see if this is an initial login and set username
	$username = isset($_POST['username']) ? $_POST['username'] : "";
	if ($username != "") {
		// try and authenticate posted name
		$auth = authenticateLogin($username);
		if ($auth['ErrorCode'] == "Username and Password validated") {
			//set config vars from LDAP
			$_SESSION['emAppUserId'] = $auth['uid'];
			$emAppUserLogin = $auth['cn'];
			$emAppUserName = $auth['fullname'];
			$emAppUserEmail = $auth['email'];
		} else {
			die('Authentication Failed: ' . $auth['ErrorCode']);
		}
	}

	if (isset($_SESSION['emAppUserId'])) {
		// if user is logged in, set user ID to emApp's session user_id
		$emAppUserId = $_SESSION['emAppUserId'];
	} else {
		// if anonymous user, set g2 activeUser to ''
		$emAppUserId = '';
	}
	
	// actually get gallery going passing all needed config<br> 
	$ret = GalleryEmbed::init(array('embedUri' => $embedUri, 'g2Uri' => $g2Uri, 'fullInit' => true, 'loginRedirect' =><br>  $loginRedirect, 'activeUserId' => $emAppUserId));

	// Display login link with our credentials from $loginRedirect
	GalleryCapabilities::set('login', true);

	if ($ret) {
		// Did we get an error because the user doesn't exist in g2 yet?<br> 
		$ret2 = GalleryEmbed::isExternalIdMapped($emAppUserId, 'GalleryUser');<br> 
		if ($ret2 && $ret2->getErrorCode() & ERROR_MISSING_OBJECT) {<br> 
			// The user does not exist in G2 yet. Create in now on-the-fly<br> 
			$ret = GalleryEmbed::createUser($emAppUserId, array ( 'username' => $emAppUserLogin, 'email' =><br> $emAppUserEmail, 'fullname' => $emAppUserName));<br> 
			if ($ret) {<br> 
				// An error during user creation. Not good, print an error or do whatever is appropriate<br> 
				print "An error occurred during the on-the-fly user creation <br>";
				print $ret->getAsHtml();<br> 
				exit;<br> 
			}
		} else {
			// The error we got wasn't due to a missing user, it was a real error
			if ($ret2) {
				print "An error occurred while checking if a user already exists<br>";
				print $ret2->getAsHtml();
			}
			print "An error occurred while trying to initialize G2<br>";
			print $ret->getAsHtml();
			exit;
		}
	}

	// At this point we know that either the user either existed already before or that it was just created
	$g2moddata = GalleryEmbed::handleRequest();

	// show error message if isDone is not defined<br> 
	if (!isset($g2moddata['isDone'])) {
		$data['bodyHtml'] = 'isDone is not defined, something very bad must have happened.';<br> 
		return $data;
	}

	// exit if it was an immediate view / request (G2 already outputted some data)<br> 
	if ($g2moddata['isDone']) {<br> 
		exit;
	}

	// put the body html
	$data['bodyHtml'] = isset($g2moddata['bodyHtml']) ? $g2moddata['bodyHtml'] : '';<br> 

	// get the page title, javascript and css links from the <head> html from G2<br> 
	$title = ''; $javascript = array();	$css = array();<br> 

	if (isset($g2moddata['headHtml'])) {
		list($data['title'], $css, $javascript) = GalleryEmbed::parseHead($g2moddata['headHtml']);<br> 
		$data['headHtml'] = $g2moddata['headHtml'];
	}


	// Add G2 javascript
	$data['javascript'] = '';
	if (!empty($javascript)) {
		foreach ($javascript as $script) {
			$data['javascript'] .= "\n".$script;
		}
	}

	// Add G2 css
	$data['css'] = '';
	if (!empty($css)) {
		foreach ($css as $style) {
			$data['css'] .= "\n".$style;
		}
	}

	return $data;
}

function authenticateLogin($username) {
	// ldap config
	$server="ldap://myldap.server.com:389";
	$basedn="dc=ad,dc=domainname,dc=com";
	$filter="(&(objectclass=user)(cn=$username)(!(userAccountControl=66050))(!(objectclass=computer)))";
	// try and connect
	if (!($connect = ldap_connect($server))) {
		$loginError = 'Could not connect to LDAP server';
	} else {
		// Logged in - Override some options
		ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
		ldap_set_option($connect,LDAP_OPT_PROTOCOL_VERSION,3);
		$bind = ldap_bind($connect);
		// Search for the user to get the DN
		$sr = ldap_search($connect,$basedn,$filter);
		$info = ldap_get_entries($connect, $sr);
		// set basic user info
		$fullname=$info[0]["displayname"][0];
		$cn=$info[0]["cn"][0];
		$uid=$info[0]["uidnumber"][0];
		$email=$info[0]["userprincipalname"][0];
		$dn=$info[0]["dn"];

		// Store key user information in an array to be returned
		$result['fullname'] = $fullname;
		$result['uid'] = $uid;
		$result['cn'] = $cn;
		$result['email'] = $email;
		if ($dn != "") {
			$loginError = 'Username and Password validated';
		} else {
			$loginError = "Bind Failed for $dn";
		}
	}
	// set results of bind
	$result['ErrorCode'] = $loginError;
	
	return $result;
}
?>