Skip to content

Instantly share code, notes, and snippets.

@k-holy
Created July 28, 2011 09:44
Show Gist options
  • Save k-holy/1111302 to your computer and use it in GitHub Desktop.
Save k-holy/1111302 to your computer and use it in GitHub Desktop.
PHP OpenIDの利用サンプル
<?php
define('Auth_Yadis_CURL_OVERRIDE', '1'); // Curlは使わない
define('Auth_OpenID_RAND_SOURCE' ,
(!file_exists('/dev/urandom') || !is_readable('/dev/urandom'))
? '/dev/urandom' : null);
if (!isset($_SESSION)) {
session_start();
}
class Util {
public static function NL($data) {
return str_replace("\r", "\n", str_replace("\r\n", "\n", $data));
}
public static function H($data, $default=null, $empty=null, $null=null) {
$var = $default;
if (isset($data)) {
if (strcmp($data, '') != 0) {
$var = htmlspecialchars(self::NL($data), ENT_QUOTES, 'UTF-8');
} elseif (isset($empty)) {
$var = $empty;
}
} elseif (isset($null)) {
$var = $null;
}
return $var;
}
}
use \Util as U;
require_once "Auth/OpenID/Consumer.php";
require_once "Auth/OpenID/FileStore.php";
require_once "Auth/OpenID/SReg.php";
$IDENTIFIERS = array(
'yahoo' => 'https://me.yahoo.co.jp/',
'google' => 'https://www.google.com/accounts/o8/id',
'mixi' => 'https://mixi.jp/',
'livedoor' => 'http://livedoor.com/',
'hatena' => 'http://www.hatena.ne.jp/{username}/', // はてなはID必須っぽい
);
$scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
$trustRoot = sprintf('%s://%s:%s%s/' , $scheme,
$_SERVER['SERVER_NAME'],
$_SERVER['SERVER_PORT'],
dirname($_SERVER['PHP_SELF']));
$returnTo = sprintf('%s://%s:%s%s/open_id.php?returned=1', $scheme,
$_SERVER['SERVER_NAME'],
$_SERVER['SERVER_PORT'],
dirname($_SERVER['PHP_SELF']));
$data['identifier'] = (isset($_POST['identifier']) && strlen($_POST['identifier']) >= 1)
? $_POST['identifier'] : '';
$data['user_identifier'] = (isset($_POST['user_identifier']) && strlen($_POST['user_identifier']) >= 1)
? $_POST['user_identifier'] : '';
$data['username'] = (isset($_POST['username']) && strlen($_POST['username']) >= 1)
? $_POST['username'] : '';
$identifier = null;
if (strlen($data['user_identifier']) >= 1) {
$identifier = $data['user_identifier'];
} elseif (strlen($data['identifier']) >= 1 && isset($IDENTIFIERS[$data['identifier']])) {
$identifier = $IDENTIFIERS[$data['identifier']];
}
if (strlen($data['username']) >= 1) {
$identifier = str_replace('{username}', $data['username'], $identifier);
}
$store = new Auth_OpenID_FileStore('/tmp/_php_consumer_test');
$consumer = new Auth_OpenID_Consumer($store);
if (isset($_POST['verify']) && isset($identifier)) {
$auth_request = $consumer->begin($identifier);
if (!($auth_request instanceof Auth_OpenID_AuthRequest)) {
throw new RuntimeException(
sprintf("Authentication error; the identifier '%s' not a valid OpenID.",
$identifier));
}
$sreg_request = Auth_OpenID_SRegRequest::build(
array('nickname'), // Required
array('fullname', 'email', 'dob', 'gender', 'postcode', 'country', 'language', 'timezone') // Optional
);
if ($sreg_request instanceof Auth_OpenID_SRegRequest) {
$auth_request->addExtension($sreg_request);
}
if ($auth_request->shouldSendRedirect()) {
$redirect_url = $auth_request->redirectURL($trustRoot, $returnTo);
if (Auth_OpenID::isFailure($redirect_url)) {
throw new RuntimeException(
sprintf('Could not redirect to server: %s', $redirect_url->message));
}
header(sprintf('Location: %s', $redirect_url));
exit;
}
$form_html = $auth_request->htmlMarkup($trustRoot, $returnTo, false,
array('id' => 'openid_message'));
if (Auth_OpenID::isFailure($form_html)) {
throw new RuntimeException(
sprintf('Could not redirect to server: %s', $form_html->message));
}
print $form_html;
exit;
}
$response = (isset($_GET['returned'])) ? $consumer->complete($returnTo) : null;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex,nofollow" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<title>PHP OpenID Authentication Example</title>
<body>
<h1>PHP OpenID Authentication Example</h1>
<?php if (isset($response) && $response instanceof Auth_OpenID_ConsumerResponse) : ?>
<?php if ($response->status == Auth_OpenID_CANCEL) : ?>
<p>Verification cancelled.</p>
<?php elseif ($response->status == Auth_OpenID_FAILURE) : ?>
<p>OpenID authentication failed: <?=U::H($response->message)?></p>
<?php elseif ($response->status == Auth_OpenID_SUCCESS) : ?>
<?php
$sregResponse = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
$sregData = ($sregResponse instanceof Auth_OpenID_SRegResponse) ? $sregResponse->contents() : null;
?>
<p>You have successfully verified <?=U::H($response->getDisplayIdentifier())?> as your identity.
<?php if (isset($response->endpoint->canonicalID)) : ?>
<p>XRI CanonicalID: <?=U::H($response->endpoint->canonicalID)?></p>
<?php endif ?>
<?php if (isset($sregData) && is_array($sregData) && count($sregData) >= 1) : ?>
<ul>
<?php foreach ($sregData as $field => $value) : ?>
<li><?=U::H($field)?>:<?=U::H($value)?></li>
<?php endforeach ?>
</ul>
<?php endif ?>
<?php endif ?>
<?php endif ?>
<form method="post" action="<?=U::H($_SERVER['SCRIPT_NAME'])?>">
<p>
<select name="identifier">
<?php foreach (array_keys($IDENTIFIERS) as $name) : ?>
<option value="<?=U::H($name)?>"
<?php echo (isset($data['identifier']) && $data['identifier'] == $name)
? ' selected="selected"' : ''?>><?=U::H($name)?></option>
<?php endforeach ?>
</select>
<div id="username_area" style="display:none;">
UserId <input type="text" id="username" name="username" value="<?=U::H($data['username'])?>"/>
</div>
<script type="text/javascript"><!--
$(document).ready(function(){
$('select[name="identifier"]').change(function() {
if ($('select[name="identifier"] option:selected').val() == 'hatena') {
$('#username_area').show('fast');
} else {
$('#username_area').hide('fast');
}
});
});
// -->
</script>
</p>
<p>Other Identity URL:<input type="text" name="user_identifier" value="<?=U::H($data['user_identifier'])?>" /></p>
<p><input type="submit" name="verify" value="Verify" /></p>
</form>
</body>
</html>
@k-holy
Copy link
Author

k-holy commented Jul 29, 2011

jQueryの勉強も兼ねて、はてなID入力欄を追加してシュインシュインさせてみた

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment