comparison modules/openid/openid.module @ 1:c1f4ac30525a 6.0

Drupal 6.0
author Franck Deroche <webmaster@defr.org>
date Tue, 23 Dec 2008 14:28:28 +0100
parents
children 2427550111ae
comparison
equal deleted inserted replaced
0:5a113a1c4740 1:c1f4ac30525a
1 <?php
2 // $Id: openid.module,v 1.19 2008/01/30 22:11:22 goba Exp $
3
4 /**
5 * @file
6 * Implement OpenID Relying Party support for Drupal
7 */
8
9 /**
10 * Implementation of hook_menu.
11 */
12 function openid_menu() {
13 $items['openid/authenticate'] = array(
14 'title' => 'OpenID Login',
15 'page callback' => 'openid_authentication_page',
16 'access callback' => 'user_is_anonymous',
17 'type' => MENU_CALLBACK,
18 'file' => 'openid.pages.inc',
19 );
20 $items['user/%user/openid'] = array(
21 'title' => 'OpenID identities',
22 'page callback' => 'openid_user_identities',
23 'page arguments' => array(1),
24 'access callback' => 'user_edit_access',
25 'access arguments' => array(1),
26 'type' => MENU_LOCAL_TASK,
27 'file' => 'openid.pages.inc',
28 );
29 $items['user/%user/openid/delete'] = array(
30 'title' => 'Delete OpenID',
31 'page callback' => 'openid_user_delete',
32 'page arguments' => array(1),
33 'type' => MENU_CALLBACK,
34 'file' => 'openid.pages.inc',
35 );
36 return $items;
37 }
38
39 /**
40 * Implementation of hook_help().
41 */
42 function openid_help($path, $arg) {
43 switch ($path) {
44
45 case 'user/%/openid':
46 $output = '<p>'. t('This site supports <a href="@openid-net">OpenID</a>, a secure way to log into 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' => url('http://openid.net'))) .'</p>';
47 $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' => url('http://openid.net/wiki/index.php/OpenIDServers'), '@openid-net' => url('http://openid.net'))) .'</p>';
48 $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 login, 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>';
49 return $output;
50
51 case 'admin/help#openid':
52 $output = '<p>'. t('OpenID 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 your site.') .'</p>';
53 $output .= '<p>'. t('Users can create 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 is good for the site, and offers convenience and security to the users. OpenID is not a trust system, so email verification is still necessary. The benefit stems from the fact that users 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.') .'</p>';
54 $output .= '<p>'. t('The basic concept is as follows: A user has an account on an OpenID server. This account provides them with a unique URL (such as myusername.openidprovider.com). When the user comes to your site, they are presented with the option of entering this URL. Your 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 your site record, or need to record the user\'s password.') .'</p>';
55 $output .= '<p>'. t('More information on OpenID is available at <a href="@openid-net">OpenID.net</a>.', array('@openid-net' => url('http://openid.net'))) .'</p>';
56 $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@handbook">OpenID module</a>.', array('@handbook' => 'http://drupal.org/handbook/modules/openid')) .'</p>';
57 return $output;
58 }
59 }
60
61 /**
62 * Implementation of hook_user().
63 */
64 function openid_user($op, &$edit, &$account, $category = NULL) {
65 if ($op == 'insert' && isset($_SESSION['openid']['values'])) {
66 // The user has registered after trying to login via OpenID.
67 if (variable_get('user_email_verification', TRUE)) {
68 drupal_set_message(t('Once you have verified your email address, you may log in via OpenID.'));
69 }
70 unset($_SESSION['openid']);
71 }
72 }
73
74 /**
75 * Implementation of hook_form_alter : adds OpenID login to the login forms.
76 */
77 function openid_form_alter(&$form, $form_state, $form_id) {
78 if ($form_id == 'user_login_block' || $form_id == 'user_login') {
79 drupal_add_css(drupal_get_path('module', 'openid') .'/openid.css', 'module');
80 drupal_add_js(drupal_get_path('module', 'openid') .'/openid.js');
81 if (!empty($form_state['post']['openid_identifier'])) {
82 $form['name']['#required'] = FALSE;
83 $form['pass']['#required'] = FALSE;
84 unset($form['#submit']);
85 $form['#validate'] = array('openid_login_validate');
86 }
87
88 $items = array();
89 $items[] = array(
90 'data' => l(t('Log in using OpenID'), '#'),
91 'class' => 'openid-link',
92 );
93 $items[] = array(
94 'data' => l(t('Cancel OpenID login'), '#'),
95 'class' => 'user-link',
96 );
97
98 $form['openid_links'] = array(
99 '#value' => theme('item_list', $items),
100 '#weight' => 1,
101 );
102
103 $form['links']['#weight'] = 2;
104
105 $form['openid_identifier'] = array(
106 '#type' => 'textfield',
107 '#title' => t('Log in using OpenID'),
108 '#size' => ($form_id == 'user_login') ? 58 : 13,
109 '#maxlength' => 255,
110 '#weight' => -1,
111 '#description' => l(t('What is OpenID?'), 'http://openid.net/', array('external' => TRUE)),
112 );
113 $form['openid.return_to'] = array('#type' => 'hidden', '#value' => url('openid/authenticate', array('absolute' => TRUE, 'query' => drupal_get_destination())));
114 }
115 elseif ($form_id == 'user_register' && isset($_SESSION['openid'])) {
116 // We were unable to auto-register a new user. Prefill the registration
117 // form with the values we have.
118 $form['name']['#default_value'] = $_SESSION['openid']['values']['name'];
119 $form['mail']['#default_value'] = $_SESSION['openid']['values']['mail'];
120 // If user_email_verification is off, hide the password field and just fill
121 // with random password to avoid confusion.
122 if (!variable_get('user_email_verification', TRUE)) {
123 $form['pass']['#type'] = 'hidden';
124 $form['pass']['#value'] = user_password();
125 }
126 $form['auth_openid'] = array('#type' => 'hidden', '#value' => $_SESSION['openid']['values']['auth_openid']);
127 }
128 return $form;
129 }
130
131 /**
132 * Login form _validate hook
133 */
134 function openid_login_validate($form, &$form_state) {
135 $return_to = $form_state['values']['openid.return_to'];
136 if (empty($return_to)) {
137 $return_to = url('', array('absolute' => TRUE));
138 }
139
140 openid_begin($form_state['values']['openid_identifier'], $return_to, $form_state['values']);
141 }
142
143 /**
144 * The initial step of OpenID authentication responsible for the following:
145 * - Perform discovery on the claimed OpenID.
146 * - If possible, create an association with the Provider's endpoint.
147 * - Create the authentication request.
148 * - Perform the appropriate redirect.
149 *
150 * @param $claimed_id The OpenID to authenticate
151 * @param $return_to The endpoint to return to from the OpenID Provider
152 */
153 function openid_begin($claimed_id, $return_to = '', $form_values = array()) {
154 module_load_include('inc', 'openid');
155
156 $claimed_id = _openid_normalize($claimed_id);
157
158 $services = openid_discovery($claimed_id);
159 if (count($services) == 0) {
160 form_set_error('openid_identifier', t('Sorry, that is not a valid OpenID. Please ensure you have spelled your ID correctly.'));
161 return;
162 }
163
164 // Store discovered information in the users' session so we don't have to rediscover.
165 $_SESSION['openid']['service'] = $services[0];
166 // Store the claimed id
167 $_SESSION['openid']['claimed_id'] = $claimed_id;
168 // Store the login form values so we can pass them to
169 // user_exteral_login later.
170 $_SESSION['openid']['user_login_values'] = $form_values;
171
172 $op_endpoint = $services[0]['uri'];
173 // If bcmath is present, then create an association
174 $assoc_handle = '';
175 if (function_exists('bcadd')) {
176 $assoc_handle = openid_association($op_endpoint);
177 }
178
179 // Now that there is an association created, move on
180 // to request authentication from the IdP
181 // First check for LocalID. If not found, check for Delegate. Fall
182 // back to $claimed_id if neither is found.
183 if (!empty($services[0]['localid'])) {
184 $identity = $services[0]['localid'];
185 }
186 else if (!empty($services[0]['delegate'])) {
187 $identity = $services[0]['delegate'];
188 }
189 else {
190 $identity = $claimed_id;
191 }
192
193 if (isset($services[0]['types']) && is_array($services[0]['types']) && in_array(OPENID_NS_2_0 .'/server', $services[0]['types'])) {
194 $identity = 'http://specs.openid.net/auth/2.0/identifier_select';
195 }
196 $authn_request = openid_authentication_request($claimed_id, $identity, $return_to, $assoc_handle, $services[0]['version']);
197
198 if ($services[0]['version'] == 2) {
199 openid_redirect($op_endpoint, $authn_request);
200 }
201 else {
202 openid_redirect_http($op_endpoint, $authn_request);
203 }
204 }
205
206 /**
207 * Completes OpenID authentication by validating returned data from the OpenID
208 * Provider.
209 *
210 * @param $response Array of returned values from the OpenID Provider.
211 *
212 * @return $response Response values for further processing with
213 * $response['status'] set to one of 'success', 'failed' or 'cancel'.
214 */
215 function openid_complete($response = array()) {
216 module_load_include('inc', 'openid');
217
218 if (count($response) == 0) {
219 $response = _openid_response();
220 }
221
222 // Default to failed response
223 $response['status'] = 'failed';
224 if (isset($_SESSION['openid']['service']['uri']) && isset($_SESSION['openid']['claimed_id'])) {
225 $service = $_SESSION['openid']['service'];
226 $claimed_id = $_SESSION['openid']['claimed_id'];
227 unset($_SESSION['openid']['service']);
228 unset($_SESSION['openid']['claimed_id']);
229 if (isset($response['openid.mode'])) {
230 if ($response['openid.mode'] == 'cancel') {
231 $response['status'] = 'cancel';
232 }
233 else {
234 if (openid_verify_assertion($service['uri'], $response)) {
235 // If the returned claimed_id is different from the session claimed_id,
236 // then we need to do discovery and make sure the op_endpoint matches.
237 if ($service['version'] == 2 && $response['openid.claimed_id'] != $claimed_id) {
238 $disco = openid_discovery($response['openid.claimed_id']);
239 if ($disco[0]['uri'] != $service['uri']) {
240 return $response;
241 }
242 }
243 else {
244 $response['openid.claimed_id'] = $claimed_id;
245 }
246 $response['status'] = 'success';
247 }
248 }
249 }
250 }
251 return $response;
252 }
253
254 /**
255 * Perform discovery on a claimed ID to determine the OpenID provider endpoint.
256 *
257 * @param $claimed_id The OpenID URL to perform discovery on.
258 *
259 * @return Array of services discovered (including OpenID version, endpoint
260 * URI, etc).
261 */
262 function openid_discovery($claimed_id) {
263 module_load_include('inc', 'openid');
264 module_load_include('inc', 'openid', 'xrds');
265
266 $services = array();
267
268 $xrds_url = $claimed_id;
269 if (_openid_is_xri($claimed_id)) {
270 $xrds_url = 'http://xri.net/'. $claimed_id;
271 }
272 $url = @parse_url($xrds_url);
273 if ($url['scheme'] == 'http' || $url['scheme'] == 'https') {
274 // For regular URLs, try Yadis resolution first, then HTML-based discovery
275 $headers = array('Accept' => 'application/xrds+xml');
276 $result = drupal_http_request($xrds_url, $headers);
277
278 if (!isset($result->error)) {
279 if (isset($result->headers['Content-Type']) && preg_match("/application\/xrds\+xml/", $result->headers['Content-Type'])) {
280 // Parse XML document to find URL
281 $services = xrds_parse($result->data);
282 }
283 else {
284 $xrds_url = NULL;
285 if (isset($result->headers['X-XRDS-Location'])) {
286 $xrds_url = $result->headers['X-XRDS-Location'];
287 }
288 else {
289 // Look for meta http-equiv link in HTML head
290 $xrds_url = _openid_meta_httpequiv('X-XRDS-Location', $result->data);
291 }
292 if (!empty($xrds_url)) {
293 $headers = array('Accept' => 'application/xrds+xml');
294 $xrds_result = drupal_http_request($xrds_url, $headers);
295 if (!isset($xrds_result->error)) {
296 $services = xrds_parse($xrds_result->data);
297 }
298 }
299 }
300
301 // Check for HTML delegation
302 if (count($services) == 0) {
303 // Look for 2.0 links
304 $uri = _openid_link_href('openid2.provider', $result->data);
305 $delegate = _openid_link_href('openid2.local_id', $result->data);
306 $version = 2;
307
308 // 1.0 links
309 if (empty($uri)) {
310 $uri = _openid_link_href('openid.server', $result->data);
311 $delegate = _openid_link_href('openid.delegate', $result->data);
312 $version = 1;
313 }
314 if (!empty($uri)) {
315 $services[] = array('uri' => $uri, 'delegate' => $delegate, 'version' => $version);
316 }
317 }
318 }
319 }
320 if (!$services) {
321 module_invoke('system', 'check_http_request');
322 }
323 return $services;
324 }
325
326 /**
327 * Attempt to create a shared secret with the OpenID Provider.
328 *
329 * @param $op_endpoint URL of the OpenID Provider endpoint.
330 *
331 * @return $assoc_handle The association handle.
332 */
333 function openid_association($op_endpoint) {
334 module_load_include('inc', 'openid');
335
336 // Remove Old Associations:
337 db_query("DELETE FROM {openid_association} WHERE created + expires_in < %d", time());
338
339 // Check to see if we have an association for this IdP already
340 $assoc_handle = db_result(db_query("SELECT assoc_handle FROM {openid_association} WHERE idp_endpoint_uri = '%s'", $op_endpoint));
341 if (empty($assoc_handle)) {
342 $mod = OPENID_DH_DEFAULT_MOD;
343 $gen = OPENID_DH_DEFAULT_GEN;
344 $r = _openid_dh_rand($mod);
345 $private = bcadd($r, 1);
346 $public = bcpowmod($gen, $private, $mod);
347
348 // If there is no existing association, then request one
349 $assoc_request = openid_association_request($public);
350 $assoc_message = _openid_encode_message(_openid_create_message($assoc_request));
351 $assoc_headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8');
352 $assoc_result = drupal_http_request($op_endpoint, $assoc_headers, 'POST', $assoc_message);
353 if (isset($assoc_result->error)) {
354 module_invoke('system', 'check_http_request');
355 return FALSE;
356 }
357
358 $assoc_response = _openid_parse_message($assoc_result->data);
359 if (isset($assoc_response['mode']) && $assoc_response['mode'] == 'error') {
360 module_invoke('system', 'check_http_request');
361 return FALSE;
362 }
363
364 if ($assoc_response['session_type'] == 'DH-SHA1') {
365 $spub = _openid_dh_base64_to_long($assoc_response['dh_server_public']);
366 $enc_mac_key = base64_decode($assoc_response['enc_mac_key']);
367 $shared = bcpowmod($spub, $private, $mod);
368 $assoc_response['mac_key'] = base64_encode(_openid_dh_xorsecret($shared, $enc_mac_key));
369 }
370 db_query("INSERT INTO {openid_association} (idp_endpoint_uri, session_type, assoc_handle, assoc_type, expires_in, mac_key, created) VALUES('%s', '%s', '%s', '%s', %d, '%s', %d)",
371 $op_endpoint, $assoc_response['session_type'], $assoc_response['assoc_handle'], $assoc_response['assoc_type'], $assoc_response['expires_in'], $assoc_response['mac_key'], time());
372
373 $assoc_handle = $assoc_response['assoc_handle'];
374 }
375
376 return $assoc_handle;
377 }
378
379 /**
380 * Authenticate a user or attempt registration.
381 *
382 * @param $response Response values from the OpenID Provider.
383 */
384 function openid_authentication($response) {
385 module_load_include('inc', 'openid');
386
387 $identity = $response['openid.claimed_id'];
388
389 $account = user_external_load($identity);
390 if (isset($account->uid)) {
391 if (!variable_get('user_email_verification', TRUE) || $account->login) {
392 user_external_login($account, $_SESSION['openid']['user_login_values']);
393 }
394 else {
395 drupal_set_message(t('You must validate your email address for this account before logging in via OpenID'));
396 }
397 }
398 elseif (variable_get('user_register', 1)) {
399 // Register new user
400 $form_state['redirect'] = NULL;
401 $form_state['values']['name'] = (empty($response['openid.sreg.nickname'])) ? $identity : $response['openid.sreg.nickname'];
402 $form_state['values']['mail'] = (empty($response['openid.sreg.email'])) ? '' : $response['openid.sreg.email'];
403 $form_state['values']['pass'] = user_password();
404 $form_state['values']['status'] = variable_get('user_register', 1) == 1;
405 $form_state['values']['response'] = $response;
406 $form_state['values']['auth_openid'] = $identity;
407 $form = drupal_retrieve_form('user_register', $form_state);
408 drupal_prepare_form('user_register', $form, $form_state);
409 drupal_validate_form('user_register', $form, $form_state);
410 if (form_get_errors()) {
411 // We were unable to register a valid new user, redirect to standard
412 // user/register and prefill with the values we received.
413 drupal_set_message(t('OpenID registration failed for the reasons listed. You may register now, or 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'))), 'error');
414 $_SESSION['openid']['values'] = $form_state['values'];
415 // We'll want to redirect back to the same place.
416 $destination = drupal_get_destination();
417 unset($_REQUEST['destination']);
418 drupal_goto('user/register', $destination);
419 }
420 else {
421 unset($form_state['values']['response']);
422 $account = user_save('', $form_state['values']);
423 // Terminate if an error occured during user_save().
424 if (!$account) {
425 drupal_set_message(t("Error saving user account."), 'error');
426 drupal_goto();
427 }
428 user_external_login($account);
429 }
430 drupal_redirect_form($form, $form_state['redirect']);
431 }
432 else {
433 drupal_set_message(t('Only site administrators can create new user accounts.'), 'error');
434 }
435 drupal_goto();
436 }
437
438 function openid_association_request($public) {
439 module_load_include('inc', 'openid');
440
441 $request = array(
442 'openid.ns' => OPENID_NS_2_0,
443 'openid.mode' => 'associate',
444 'openid.session_type' => 'DH-SHA1',
445 'openid.assoc_type' => 'HMAC-SHA1'
446 );
447
448 if ($request['openid.session_type'] == 'DH-SHA1' || $request['openid.session_type'] == 'DH-SHA256') {
449 $cpub = _openid_dh_long_to_base64($public);
450 $request['openid.dh_consumer_public'] = $cpub;
451 }
452
453 return $request;
454 }
455
456 function openid_authentication_request($claimed_id, $identity, $return_to = '', $assoc_handle = '', $version = 2) {
457 module_load_include('inc', 'openid');
458
459 $ns = ($version == 2) ? OPENID_NS_2_0 : OPENID_NS_1_0;
460 $request = array(
461 'openid.ns' => $ns,
462 'openid.mode' => 'checkid_setup',
463 'openid.identity' => $identity,
464 'openid.claimed_id' => $claimed_id,
465 'openid.assoc_handle' => $assoc_handle,
466 'openid.return_to' => $return_to,
467 );
468
469 if ($version == 2) {
470 $request['openid.realm'] = url('', array('absolute' => TRUE));
471 }
472 else {
473 $request['openid.trust_root'] = $realm;
474 }
475
476 // Simple Registration
477 $request['openid.sreg.required'] = 'nickname,email';
478 $request['openid.ns.sreg'] = "http://openid.net/extensions/sreg/1.1";
479
480 $request = array_merge($request, module_invoke_all('openid', 'request', $request));
481
482 return $request;
483 }
484
485 /**
486 * Attempt to verify the response received from the OpenID Provider.
487 *
488 * @param $op_endpoint The OpenID Provider URL.
489 * @param $response Array of repsonse values from the provider.
490 *
491 * @return boolean
492 */
493 function openid_verify_assertion($op_endpoint, $response) {
494 module_load_include('inc', 'openid');
495
496 $valid = FALSE;
497
498 $association = db_fetch_object(db_query("SELECT * FROM {openid_association} WHERE assoc_handle = '%s'", $response['openid.assoc_handle']));
499 if ($association && isset($association->session_type)) {
500 $keys_to_sign = explode(',', $response['openid.signed']);
501 $self_sig = _openid_signature($association, $response, $keys_to_sign);
502 if ($self_sig == $response['openid.sig']) {
503 $valid = TRUE;
504 }
505 else {
506 $valid = FALSE;
507 }
508 }
509 else {
510 $request = $response;
511 $request['openid.mode'] = 'check_authentication';
512 $message = _openid_create_message($request);
513 $headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8');
514 $result = drupal_http_request($op_endpoint, $headers, 'POST', _openid_encode_message($message));
515 if (!isset($result->error)) {
516 $response = _openid_parse_message($result->data);
517 if (strtolower(trim($response['is_valid'])) == 'true') {
518 $valid = TRUE;
519 }
520 else {
521 $valid = FALSE;
522 }
523 }
524 }
525 if (!$valid) {
526 module_invoke('system', 'check_http_request');
527 }
528 return $valid;
529 }