/apps/user/handlers/login/openid.php

https://bitbucket.org/jonphipps/elefant-vocabhub · PHP · 85 lines · 63 code · 11 blank · 11 comment · 12 complexity · 647dc19409954e918fbf08c060d5a15c MD5 · raw file

  1. <?php
  2. /**
  3. * OpenID social login handler.
  4. */
  5. if (! in_array ('openid', $appconf['User']['login_methods'])) {
  6. echo $this->error (404, __ ('Not found'), __ ('The page you requested could not be found.'));
  7. return;
  8. }
  9. $openid = new LightOpenID ($_SERVER['HTTP_HOST']);
  10. // handle the openid request
  11. if (! $openid->mode) {
  12. if (isset ($_POST['openid_identifier'])) {
  13. $openid->identity = $_POST['openid_identifier'];
  14. $openid->required = array ('namePerson/first', 'namePerson/last', 'contact/email');
  15. $this->redirect ($openid->authUrl ());
  16. }
  17. $page->title = 'Sign in with OpenID';
  18. echo $tpl->render ('user/login/openid');
  19. return;
  20. } elseif ($openid->mode == 'cancel') {
  21. $this->redirect ($_GET['redirect']);
  22. } elseif (! $openid->validate ()) {
  23. $this->redirect ($_GET['redirect']);
  24. }
  25. // get the openid token and data
  26. $token = $openid->identity;
  27. $data = $openid->getAttributes ();
  28. if (isset ($data['contact/email'])) {
  29. // fetch by email
  30. $u = User::query ()->where ('email', $data['contact/email'])->single ();
  31. } else {
  32. // no email, fetch by token
  33. $uid = User_OpenID::get_user_id ($token);
  34. if ($uid) {
  35. $u = new User ($uid);
  36. }
  37. }
  38. @session_start ();
  39. $_SESSION['session_openid'] = $token;
  40. if ($u) {
  41. // already have an account, log them in
  42. $u->session_id = md5 (uniqid (mt_rand (), 1));
  43. $u->expires = gmdate ('Y-m-d H:i:s', time () + 2592000);
  44. $try = 0;
  45. while (! $u->put ()) {
  46. $u->session_id = md5 (uniqid (mt_rand (), 1));
  47. $try++;
  48. if ($try == 5) {
  49. $this->redirect ($_GET['redirect']);
  50. }
  51. }
  52. $_SESSION['session_id'] = $u->session_id;
  53. // save openid token
  54. $oid = new User_OpenID (array (
  55. 'token' => $token,
  56. 'user_id' => $u->id
  57. ));
  58. $oid->put ();
  59. $this->redirect ($_GET['redirect']);
  60. } elseif (isset ($data['contact/email'])) {
  61. // signup form to create a linked account, prefill name and email
  62. $_POST['name'] = $data['namePerson/first'] . ' ' . $data['namePerson/last'];
  63. $_POST['email'] = $data['contact/email'];
  64. $_POST['redirect'] = $_GET['redirect'];
  65. $_POST['token'] = $token;
  66. echo $this->run ('user/login/newuser');
  67. } else {
  68. // signup form to create a linked account, prefill name
  69. $_POST['name'] = $data['namePerson/first'] . ' ' . $data['namePerson/last'];
  70. $_POST['redirect'] = $_GET['redirect'];
  71. $_POST['token'] = $token;
  72. echo $this->run ('user/login/newuser');
  73. }
  74. ?>