Newer
Older
<?php
/**
* @file
* Implement OpenID Relying Party support for Drupal
*/
/**
Dries Buytaert
committed
* Implements hook_menu().
*/
function openid_menu() {
$items['openid/authenticate'] = array(
'title' => 'OpenID Login',
'page callback' => 'openid_authentication_page',
'access callback' => 'user_is_anonymous',
'type' => MENU_CALLBACK,
'file' => 'openid.pages.inc',
$items['user/login/openid'] = array(
'title' => 'OpenID',
'page callback' => 'drupal_get_form',
'page arguments' => array('openid_login_form'),
'access callback' => 'user_is_anonymous',
'type' => MENU_LOCAL_TASK,
);
$items['user/%user/openid'] = array(
'title' => 'OpenID identities',
'page callback' => 'openid_user_identities',
'page arguments' => array(1),
'access callback' => 'user_edit_access',
'access arguments' => array(1),
'type' => MENU_LOCAL_TASK,
'file' => 'openid.pages.inc',
);
$items['user/%user/openid/delete'] = array(
'title' => 'Delete OpenID',
Dries Buytaert
committed
'page callback' => 'drupal_get_form',
'page arguments' => array('openid_user_delete_form', 1),
Dries Buytaert
committed
'access callback' => 'user_edit_access',
'access arguments' => array(1),
'file' => 'openid.pages.inc',
);
return $items;
}
Angie Byron
committed
/**
* Implements hook_menu_site_status_alter().
*/
function openid_menu_site_status_alter(&$menu_site_status, $path) {
// Allow access to openid/authenticate even if site is in offline mode.
if ($menu_site_status == MENU_SITE_OFFLINE && user_is_anonymous() && in_array($path, array('openid/authenticate', 'user/login/openid'))) {
Angie Byron
committed
$menu_site_status = MENU_SITE_ONLINE;
}
}
Dries Buytaert
committed
/**
* Implements hook_admin_paths().
*/
function openid_admin_paths() {
$paths = array(
'user/*/openid' => TRUE,
'user/*/openid/delete' => TRUE,
);
return $paths;
}
Dries Buytaert
committed
* Implements hook_help().
Gábor Hojtsy
committed
function openid_help($path, $arg) {
switch ($path) {
case 'user/%/openid':
Angie Byron
committed
$output = '<p>' . t('This site supports <a href="@openid-net">OpenID</a>, a secure way to log in to many websites using a single username and password. OpenID can reduce the necessity of managing many usernames and passwords for many websites.', array('@openid-net' => 'http://openid.net')) . '</p>';
$output .= '<p>' . t('To use OpenID you must first establish an identity on a public or private OpenID server. If you do not have an OpenID and would like one, look into one of the <a href="@openid-providers">free public providers</a>. You can find out more about OpenID at <a href="@openid-net">this website</a>.', array('@openid-providers' => 'http://openid.net/get/', '@openid-net' => 'http://openid.net')) . '</p>';
Angie Byron
committed
$output .= '<p>' . t('If you already have an OpenID, enter the URL to your OpenID server below (e.g. myusername.openidprovider.com). Next time you log in, you will be able to use this URL instead of a regular username and password. You can have multiple OpenID servers if you like; just keep adding them here.') . '</p>';
Dries Buytaert
committed
return $output;
Gábor Hojtsy
committed
case 'admin/help#openid':
Angie Byron
committed
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The OpenID module allows users to log in using the OpenID single sign on service. <a href="@openid-net">OpenID</a> is a secure method for logging into many websites with a single username and password. It does not require special software, and it does not share passwords with any site to which it is associated, including the site being logged into. The main benefit to users is that they can have a single password that they can use on many websites. This means they can easily update their single password from a centralized location, rather than having to change dozens of passwords individually. For more information, see the online handbook entry for <a href="@handbook">OpenID module</a>.', array('@openid-net' => 'http://openid.net', '@handbook' => 'http://drupal.org/documentation/modules/openid')) . '</p>';
Angie Byron
committed
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Logging in with OpenID') . '</dt>';
$output .= '<dd>' . t("To log in using OpenID, a user must already have an OpenID account. Users can then create site accounts using their OpenID, assign one or more OpenIDs to an existing account, and log in using an OpenID. This lowers the barrier to registration, which helps increase the user base, and offers convenience and security to the users. Because OpenID cannot guarantee a user is legitimate, email verification is still necessary. When logging in, users are presented with the option of entering their OpenID URL, which will look like <em>myusername.openidprovider.com</em>. The site then communicates with the OpenID server, asking it to verify the identity of the user. If the user is logged into their OpenID server, the server communicates back to your site, verifying the user. If they are not logged in, the OpenID server will ask the user for their password. At no point does the site being logged into record the user's OpenID password.") . '</dd>';
$output .= '</dl>';
Gábor Hojtsy
committed
return $output;
}
}
Dries Buytaert
committed
/**
* Fetch a user object by OpenID identifier.
*
* @param $identifier
* The OpenID identifier.
*
* @return
* A fully-loaded user object if the user is found or FALSE if not found.
*/
function openid_external_load($identifier) {
$uid = db_query("SELECT uid FROM {openid_identities} WHERE identifier = :identifier", array(':identifier' => $identifier))->fetchField();
if ($uid) {
return user_load($uid);
}
return FALSE;
}
/**
* Implements hook_user_delete().
*/
function openid_user_delete($account) {
db_delete('openid_identities')
->condition('uid', $account->uid)
->execute();
}
Dries Buytaert
committed
* Implements hook_user_insert().
function openid_user_insert($account) {
if (!empty($account->openid_claimed_id)) {
Angie Byron
committed
// The user has registered after trying to log in via OpenID.
Angie Byron
committed
if (config('user.settings')->get('verify_mail')) {
Angie Byron
committed
drupal_set_message(t('Once you have verified your e-mail address, you may log in via OpenID.'));
Dries Buytaert
committed
db_insert('openid_identities')
->fields(array(
'uid' => $account->uid,
'identifier' => $account->openid_claimed_id,
))
->execute();
unset($_SESSION['openid']);
unset($account->openid_claimed_id);
}
}
/**
* Implements hook_user_login().
*
* Save openid_identifier to visitor cookie.
*/
function openid_user_login($account) {
if (isset($_SESSION['openid'])) {
// The user has logged in via OpenID.
Dries Buytaert
committed
user_cookie_save(array_intersect_key($_SESSION['openid']['user_login_values'], array_flip(array('openid_identifier'))));
unset($_SESSION['openid']);
}
}
/**
* Implements hook_user_logout().
*
* Delete any openid_identifier in visitor cookie.
*/
function openid_user_logout($account) {
if (isset($_COOKIE['Drupal_visitor_openid_identifier'])) {
user_cookie_delete('openid_identifier');
}
}
* Implements hook_block_view_MODULE_DELTA_alter().
*
* Adds the OpenID login form to the user login block.
*
Dries Buytaert
committed
* @see \Drupal\user\Plugin\block\block\UserLoginBlock
Angie Byron
committed
*/
Dries Buytaert
committed
function openid_block_view_user_login_block_alter(&$build, $block) {
// Only alter the block when it is non-empty, i.e. when no user is logged in.
Dries Buytaert
committed
if (!isset($build['user_login_form'])) {
return;
Angie Byron
committed
Dries Buytaert
committed
$build['openid_login_form'] = drupal_get_form('openid_login_form');
$build['openid_login_form']['openid_identifier']['#size'] = $build['user_login_form']['name']['#size'];
Angie Byron
committed
Angie Byron
committed
// Put an OpenID link as a first element.
Dries Buytaert
committed
$build['user_links']['#items'] = array(
Angie Byron
committed
l(t('Log in using OpenID'), 'user/login/openid', array(
'attributes' => array(
'title' => t('Log in using OpenID.'),
'class' => array('openid-link'),
'role' => 'button',
'tabindex' => 0,
),
))
Dries Buytaert
committed
) + $build['user_links']['#items'];
Angie Byron
committed
// Move links under the openid form.
Dries Buytaert
committed
$build['user_links']['#weight'] = 10;
}
Angie Byron
committed
/**
* Form constructor for the OpenID login form.
*
* @see openid_login_form_submit()
*/
function openid_login_form($form) {
$form['#attached']['library'][] = array('openid', 'drupal.openid');
Angie Byron
committed
$form['openid_identifier'] = array(
'#type' => 'textfield',
'#title' => t('OpenID'),
Angie Byron
committed
'#maxlength' => 255,
'#description' => l(t('What is OpenID?'), 'http://openid.net/', array('external' => TRUE)),
'#required' => TRUE,
);
$form['openid.return_to'] = array(
'#type' => 'hidden',
'#value' => url('openid/authenticate', array('absolute' => TRUE, 'query' => user_login_destination())),
Angie Byron
committed
);
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in'));
return $form;
}
/**
* Form submit handler for openid_login_form().
*
* @see openid_login_form()
*/
function openid_login_form_submit($form, &$form_state) {
$return_to = $form_state['values']['openid.return_to'];
if (empty($return_to)) {
$return_to = url('', array('absolute' => TRUE));
}
openid_begin($form_state['values']['openid_identifier'], $return_to, $form_state['values']);
Angie Byron
committed
}
/**
Dries Buytaert
committed
* Implements hook_form_FORM_ID_alter().
Dries Buytaert
committed
*
Dries Buytaert
committed
* Prefills the login form with values acquired via OpenID.
Angie Byron
committed
*/
function openid_form_user_register_form_alter(&$form, &$form_state) {
Dries Buytaert
committed
if (isset($_SESSION['openid']['response'])) {
module_load_include('inc', 'openid');
$response = $_SESSION['openid']['response'];
// Extract Simple Registration keys from the response. We only include
// signed keys as required by OpenID Simple Registration Extension 1.0,
// section 4.
$sreg_values = openid_extract_namespace($response, OPENID_NS_SREG, 'sreg', TRUE);
// Extract Attribute Exchanges keys from the response. We only include
// signed keys. This is not required by the specification, but it is
// recommended by Google, see
// http://googlecode.blogspot.com/2011/05/security-advisory-to-websites-using.html
$ax_values = openid_extract_namespace($response, OPENID_NS_AX, 'ax', TRUE);
Dries Buytaert
committed
if (!empty($sreg_values['nickname'])) {
// Use the nickname returned by Simple Registration if available.
$form['account']['name']['#default_value'] = $sreg_values['nickname'];
}
Dries Buytaert
committed
elseif ($ax_name_values = openid_extract_ax_values($ax_values, array('http://axschema.org/namePerson/friendly', 'http://schema.openid.net/namePerson/friendly'))) {
Dries Buytaert
committed
// Else, use the first nickname returned by AX if available.
$form['account']['name']['#default_value'] = current($ax_name_values);
}
else {
$form['account']['name']['#default_value'] = '';
Dries Buytaert
committed
}
if (!empty($sreg_values['email'])) {
// Use the email returned by Simple Registration if available.
$form['account']['mail']['#default_value'] = $sreg_values['email'];
}
Dries Buytaert
committed
elseif ($ax_mail_values = openid_extract_ax_values($ax_values, array('http://axschema.org/contact/email', 'http://schema.openid.net/contact/email'))) {
Dries Buytaert
committed
// Else, use the first nickname returned by AX if available.
$form['account']['mail']['#default_value'] = current($ax_mail_values);
Dries Buytaert
committed
}
Angie Byron
committed
Angie Byron
committed
// If email verification is off, hide the password field and just fill
// with random password to avoid confusion.
Angie Byron
committed
if (!config('user.settings')->get('verify_mail')) {
Dries Buytaert
committed
$form['account']['pass']['#type'] = 'hidden';
$form['account']['pass']['#value'] = user_password();
Dries Buytaert
committed
$timezone = FALSE;
if (!empty($sreg_values['timezone'])) {
$timezone = $sreg_values['timezone'];
}
elseif ($ax_timezone_values = openid_extract_ax_values($ax_values, array('http://axschema.org/pref/timezone', 'http://openid.net/schema/timezone'))) {
$timezone = current($ax_timezone_values);
}
if (in_array($timezone, timezone_identifiers_list())) {
$account = $form_state['controller']->getEntity($form_state);
$account->timezone = $timezone;
}
$language = FALSE;
if (!empty($sreg_values['language'])) {
$language = $sreg_values['language'];
}
elseif ($ax_language_values = openid_extract_ax_values($ax_values, array('http://axschema.org/pref/language', 'http://openid.net/schema/language/pref'))) {
$language = current($ax_language_values);
}
if ($language) {
// The OpenID Simple Registration Extension specification is unclear about
// the format of openid.sreg.language. Codes like "EN" and "ZH_CN" have
// been observed.
// AX values are in RFC 4646 format, e.g. "de", "en-GB", "en-Latn-GB",
// "zh-Hans", or "zh-Hans-CN". The first part is the language, the second
// is the script, and the third is the region. Other parts are also
// defined, but we will not use them here. All parts except the first are
// optional.
// We generate a list of all permutations of the first three parts and
// match them against the list of enabled languages. E.g. if the user's
// preferred langugage is "en-GB", we look for "en-gb" (Drupal's language
// codes are lower-case) or fall back to "en".
$parts = preg_split('/[_-]/', strtolower($language));
$candidate_langcodes[] = $parts[0];
if (count($parts) > 1) {
$candidate_langcodes[] = $parts[0] . '-' . $parts[1];
}
if (count($parts) > 2) {
$candidate_langcodes[] = $parts[0] . '-' . $parts[2];
$candidate_langcodes[] = $parts[0] . '-' . $parts[1] . '-' . $parts[2];
}
Angie Byron
committed
$languages = language_list();
// Iterate over the generated permutations starting with the longest (most
// specific) strings.
foreach (array_reverse($candidate_langcodes) as $candidate_langcode) {
Angie Byron
committed
if (isset($languages[$candidate_langcode])) {
$form['language']['preferred_langcode']['#type'] = 'hidden';
$form['language']['preferred_langcode']['#value'] = $candidate_langcode;
// Skip the rest of the foreach to not overwrite the specific
// language we found.
break;
}
}
}
Dries Buytaert
committed
$form['openid_claimed_id'] = array(
'#type' => 'value',
'#default_value' => $response['openid.claimed_id'],
);
Angie Byron
committed
$form['openid_display'] = array(
'#type' => 'item',
'#title' => t('Your OpenID'),
'#description' => t('This OpenID will be attached to your account after registration.'),
Dries Buytaert
committed
'#markup' => check_plain($response['openid.claimed_id']),
Angie Byron
committed
);
}
}
/**
* The initial step of OpenID authentication responsible for the following:
* - Perform discovery on the claimed OpenID.
* - If possible, create an association with the Provider's endpoint.
* - Create the authentication request.
* - Perform the appropriate redirect.
*
* @param $claimed_id The OpenID to authenticate
* @param $return_to The endpoint to return to from the OpenID Provider
*/
function openid_begin($claimed_id, $return_to = '', $form_values = array()) {
module_load_include('inc', 'openid');
Angie Byron
committed
$service = NULL;
Dries Buytaert
committed
$claimed_id = openid_normalize($claimed_id);
Angie Byron
committed
$discovery = openid_discovery($claimed_id);
Angie Byron
committed
if (!empty($discovery['services'])) {
$service = _openid_select_service($discovery['services']);
}
Dries Buytaert
committed
Angie Byron
committed
// Quit if the discovery result was empty or if we can't select any service.
if (!$discovery || !$service) {
form_set_error('openid_identifier', t('Sorry, that is not a valid OpenID. Ensure you have spelled your ID correctly.'));
return;
}
Angie Byron
committed
// Set claimed id from discovery.
if (!empty($discovery['claimed_id'])) {
$claimed_id = $discovery['claimed_id'];
}
// Store discovered information in the users' session so we don't have to rediscover.
Dries Buytaert
committed
$_SESSION['openid']['service'] = $service;
// Store the claimed id
$_SESSION['openid']['claimed_id'] = $claimed_id;
// Store the login form values so we can pass them to
// user_exteral_login later.
$_SESSION['openid']['user_login_values'] = $form_values;
Dries Buytaert
committed
// If a supported math library is present, then create an association.
$assoc_handle = '';
Dries Buytaert
committed
if (_openid_get_math_library()) {
Dries Buytaert
committed
$assoc_handle = openid_association($service['uri']);
}
Dries Buytaert
committed
if (in_array('http://specs.openid.net/auth/2.0/server', $service['types'])) {
// User entered an OP Identifier.
$claimed_id = $identity = 'http://specs.openid.net/auth/2.0/identifier_select';
Dries Buytaert
committed
// Use Claimed ID and/or OP-Local Identifier from service description, if
// available.
if (!empty($service['claimed_id'])) {
$claimed_id = $service['claimed_id'];
Dries Buytaert
committed
}
Dries Buytaert
committed
$identity = !empty($service['identity']) ? $service['identity'] : $claimed_id;
}
Dries Buytaert
committed
$request = openid_authentication_request($claimed_id, $identity, $return_to, $assoc_handle, $service);
Dries Buytaert
committed
if ($service['version'] == 2) {
openid_redirect($service['uri'], $request);
}
else {
Dries Buytaert
committed
openid_redirect_http($service['uri'], $request);
}
}
/**
* Completes OpenID authentication by validating returned data from the OpenID
* Provider.
*
* @param $response Array of returned values from the OpenID Provider.
*
* @return $response Response values for further processing with
* $response['status'] set to one of 'success', 'failed' or 'cancel'.
*/
function openid_complete($response = array()) {
module_load_include('inc', 'openid');
if (count($response) == 0) {
$response = _openid_response();
}
// Default to failed response
$response['status'] = 'failed';
if (isset($_SESSION['openid']['service']['uri']) && isset($_SESSION['openid']['claimed_id'])) {
$service = $_SESSION['openid']['service'];
$claimed_id = $_SESSION['openid']['claimed_id'];
unset($_SESSION['openid']['service']);
unset($_SESSION['openid']['claimed_id']);
if (isset($response['openid.mode'])) {
if ($response['openid.mode'] == 'cancel') {
$response['status'] = 'cancel';
}
else {
if (openid_verify_assertion($service, $response)) {
Dries Buytaert
committed
// OpenID Authentication, section 7.3.2.3 and Appendix A.5:
// The CanonicalID specified in the XRDS document must be used as the
// account key. We rely on the XRI proxy resolver to verify that the
// provider is authorized to respond on behalf of the specified
// identifer (required per Extensible Resource Identifier (XRI)
// (XRI) Resolution Version 2.0, section 14.3):
if (!empty($service['claimed_id'])) {
$response['openid.claimed_id'] = $service['claimed_id'];
}
elseif ($service['version'] == 2) {
Dries Buytaert
committed
// Returned Claimed Identifier could contain unique fragment
// identifier to allow identifier recycling so we need to preserve
// it in the response.
$response_claimed_id = openid_normalize($response['openid.claimed_id']);
// OpenID Authentication, section 11.2:
// If the returned Claimed Identifier is different from the one sent
// to the OpenID Provider, we need to do discovery on the returned
// identififer to make sure that the provider is authorized to
// respond on behalf of this.
Dries Buytaert
committed
if ($response_claimed_id != $claimed_id) {
Angie Byron
committed
$discovery = openid_discovery($response['openid.claimed_id']);
if ($discovery && !empty($discovery['services'])) {
$uris = array();
foreach ($discovery['services'] as $discovered_service) {
if (in_array('http://specs.openid.net/auth/2.0/server', $discovered_service['types']) || in_array('http://specs.openid.net/auth/2.0/signon', $discovered_service['types'])) {
$uris[] = $discovered_service['uri'];
}
}
}
if (!in_array($service['uri'], $uris)) {
return $response;
Dries Buytaert
committed
}
}
}
else {
$response['openid.claimed_id'] = $claimed_id;
}
$response['status'] = 'success';
}
}
}
}
return $response;
}
/**
* Perform discovery on a claimed ID to determine the OpenID provider endpoint.
*
Angie Byron
committed
* Discovery methods are provided by the hook_openid_discovery_method_info and
* could be further altered using the hook_openid_discovery_method_info_alter.
*
* @param $claimed_id
* The OpenID URL to perform discovery on.
Angie Byron
committed
* @return
* The resulting discovery array from the first successful discovery method,
* which must contain following keys:
* - 'services' (required) an array of discovered services (including OpenID
* version, endpoint URI, etc).
* - 'claimed_id' (optional) new claimed identifer, found by following HTTP
* redirects during the services discovery.
* If all the discovery method fails or if no appropriate discovery method is
* found, FALSE is returned.
*/
function openid_discovery($claimed_id) {
module_load_include('inc', 'openid');
Dries Buytaert
committed
$methods = module_invoke_all('openid_discovery_method_info');
drupal_alter('openid_discovery_method_info', $methods);
Angie Byron
committed
// Execute each method in turn and return first successful discovery.
Dries Buytaert
committed
foreach ($methods as $method) {
Angie Byron
committed
$discovery = $method($claimed_id);
if (!empty($discovery)) {
return $discovery;
Dries Buytaert
committed
}
}
Angie Byron
committed
return FALSE;
Dries Buytaert
committed
}
/**
* Implements hook_openid_discovery_method_info().
Dries Buytaert
committed
*
* Define standard discovery methods.
*/
function openid_openid_discovery_method_info() {
// The discovery process will stop as soon as one discovery method succeed.
// We first attempt to discover XRI-based identifiers, then standard XRDS
// identifiers via Yadis and HTML-based discovery, conforming to the OpenID 2.0
// specification.
Dries Buytaert
committed
return array(
'xri' => '_openid_xri_discovery',
'xrds' => '_openid_xrds_discovery',
);
}
/**
* OpenID discovery method: perform an XRI discovery.
*
* @see http://openid.net/specs/openid-authentication-2_0.html#discovery
* @see hook_openid_discovery_method_info()
Angie Byron
committed
* @see openid_discovery()
*
* @return
* An array of discovered services and claimed identifier or NULL. See
* openid_discovery() for more specific information.
Dries Buytaert
committed
*/
function _openid_xri_discovery($claimed_id) {
if (_openid_is_xri($claimed_id)) {
Dries Buytaert
committed
// Resolve XRI using a proxy resolver (Extensible Resource Identifier (XRI)
Dries Buytaert
committed
// Resolution Version 2.0, section 11.2 and 14.3).
Angie Byron
committed
$xrds_url = config('openid.settings')->get('xri_proxy_resolver') . rawurlencode($claimed_id) . '?_xrd_r=application/xrds+xml';
Angie Byron
committed
$discovery = _openid_xrds_discovery($xrds_url);
if (!empty($discovery['services']) && is_array($discovery['services'])) {
foreach ($discovery['services'] as $i => &$service) {
$status = $service['xrd']->children(OPENID_NS_XRD)->Status;
if ($status && $status->attributes()->cid == 'verified') {
$service['claimed_id'] = openid_normalize((string)$service['xrd']->children(OPENID_NS_XRD)->CanonicalID);
}
else {
// Ignore service if the Canonical ID could not be verified.
unset($discovery['services'][$i]);
}
Dries Buytaert
committed
}
Angie Byron
committed
if (!empty($discovery['services'])) {
return $discovery;
Dries Buytaert
committed
}
Dries Buytaert
committed
}
Dries Buytaert
committed
}
/**
* OpenID discovery method: perform a XRDS discovery.
*
* @see http://openid.net/specs/openid-authentication-2_0.html#discovery
* @see hook_openid_discovery_method_info()
Angie Byron
committed
* @see openid_discovery()
*
* @return
* An array of discovered services and claimed identifier or NULL. See
* openid_discovery() for more specific information.
Dries Buytaert
committed
*/
function _openid_xrds_discovery($claimed_id) {
$services = array();
$xrds_url = $claimed_id;
$scheme = @parse_url($xrds_url, PHP_URL_SCHEME);
if ($scheme == 'http' || $scheme == 'https') {
// For regular URLs, try Yadis resolution first, then HTML-based discovery
$headers = array('Accept' => 'application/xrds+xml');
Dries Buytaert
committed
$result = drupal_http_request($xrds_url, array('headers' => $headers));
Angie Byron
committed
// Check for HTTP error and make sure, that we reach the target. If the
// maximum allowed redirects are exhausted, final destination URL isn't
// reached, but drupal_http_request() doesn't return any error.
// @todo Remove the check for 200 HTTP result code after the following issue
// will be fixed: http://drupal.org/node/1096890.
if (!isset($result->error) && $result->code == 200) {
// Replace the user-entered claimed_id if we received a redirect.
if (!empty($result->redirect_url)) {
$claimed_id = openid_normalize($result->redirect_url);
}
Dries Buytaert
committed
if (isset($result->headers['content-type']) && preg_match("/application\/xrds\+xml/", $result->headers['content-type'])) {
// Parse XML document to find URL
Dries Buytaert
committed
$services = _openid_xrds_parse($result->data);
}
else {
$xrds_url = NULL;
Dries Buytaert
committed
if (isset($result->headers['x-xrds-location'])) {
$xrds_url = $result->headers['x-xrds-location'];
}
else {
// Look for meta http-equiv link in HTML head
$xrds_url = _openid_meta_httpequiv($result->data);
}
if (!empty($xrds_url)) {
$headers = array('Accept' => 'application/xrds+xml');
Dries Buytaert
committed
$xrds_result = drupal_http_request($xrds_url, array('headers' => $headers));
if (!isset($xrds_result->error)) {
Dries Buytaert
committed
$services = _openid_xrds_parse($xrds_result->data);
}
}
}
// Check for HTML delegation
if (count($services) == 0) {
// Look for 2.0 links
$uri = _openid_link_href('openid2.provider', $result->data);
Dries Buytaert
committed
$identity = _openid_link_href('openid2.local_id', $result->data);
Dries Buytaert
committed
$type = 'http://specs.openid.net/auth/2.0/signon';
Dries Buytaert
committed
// 1.x links
if (empty($uri)) {
$uri = _openid_link_href('openid.server', $result->data);
Dries Buytaert
committed
$identity = _openid_link_href('openid.delegate', $result->data);
Dries Buytaert
committed
$type = 'http://openid.net/signon/1.1';
}
if (!empty($uri)) {
Dries Buytaert
committed
$services[] = array(
'uri' => $uri,
Dries Buytaert
committed
'identity' => $identity,
Dries Buytaert
committed
'types' => array($type),
);
}
}
}
}
Angie Byron
committed
if (!empty($services)) {
return array(
'services' => $services,
'claimed_id' => $claimed_id,
);
}
}
Dries Buytaert
committed
/**
* Implements hook_openid_normalization_method_info().
Dries Buytaert
committed
*
* Define standard normalization methods.
*/
function openid_openid_normalization_method_info() {
// OpenID Authentication 2.0, section 7.2:
// If the User-supplied Identifier looks like an XRI, treat it as such;
// otherwise treat it as an HTTP URL.
Dries Buytaert
committed
return array(
'xri' => '_openid_xri_normalize',
'url' => '_openid_url_normalize',
);
}
/**
* Attempt to create a shared secret with the OpenID Provider.
*
* @param $op_endpoint URL of the OpenID Provider endpoint.
*
* @return $assoc_handle The association handle.
*/
function openid_association($op_endpoint) {
module_load_include('inc', 'openid');
// Remove Old Associations:
db_delete('openid_association')
Dries Buytaert
committed
->where('created + expires_in < :request_time', array(':request_time' => REQUEST_TIME))
->execute();
// Check to see if we have an association for this IdP already
$assoc_handle = db_query("SELECT assoc_handle FROM {openid_association} WHERE idp_endpoint_uri = :endpoint", array(':endpoint' => $op_endpoint))->fetchField();
if (empty($assoc_handle)) {
$mod = OPENID_DH_DEFAULT_MOD;
$gen = OPENID_DH_DEFAULT_GEN;
$r = _openid_dh_rand($mod);
Dries Buytaert
committed
$private = _openid_math_add($r, 1);
$public = _openid_math_powmod($gen, $private, $mod);
// If there is no existing association, then request one
$assoc_request = openid_association_request($public);
$assoc_message = _openid_encode_message(_openid_create_message($assoc_request));
Dries Buytaert
committed
$assoc_options = array(
'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8'),
'method' => 'POST',
'data' => $assoc_message,
);
$assoc_result = drupal_http_request($op_endpoint, $assoc_options);
if (isset($assoc_result->error)) {
return FALSE;
}
$assoc_response = _openid_parse_message($assoc_result->data);
if (isset($assoc_response['mode']) && $assoc_response['mode'] == 'error') {
Gábor Hojtsy
committed
return FALSE;
}
if ($assoc_response['session_type'] == 'DH-SHA1') {
$spub = _openid_dh_base64_to_long($assoc_response['dh_server_public']);
$enc_mac_key = base64_decode($assoc_response['enc_mac_key']);
Dries Buytaert
committed
$shared = _openid_math_powmod($spub, $private, $mod);
$assoc_response['mac_key'] = base64_encode(_openid_dh_xorsecret($shared, $enc_mac_key));
}
db_insert('openid_association')
->fields(array(
'idp_endpoint_uri' => $op_endpoint,
'session_type' => $assoc_response['session_type'],
'assoc_handle' => $assoc_response['assoc_handle'],
'assoc_type' => $assoc_response['assoc_type'],
'expires_in' => $assoc_response['expires_in'],
'mac_key' => $assoc_response['mac_key'],
'created' => REQUEST_TIME,
))
->execute();
$assoc_handle = $assoc_response['assoc_handle'];
}
return $assoc_handle;
}
/**
* Authenticate a user or attempt registration.
*
* @param $response Response values from the OpenID Provider.
*/
function openid_authentication($response) {
$identity = $response['openid.claimed_id'];
Dries Buytaert
committed
$account = openid_external_load($identity);
if (isset($account->uid)) {
Angie Byron
committed
if (!config('user.settings')->get('verify_mail') || $account->login) {
Dries Buytaert
committed
// Check if user is blocked.
Angie Byron
committed
$state['values']['name'] = $account->name;
user_login_name_validate(array(), $state);
Dries Buytaert
committed
if (!form_get_errors()) {
// Load global $user and perform final login tasks.
$form_state['uid'] = $account->uid;
Angie Byron
committed
user_login_form_submit(array(), $form_state);
Dries Buytaert
committed
}
}
else {
Dries Buytaert
committed
drupal_set_message(t('You must validate your email address for this account before logging in via OpenID.'));
catch
committed
// Let other modules act on OpenID login
module_invoke_all('openid_response', $response, $account);
Angie Byron
committed
elseif (config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY) {
// Register new user.
Dries Buytaert
committed
Dries Buytaert
committed
// Save response for use in openid_form_user_register_form_alter().
$_SESSION['openid']['response'] = $response;
Dries Buytaert
committed
$form_state['values'] = array();
$form_state['values']['op'] = t('Create new account');
$account = entity_create('user', array());
entity_form_submit($account, 'register', $form_state);
catch
committed
if (empty($form_state['user'])) {
module_invoke_all('openid_response', $response, NULL);
}
else {
module_invoke_all('openid_response', $response, $form_state['user']);
drupal_goto();
}
$messages = drupal_get_messages('error');
if (empty($form_state['values']['name']) || empty($form_state['values']['mail'])) {
// If the OpenID provider did not provide both a user name and an email
// address, ask the user to complete the registration manually instead of
// showing the error messages about the missing values generated by FAPI.
drupal_set_message(t('Complete the registration by filling out the form below. If you already have an account, you can <a href="@login">log in</a> now and add your OpenID under "My account".', array('@login' => url('user/login'))), 'warning');
}
else {
drupal_set_message(t('Account registration using the information provided by your OpenID provider failed due to the reasons listed below. Complete the registration by filling out the form below. If you already have an account, you can <a href="@login">log in</a> now and add your OpenID under "My account".', array('@login' => url('user/login'))), 'warning');
// Append form validation errors below the above warning.
foreach ($messages['error'] as $message) {
drupal_set_message( $message, 'error');
}
}
// We were unable to register a valid new user. Redirect to the normal
// registration page and prefill with the values we received.
Dries Buytaert
committed
$destination = drupal_get_destination();
unset($_GET['destination']);
drupal_goto('user/register', array('query' => $destination));
Gábor Hojtsy
committed
else {
drupal_set_message(t('Only site administrators can create new user accounts.'), 'error');
catch
committed
module_invoke_all('openid_response', $response, NULL);
Gábor Hojtsy
committed
}
drupal_goto();
}
function openid_association_request($public) {
module_load_include('inc', 'openid');
$request = array(
'openid.ns' => OPENID_NS_2_0,
'openid.mode' => 'associate',
'openid.session_type' => 'DH-SHA1',
'openid.assoc_type' => 'HMAC-SHA1'
);
if ($request['openid.session_type'] == 'DH-SHA1' || $request['openid.session_type'] == 'DH-SHA256') {
$cpub = _openid_dh_long_to_base64($public);
$request['openid.dh_consumer_public'] = $cpub;
}
return $request;
}
Dries Buytaert
committed
function openid_authentication_request($claimed_id, $identity, $return_to = '', $assoc_handle = '', $service) {
global $base_url;
module_load_include('inc', 'openid');
$request = array(
'openid.mode' => 'checkid_setup',
'openid.identity' => $identity,
'openid.assoc_handle' => $assoc_handle,
'openid.return_to' => $return_to,
);
Dries Buytaert
committed
if ($service['version'] == 2) {
$request['openid.ns'] = OPENID_NS_2_0;
$request['openid.claimed_id'] = $claimed_id;
$request['openid.realm'] = $base_url .'/';
}
else {
$request['openid.trust_root'] = $base_url .'/';
}
Dries Buytaert
committed
// Always request Simple Registration. The specification doesn't mandate
// that the Endpoint advertise OPENID_NS_SREG in the service description.
$request['openid.ns.sreg'] = OPENID_NS_SREG;
$request['openid.sreg.required'] = 'nickname,email';
$request['openid.sreg.optional'] = 'timezone,language';
Dries Buytaert
committed
// Request Attribute Exchange, if available.
// We only request the minimum attributes we need here, contributed modules
// can alter the request to add more attribute, and map them to profile fields.
if (in_array(OPENID_NS_AX, $service['types'])) {
$request['openid.ns.ax'] = OPENID_NS_AX;
$request['openid.ax.mode'] = 'fetch_request';
Dries Buytaert
committed
$request['openid.ax.required'] = 'mail_ao,name_ao,mail_son,name_son';
$request['openid.ax.if_available'] = 'timezone_ao,language_ao,timezone_son,language_son';
Dries Buytaert
committed
// Implementors disagree on which URIs to use, even for simple
// attributes like name and email (*sigh*). We ask for both axschema.org
// attributes (which are supposed to be newer), and schema.openid.net ones
// (which are supposed to be legacy).
// Attributes as defined by axschema.org.
$request['openid.ax.type.mail_ao'] = 'http://axschema.org/contact/email';
$request['openid.ax.type.name_ao'] = 'http://axschema.org/namePerson/friendly';
$request['openid.ax.type.timezone_ao'] = 'http://axschema.org/pref/timezone';
$request['openid.ax.type.language_ao'] = 'http://axschema.org/pref/language';
Dries Buytaert
committed
// Attributes as defined by schema.openid.net.
$request['openid.ax.type.mail_son'] = 'http://schema.openid.net/contact/email';
$request['openid.ax.type.name_son'] = 'http://schema.openid.net/namePerson/friendly';
$request['openid.ax.type.timezone_son'] = 'http://openid.net/schema/timezone';
$request['openid.ax.type.language_son'] = 'http://openid.net/schema/language/pref';
Dries Buytaert
committed
}
catch
committed
drupal_alter('openid_request', $request, $service);
return $request;
}
/**
* Attempt to verify the response received from the OpenID Provider.
*
* @param $service
* Array describing the OpenID provider.
* @param $response
* Array of response values from the provider.
*
* @return boolean
Dries Buytaert
committed
* @see http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4
function openid_verify_assertion($service, $response) {
module_load_include('inc', 'openid');
// http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.3
// Check the Nonce to protect against replay attacks.
if (!openid_verify_assertion_nonce($service, $response)) {
return FALSE;
}
// http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.1
// Verifying the return URL.
if (!openid_verify_assertion_return_url($service, $response)) {
return FALSE;
}
// http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4
// Verify the signatures.
$valid = FALSE;
Dries Buytaert
committed
$association = FALSE;
// If the OP returned a openid.invalidate_handle, we have to proceed with
// direct verification: ignore the openid.assoc_handle, even if present.
// See http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.1
if (!empty($response['openid.assoc_handle']) && empty($response['openid.invalidate_handle'])) {
$association = db_query("SELECT * FROM {openid_association} WHERE assoc_handle = :assoc_handle", array(':assoc_handle' => $response['openid.assoc_handle']))->fetchObject();
}
if ($association && isset($association->session_type)) {
// http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.2
// Verification using an association.
$valid = openid_verify_assertion_signature($service, $association, $response);
}
else {
// http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.2
// Direct verification.
Dries Buytaert
committed
// The verification requests contain all the fields from the response,
// except openid.mode.
$request = $response;
$request['openid.mode'] = 'check_authentication';
$message = _openid_create_message($request);
Dries Buytaert
committed
$options = array(
'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8'),
'method' => 'POST',
'data' => _openid_encode_message($message),
);
$result = drupal_http_request($service['uri'], $options);
if (!isset($result->error)) {
$response = _openid_parse_message($result->data);
Dries Buytaert
committed
if (strtolower(trim($response['is_valid'])) == 'true') {
$valid = TRUE;
Dries Buytaert
committed
if (!empty($response['invalidate_handle'])) {
// This association handle has expired on the OP side, remove it from the
// database to avoid reusing it again on a subsequent authentication request.
// See http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4.2.2
db_delete('openid_association')
->condition('assoc_handle', $response['invalidate_handle'])
->execute();
}
}
else {
$valid = FALSE;
}
}
}
return $valid;
}
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Verify the signature of the response received from the OpenID provider.
*
* @param $service
* Array describing the OpenID provider.
* @param $association
* Information on the association with the OpenID provider.
* @param $response
* Array of response values from the provider.
*
* @return
* TRUE if the signature is valid and covers all fields required to be signed.
* @see http://openid.net/specs/openid-authentication-2_0.html#rfc.section.11.4
*/
function openid_verify_assertion_signature($service, $association, $response) {
if ($service['version'] == 2) {
// OpenID Authentication 2.0, section 10.1:
// These keys must always be signed.
$mandatory_keys = array('op_endpoint', 'return_to', 'response_nonce', 'assoc_handle');
if (isset($response['openid.claimed_id'])) {
// If present, these two keys must also be signed. According to the spec,
// they are either both present or both absent.
$mandatory_keys[] = 'claimed_id';
$mandatory_keys[] = 'identity';
}