PageRenderTime 58ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/plugins/OpenID/openid.php

https://gitlab.com/BeS/io.schiessle.org
PHP | 398 lines | 248 code | 56 blank | 94 comment | 34 complexity | aee169cc7bf31ac7d76673539dbbce35 MD5 | raw file
  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. $openid_url = Auth_OpenID::normalizeUrl($openid_url);
  115. if (!common_valid_http_url($openid_url)) {
  116. throw new ClientException(_m('No valid URL provided for OpenID.'));
  117. }
  118. $consumer = oid_consumer();
  119. if (!$consumer) {
  120. // TRANS: OpenID plugin server error.
  121. throw new ServerException(_m('Cannot instantiate OpenID consumer object.'));
  122. }
  123. common_ensure_session();
  124. $auth_request = $consumer->begin($openid_url);
  125. // Handle failure status return values.
  126. if (!$auth_request) {
  127. common_log(LOG_ERR, __METHOD__ . ": mystery fail contacting $openid_url");
  128. // TRANS: OpenID plugin message. Given when an OpenID is not valid.
  129. throw new ServerException(_m('Not a valid OpenID.'));
  130. } else if (Auth_OpenID::isFailure($auth_request)) {
  131. common_log(LOG_ERR, __METHOD__ . ": OpenID fail to $openid_url: $auth_request->message");
  132. // TRANS: OpenID plugin server error. Given when the OpenID authentication request fails.
  133. // TRANS: %s is the failure message.
  134. throw new ServerException(sprintf(_m('OpenID failure: %s.'), $auth_request->message));
  135. }
  136. $sreg_request = Auth_OpenID_SRegRequest::build(// Required
  137. array(),
  138. // Optional
  139. array('nickname',
  140. 'email',
  141. 'fullname',
  142. 'language',
  143. 'timezone',
  144. 'postcode',
  145. 'country'));
  146. if ($sreg_request) {
  147. $auth_request->addExtension($sreg_request);
  148. }
  149. $requiredTeam = common_config('openid', 'required_team');
  150. if ($requiredTeam) {
  151. // LaunchPad OpenID extension
  152. $team_request = new Auth_OpenID_TeamsRequest(array($requiredTeam));
  153. if ($team_request) {
  154. $auth_request->addExtension($team_request);
  155. }
  156. }
  157. $trust_root = common_root_url(true);
  158. $process_url = common_local_url($returnto);
  159. // Net::OpenID::Server as used on LiveJournal appears to incorrectly
  160. // reject POST requests for data submissions that OpenID 1.1 specs
  161. // as GET, although 2.0 allows them:
  162. // https://rt.cpan.org/Public/Bug/Display.html?id=42202
  163. //
  164. // Our OpenID libraries would have switched in the redirect automatically
  165. // if it were detecting 1.1 compatibility mode, however the server is
  166. // advertising itself as 2.0-compatible, so we got switched to the POST.
  167. //
  168. // Since the GET should always work anyway, we'll just take out the
  169. // autosubmitter for now.
  170. //
  171. //if ($auth_request->shouldSendRedirect()) {
  172. $redirect_url = $auth_request->redirectURL($trust_root,
  173. $process_url,
  174. $immediate);
  175. if (Auth_OpenID::isFailure($redirect_url)) {
  176. // TRANS: OpenID plugin server error. Given when the OpenID authentication request cannot be redirected.
  177. // TRANS: %s is the failure message.
  178. throw new ServerException(sprintf(_m('Could not redirect to server: %s.'), $redirect_url->message));
  179. }
  180. common_redirect($redirect_url, 303);
  181. /*
  182. } else {
  183. // Generate form markup and render it.
  184. $form_id = 'openid_message';
  185. $form_html = $auth_request->formMarkup($trust_root, $process_url,
  186. $immediate, array('id' => $form_id));
  187. // XXX: This is cheap, but things choke if we don't escape ampersands
  188. // in the HTML attributes
  189. $form_html = preg_replace('/&/', '&amp;', $form_html);
  190. // Display an error if the form markup couldn't be generated;
  191. // otherwise, render the HTML.
  192. if (Auth_OpenID::isFailure($form_html)) {
  193. // TRANS: OpenID plugin server error if the form markup could not be generated.
  194. // TRANS: %s is the failure message.
  195. common_server_error(sprintf(_m('Could not create OpenID form: %s'), $form_html->message));
  196. } else {
  197. $action = new AutosubmitAction(); // see below
  198. $action->form_html = $form_html;
  199. $action->form_id = $form_id;
  200. $action->prepare(array('action' => 'autosubmit'));
  201. $action->handle(array('action' => 'autosubmit'));
  202. }
  203. }
  204. */
  205. }
  206. // Half-assed attempt at a module-private function
  207. function _oid_print_instructions()
  208. {
  209. common_element('div', 'instructions',
  210. // TRANS: OpenID plugin user instructions.
  211. _m('This form should automatically submit itself. '.
  212. 'If not, click the submit button to go to your '.
  213. 'OpenID provider.'));
  214. }
  215. /**
  216. * Update a user from sreg parameters
  217. * @param User $user
  218. * @param array $sreg fields from OpenID sreg response
  219. * @access private
  220. */
  221. function oid_update_user($user, $sreg)
  222. {
  223. $profile = $user->getProfile();
  224. $orig_profile = clone($profile);
  225. if (!empty($sreg['fullname']) && strlen($sreg['fullname']) <= 255) {
  226. $profile->fullname = $sreg['fullname'];
  227. }
  228. if (!empty($sreg['country'])) {
  229. if ($sreg['postcode']) {
  230. // XXX: use postcode to get city and region
  231. // XXX: also, store postcode somewhere -- it's valuable!
  232. $profile->location = $sreg['postcode'] . ', ' . $sreg['country'];
  233. } else {
  234. $profile->location = $sreg['country'];
  235. }
  236. }
  237. // XXX save language if it's passed
  238. // XXX save timezone if it's passed
  239. if (!$profile->update($orig_profile)) {
  240. // TRANS: OpenID plugin server error.
  241. common_server_error(_m('Error saving the profile.'));
  242. return false;
  243. }
  244. $orig_user = clone($user);
  245. if (!empty($sreg['email']) && Validate::email($sreg['email'], common_config('email', 'check_domain'))) {
  246. $user->email = $sreg['email'];
  247. }
  248. if (!$user->update($orig_user)) {
  249. // TRANS: OpenID plugin server error.
  250. common_server_error(_m('Error saving the user.'));
  251. return false;
  252. }
  253. return true;
  254. }
  255. function oid_assert_allowed($url)
  256. {
  257. $blacklist = common_config('openid', 'blacklist');
  258. $whitelist = common_config('openid', 'whitelist');
  259. if (empty($blacklist)) {
  260. $blacklist = array();
  261. }
  262. if (empty($whitelist)) {
  263. $whitelist = array();
  264. }
  265. foreach ($blacklist as $pattern) {
  266. if (preg_match("/$pattern/", $url)) {
  267. common_log(LOG_INFO, "Matched OpenID blacklist pattern {$pattern} with {$url}");
  268. foreach ($whitelist as $exception) {
  269. if (preg_match("/$exception/", $url)) {
  270. common_log(LOG_INFO, "Matched OpenID whitelist pattern {$exception} with {$url}");
  271. return;
  272. }
  273. }
  274. // TRANS: OpenID plugin client exception (403).
  275. throw new ClientException(_m('Unauthorized URL used for OpenID login.'), 403);
  276. }
  277. }
  278. return;
  279. }
  280. /**
  281. * Check the teams available in the given OpenID response
  282. * Using Launchpad's OpenID teams extension
  283. *
  284. * @return boolean whether this user is acceptable
  285. */
  286. function oid_check_teams($response)
  287. {
  288. $requiredTeam = common_config('openid', 'required_team');
  289. if ($requiredTeam) {
  290. $team_resp = new Auth_OpenID_TeamsResponse($response);
  291. if ($team_resp) {
  292. $teams = $team_resp->getTeams();
  293. } else {
  294. $teams = array();
  295. }
  296. $match = in_array($requiredTeam, $teams);
  297. $is = $match ? 'is' : 'is not';
  298. common_log(LOG_DEBUG, "Remote user $is in required team $requiredTeam: [" . implode(', ', $teams) . "]");
  299. return $match;
  300. }
  301. return true;
  302. }
  303. class AutosubmitAction extends Action
  304. {
  305. var $form_html = null;
  306. var $form_id = null;
  307. function handle($args)
  308. {
  309. parent::handle($args);
  310. $this->showPage();
  311. }
  312. function title()
  313. {
  314. // TRANS: Title
  315. return _m('OpenID Login Submission');
  316. }
  317. function showContent()
  318. {
  319. $this->raw('<p style="margin: 20px 80px">');
  320. // @todo FIXME: This would be better using standard CSS class, but the present theme's a bit scary.
  321. $this->element('img', array('src' => Theme::path('images/icons/icon_processing.gif', 'base'),
  322. // for some reason the base CSS sets <img>s as block display?!
  323. 'style' => 'display: inline'));
  324. // TRANS: OpenID plugin message used while requesting authorization user's OpenID login provider.
  325. $this->text(_m('Requesting authorization from your login provider...'));
  326. $this->raw('</p>');
  327. $this->raw('<p style="margin-top: 60px; font-style: italic">');
  328. // TRANS: OpenID plugin message. User instruction while requesting authorization user's OpenID login provider.
  329. $this->text(_m('If you are not redirected to your login provider in a few seconds, try pushing the button below.'));
  330. $this->raw('</p>');
  331. $this->raw($this->form_html);
  332. }
  333. function showScripts()
  334. {
  335. parent::showScripts();
  336. $this->element('script', null,
  337. 'document.getElementById(\'' . $this->form_id . '\').submit();');
  338. }
  339. }