openid.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2008, 2009, StatusNet, Inc.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. if (!defined('STATUSNET')) {
  20. exit(1);
  21. }
  22. require_once('Auth/OpenID.php');
  23. require_once('Auth/OpenID/Consumer.php');
  24. require_once('Auth/OpenID/Server.php');
  25. require_once('Auth/OpenID/SReg.php');
  26. require_once('Auth/OpenID/MySQLStore.php');
  27. // About one year cookie expiry
  28. define('OPENID_COOKIE_EXPIRY', round(365.25 * 24 * 60 * 60));
  29. define('OPENID_COOKIE_KEY', 'lastusedopenid');
  30. function oid_store()
  31. {
  32. static $store = null;
  33. if (!$store) {
  34. // Can't be called statically
  35. $user = new User();
  36. $conn = $user->getDatabaseConnection();
  37. $store = new Auth_OpenID_MySQLStore($conn);
  38. }
  39. return $store;
  40. }
  41. function oid_consumer()
  42. {
  43. $store = oid_store();
  44. $consumer = new Auth_OpenID_Consumer($store);
  45. return $consumer;
  46. }
  47. function oid_server()
  48. {
  49. $store = oid_store();
  50. $server = new Auth_OpenID_Server($store, common_local_url('openidserver'));
  51. return $server;
  52. }
  53. function oid_clear_last()
  54. {
  55. oid_set_last('');
  56. }
  57. function oid_set_last($openid_url)
  58. {
  59. common_set_cookie(OPENID_COOKIE_KEY,
  60. $openid_url,
  61. time() + OPENID_COOKIE_EXPIRY);
  62. }
  63. function oid_get_last()
  64. {
  65. if (empty($_COOKIE[OPENID_COOKIE_KEY])) {
  66. return null;
  67. }
  68. $openid_url = $_COOKIE[OPENID_COOKIE_KEY];
  69. if ($openid_url && strlen($openid_url) > 0) {
  70. return $openid_url;
  71. } else {
  72. return null;
  73. }
  74. }
  75. function oid_link_user($id, $canonical, $display)
  76. {
  77. global $_PEAR;
  78. $oid = new User_openid();
  79. $oid->user_id = $id;
  80. $oid->canonical = $canonical;
  81. $oid->display = $display;
  82. $oid->created = common_sql_now();
  83. if (!$oid->insert()) {
  84. $err = &$_PEAR->getStaticProperty('DB_DataObject','lastError');
  85. return false;
  86. }
  87. return true;
  88. }
  89. function oid_get_user($openid_url)
  90. {
  91. $user = null;
  92. $oid = User_openid::getKV('canonical', $openid_url);
  93. if ($oid) {
  94. $user = User::getKV('id', $oid->user_id);
  95. }
  96. return $user;
  97. }
  98. function oid_check_immediate($openid_url, $backto=null)
  99. {
  100. if (!$backto) {
  101. $action = $_REQUEST['action'];
  102. $args = common_copy_args($_GET);
  103. unset($args['action']);
  104. $backto = common_local_url($action, $args);
  105. }
  106. common_ensure_session();
  107. $_SESSION['openid_immediate_backto'] = $backto;
  108. oid_authenticate($openid_url,
  109. 'finishimmediate',
  110. true);
  111. }
  112. function oid_authenticate($openid_url, $returnto, $immediate=false)
  113. {
  114. $consumer = oid_consumer();
  115. if (!$consumer) {
  116. // TRANS: OpenID plugin server error.
  117. common_server_error(_m('Cannot instantiate OpenID consumer object.'));
  118. return false;
  119. }
  120. common_ensure_session();
  121. $auth_request = $consumer->begin($openid_url);
  122. // Handle failure status return values.
  123. if (!$auth_request) {
  124. common_log(LOG_ERR, __METHOD__ . ": mystery fail contacting $openid_url");
  125. // TRANS: OpenID plugin message. Given when an OpenID is not valid.
  126. return _m('Not a valid OpenID.');
  127. } else if (Auth_OpenID::isFailure($auth_request)) {
  128. common_log(LOG_ERR, __METHOD__ . ": OpenID fail to $openid_url: $auth_request->message");
  129. // TRANS: OpenID plugin server error. Given when the OpenID authentication request fails.
  130. // TRANS: %s is the failure message.
  131. return sprintf(_m('OpenID failure: %s.'), $auth_request->message);
  132. }
  133. $sreg_request = Auth_OpenID_SRegRequest::build(// Required
  134. array(),
  135. // Optional
  136. array('nickname',
  137. 'email',
  138. 'fullname',
  139. 'language',
  140. 'timezone',
  141. 'postcode',
  142. 'country'));
  143. if ($sreg_request) {
  144. $auth_request->addExtension($sreg_request);
  145. }
  146. $requiredTeam = common_config('openid', 'required_team');
  147. if ($requiredTeam) {
  148. // LaunchPad OpenID extension
  149. $team_request = new Auth_OpenID_TeamsRequest(array($requiredTeam));
  150. if ($team_request) {
  151. $auth_request->addExtension($team_request);
  152. }
  153. }
  154. $trust_root = common_root_url(true);
  155. $process_url = common_local_url($returnto);
  156. // Net::OpenID::Server as used on LiveJournal appears to incorrectly
  157. // reject POST requests for data submissions that OpenID 1.1 specs
  158. // as GET, although 2.0 allows them:
  159. // https://rt.cpan.org/Public/Bug/Display.html?id=42202
  160. //
  161. // Our OpenID libraries would have switched in the redirect automatically
  162. // if it were detecting 1.1 compatibility mode, however the server is
  163. // advertising itself as 2.0-compatible, so we got switched to the POST.
  164. //
  165. // Since the GET should always work anyway, we'll just take out the
  166. // autosubmitter for now.
  167. //
  168. //if ($auth_request->shouldSendRedirect()) {
  169. $redirect_url = $auth_request->redirectURL($trust_root,
  170. $process_url,
  171. $immediate);
  172. if (!$redirect_url) {
  173. } else if (Auth_OpenID::isFailure($redirect_url)) {
  174. // TRANS: OpenID plugin server error. Given when the OpenID authentication request cannot be redirected.
  175. // TRANS: %s is the failure message.
  176. return sprintf(_m('Could not redirect to server: %s.'), $redirect_url->message);
  177. } else {
  178. common_redirect($redirect_url, 303);
  179. }
  180. /*
  181. } else {
  182. // Generate form markup and render it.
  183. $form_id = 'openid_message';
  184. $form_html = $auth_request->formMarkup($trust_root, $process_url,
  185. $immediate, array('id' => $form_id));
  186. // XXX: This is cheap, but things choke if we don't escape ampersands
  187. // in the HTML attributes
  188. $form_html = preg_replace('/&/', '&amp;', $form_html);
  189. // Display an error if the form markup couldn't be generated;
  190. // otherwise, render the HTML.
  191. if (Auth_OpenID::isFailure($form_html)) {
  192. // TRANS: OpenID plugin server error if the form markup could not be generated.
  193. // TRANS: %s is the failure message.
  194. common_server_error(sprintf(_m('Could not create OpenID form: %s'), $form_html->message));
  195. } else {
  196. $action = new AutosubmitAction(); // see below
  197. $action->form_html = $form_html;
  198. $action->form_id = $form_id;
  199. $action->prepare(array('action' => 'autosubmit'));
  200. $action->handle(array('action' => 'autosubmit'));
  201. }
  202. }
  203. */
  204. }
  205. // Half-assed attempt at a module-private function
  206. function _oid_print_instructions()
  207. {
  208. common_element('div', 'instructions',
  209. // TRANS: OpenID plugin user instructions.
  210. _m('This form should automatically submit itself. '.
  211. 'If not, click the submit button to go to your '.
  212. 'OpenID provider.'));
  213. }
  214. /**
  215. * Update a user from sreg parameters
  216. * @param User $user
  217. * @param array $sreg fields from OpenID sreg response
  218. * @access private
  219. */
  220. function oid_update_user($user, $sreg)
  221. {
  222. $profile = $user->getProfile();
  223. $orig_profile = clone($profile);
  224. if (!empty($sreg['fullname']) && strlen($sreg['fullname']) <= 255) {
  225. $profile->fullname = $sreg['fullname'];
  226. }
  227. if (!empty($sreg['country'])) {
  228. if ($sreg['postcode']) {
  229. // XXX: use postcode to get city and region
  230. // XXX: also, store postcode somewhere -- it's valuable!
  231. $profile->location = $sreg['postcode'] . ', ' . $sreg['country'];
  232. } else {
  233. $profile->location = $sreg['country'];
  234. }
  235. }
  236. // XXX save language if it's passed
  237. // XXX save timezone if it's passed
  238. if (!$profile->update($orig_profile)) {
  239. // TRANS: OpenID plugin server error.
  240. common_server_error(_m('Error saving the profile.'));
  241. return false;
  242. }
  243. $orig_user = clone($user);
  244. if (!empty($sreg['email']) && Validate::email($sreg['email'], common_config('email', 'check_domain'))) {
  245. $user->email = $sreg['email'];
  246. }
  247. if (!$user->update($orig_user)) {
  248. // TRANS: OpenID plugin server error.
  249. common_server_error(_m('Error saving the user.'));
  250. return false;
  251. }
  252. return true;
  253. }
  254. function oid_assert_allowed($url)
  255. {
  256. $blacklist = common_config('openid', 'blacklist');
  257. $whitelist = common_config('openid', 'whitelist');
  258. if (empty($blacklist)) {
  259. $blacklist = array();
  260. }
  261. if (empty($whitelist)) {
  262. $whitelist = array();
  263. }
  264. foreach ($blacklist as $pattern) {
  265. if (preg_match("/$pattern/", $url)) {
  266. common_log(LOG_INFO, "Matched OpenID blacklist pattern {$pattern} with {$url}");
  267. foreach ($whitelist as $exception) {
  268. if (preg_match("/$exception/", $url)) {
  269. common_log(LOG_INFO, "Matched OpenID whitelist pattern {$exception} with {$url}");
  270. return;
  271. }
  272. }
  273. // TRANS: OpenID plugin client exception (403).
  274. throw new ClientException(_m('Unauthorized URL used for OpenID login.'), 403);
  275. }
  276. }
  277. return;
  278. }
  279. /**
  280. * Check the teams available in the given OpenID response
  281. * Using Launchpad's OpenID teams extension
  282. *
  283. * @return boolean whether this user is acceptable
  284. */
  285. function oid_check_teams($response)
  286. {
  287. $requiredTeam = common_config('openid', 'required_team');
  288. if ($requiredTeam) {
  289. $team_resp = new Auth_OpenID_TeamsResponse($response);
  290. if ($team_resp) {
  291. $teams = $team_resp->getTeams();
  292. } else {
  293. $teams = array();
  294. }
  295. $match = in_array($requiredTeam, $teams);
  296. $is = $match ? 'is' : 'is not';
  297. common_log(LOG_DEBUG, "Remote user $is in required team $requiredTeam: [" . implode(', ', $teams) . "]");
  298. return $match;
  299. }
  300. return true;
  301. }
  302. class AutosubmitAction extends Action
  303. {
  304. var $form_html = null;
  305. var $form_id = null;
  306. function handle($args)
  307. {
  308. parent::handle($args);
  309. $this->showPage();
  310. }
  311. function title()
  312. {
  313. // TRANS: Title
  314. return _m('OpenID Login Submission');
  315. }
  316. function showContent()
  317. {
  318. $this->raw('<p style="margin: 20px 80px">');
  319. // @todo FIXME: This would be better using standard CSS class, but the present theme's a bit scary.
  320. $this->element('img', array('src' => Theme::path('images/icons/icon_processing.gif', 'base'),
  321. // for some reason the base CSS sets <img>s as block display?!
  322. 'style' => 'display: inline'));
  323. // TRANS: OpenID plugin message used while requesting authorization user's OpenID login provider.
  324. $this->text(_m('Requesting authorization from your login provider...'));
  325. $this->raw('</p>');
  326. $this->raw('<p style="margin-top: 60px; font-style: italic">');
  327. // TRANS: OpenID plugin message. User instruction while requesting authorization user's OpenID login provider.
  328. $this->text(_m('If you are not redirected to your login provider in a few seconds, try pushing the button below.'));
  329. $this->raw('</p>');
  330. $this->raw($this->form_html);
  331. }
  332. function showScripts()
  333. {
  334. parent::showScripts();
  335. $this->element('script', null,
  336. 'document.getElementById(\'' . $this->form_id . '\').submit();');
  337. }
  338. }