finishopenidlogin.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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 INSTALLDIR.'/plugins/OpenID/openid.php';
  23. class FinishopenidloginAction extends Action
  24. {
  25. public $error = null;
  26. public $username = null;
  27. public $message = null;
  28. public function handle()
  29. {
  30. parent::handle();
  31. if (common_is_real_login()) {
  32. // TRANS: Client error message trying to log on with OpenID while already logged on.
  33. $this->clientError(_m('Already logged in.'));
  34. } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
  35. $token = $this->trimmed('token');
  36. if (!$token || $token != common_session_token()) {
  37. // TRANS: Message given when there is a problem with the user's session token.
  38. $this->showForm(_m('There was a problem with your session token. Try again, please.'));
  39. return;
  40. }
  41. if ($this->arg('create')) {
  42. if (!$this->boolean('license')) {
  43. // TRANS: Message given if user does not agree with the site's license.
  44. $this->showForm(
  45. _m('You cannot register if you do not agree to the license.'),
  46. $this->trimmed('newname')
  47. );
  48. return;
  49. }
  50. $this->createNewUser();
  51. } elseif ($this->arg('connect')) {
  52. $this->connectUser();
  53. } else {
  54. // TRANS: Messag given on an unknown error.
  55. $this->showForm(
  56. _m('An unknown error has occured.'),
  57. $this->trimmed('newname')
  58. );
  59. }
  60. } else {
  61. $this->tryLogin();
  62. }
  63. }
  64. public function showPageNotice()
  65. {
  66. if ($this->error) {
  67. $this->element('div', ['class' => 'error'], $this->error);
  68. } else {
  69. $this->element('div', 'instructions',
  70. // TRANS: Instructions given after a first successful logon using OpenID.
  71. // TRANS: %s is the site name.
  72. sprintf(_m('This is the first time you have logged into %s so we must connect your OpenID to a local account. You can either create a new account, or connect with your existing account, if you have one.'), common_config('site', 'name')));
  73. }
  74. }
  75. public function title()
  76. {
  77. // TRANS: Title
  78. return _m('TITLE', 'OpenID Account Setup');
  79. }
  80. public function showForm($error=null, $username=null)
  81. {
  82. $this->error = $error;
  83. $this->username = $username;
  84. $this->showPage();
  85. }
  86. /**
  87. * @fixme much of this duplicates core code, which is very fragile.
  88. * Should probably be replaced with an extensible mini version of
  89. * the core registration form.
  90. */
  91. public function showContent()
  92. {
  93. if (!empty($this->message_text)) {
  94. $this->element('div', ['class' => 'error'], $this->message_text);
  95. return;
  96. }
  97. // We don't recognize this OpenID, so we're going to give the user
  98. // two options, each in its own mini-form.
  99. //
  100. // First, they can create a new account using their OpenID auth
  101. // info. The profile will be pre-populated with whatever name,
  102. // email, and location we can get from the OpenID provider, so
  103. // all we ask for is the license confirmation.
  104. $this->elementStart('form', ['method' => 'post',
  105. 'id' => 'account_create',
  106. 'class' => 'form_settings',
  107. 'action' => common_local_url('finishopenidlogin')]);
  108. $this->hidden('token', common_session_token());
  109. $this->elementStart('fieldset', ['id' => 'form_openid_createaccount']);
  110. $this->element('legend', null,
  111. // TRANS: Fieldset legend.
  112. _m('Create new account'));
  113. $this->element('p', null,
  114. // TRANS: Form guide.
  115. _m('Create a new user with this nickname.'));
  116. $this->elementStart('ul', 'form_data');
  117. // Hook point for captcha etc
  118. Event::handle('StartRegistrationFormData', [$this]);
  119. $this->elementStart('li');
  120. // TRANS: Field label.
  121. $this->input('newname',
  122. _m('New nickname'),
  123. ($this->username) ? $this->username : '',
  124. // TRANS: Field title.
  125. _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
  126. $this->elementEnd('li');
  127. $this->elementStart('li');
  128. // TRANS: Field label.
  129. $this->input('email', _m('Email'),
  130. $this->getEmail(),
  131. // TRANS: Field title.
  132. _m('Used only for updates, announcements, '.
  133. 'and password recovery.'));
  134. $this->elementEnd('li');
  135. // Hook point for captcha etc
  136. Event::handle('EndRegistrationFormData', [$this]);
  137. $this->elementStart('li');
  138. $this->element('input', ['type' => 'checkbox',
  139. 'id' => 'license',
  140. 'class' => 'checkbox',
  141. 'name' => 'license',
  142. 'value' => 'true']);
  143. $this->elementStart('label', ['for' => 'license',
  144. 'class' => 'checkbox']);
  145. // TRANS: OpenID plugin link text.
  146. // TRANS: %s is a link to a license with the license name as link text.
  147. $message = _m('My text and files are available under %s ' .
  148. 'except this private data: password, ' .
  149. 'email address, IM address, and phone number.');
  150. $link = '<a href="' .
  151. htmlspecialchars(common_config('license', 'url')) .
  152. '">' .
  153. htmlspecialchars(common_config('license', 'title')) .
  154. '</a>';
  155. $this->raw(sprintf(htmlspecialchars($message), $link));
  156. $this->elementEnd('label');
  157. $this->elementEnd('li');
  158. $this->elementEnd('ul');
  159. // TRANS: Button label in form in which to create a new user on the site for an OpenID.
  160. $this->submit('create', _m('BUTTON', 'Create'));
  161. $this->elementEnd('fieldset');
  162. $this->elementEnd('form');
  163. // The second option is to attach this OpenID to an existing account
  164. // on the local system, which they need to provide a password for.
  165. $this->elementStart('form', ['method' => 'post',
  166. 'id' => 'account_connect',
  167. 'class' => 'form_settings',
  168. 'action' => common_local_url('finishopenidlogin')]);
  169. $this->hidden('token', common_session_token());
  170. $this->elementStart('fieldset', ['id' => 'form_openid_createaccount']);
  171. $this->element('legend', null,
  172. // TRANS: Used as form legend for form in which to connect an OpenID to an existing user on the site.
  173. _m('Connect existing account'));
  174. $this->element('p', null,
  175. // TRANS: User instructions for form in which to connect an OpenID to an existing user on the site.
  176. _m('If you already have an account, login with your username and password to connect it to your OpenID.'));
  177. $this->elementStart('ul', 'form_data');
  178. $this->elementStart('li');
  179. // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
  180. $this->input('nickname', _m('Existing nickname'));
  181. $this->elementEnd('li');
  182. $this->elementStart('li');
  183. // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
  184. $this->password('password', _m('Password'));
  185. $this->elementEnd('li');
  186. $this->elementStart('li');
  187. // TRANS: Field label in form in which to connect an OpenID to an existing user on the site.
  188. $this->checkbox('openid-synch', _m('Synchronize Account'), false,
  189. _m('Synchronize GNU social profile with this OpenID identity.'));
  190. $this->elementEnd('li');
  191. $this->elementEnd('ul');
  192. // TRANS: Button text in form in which to connect an OpenID to an existing user on the site.
  193. $this->submit('connect', _m('BUTTON', 'Connect'));
  194. $this->elementEnd('fieldset');
  195. $this->elementEnd('form');
  196. }
  197. /**
  198. * Get specified e-mail from the form, or the OpenID sreg info, or the
  199. * invite code.
  200. *
  201. * @return string
  202. */
  203. public function getEmail()
  204. {
  205. $email = $this->trimmed('email');
  206. if (!empty($email)) {
  207. return $email;
  208. }
  209. // Pull from openid thingy
  210. list($display, $canonical, $sreg) = $this->getSavedValues();
  211. if (!empty($sreg['email'])) {
  212. return $sreg['email'];
  213. }
  214. // Terrible hack for invites...
  215. if (common_config('site', 'inviteonly')) {
  216. $code = $_SESSION['invitecode'];
  217. if ($code) {
  218. $invite = Invitation::getKV($code);
  219. if ($invite && $invite->address_type == 'email') {
  220. return $invite->address;
  221. }
  222. }
  223. }
  224. return '';
  225. }
  226. public function tryLogin()
  227. {
  228. $consumer = oid_consumer();
  229. $response = $consumer->complete(common_local_url('finishopenidlogin'));
  230. if ($response->status == Auth_OpenID_CANCEL) {
  231. // TRANS: Status message in case the response from the OpenID provider is that the logon attempt was cancelled.
  232. $this->message(_m('OpenID authentication cancelled.'));
  233. return;
  234. } elseif ($response->status == Auth_OpenID_FAILURE) {
  235. // TRANS: OpenID authentication failed; display the error message. %s is the error message.
  236. $this->message(sprintf(_m('OpenID authentication failed: %s.'), $response->message));
  237. } elseif ($response->status == Auth_OpenID_SUCCESS) {
  238. // This means the authentication succeeded; extract the
  239. // identity URL and Simple Registration data (if it was
  240. // returned).
  241. $display = $response->getDisplayIdentifier();
  242. $canonical = ($response->endpoint->canonicalID) ?
  243. $response->endpoint->canonicalID : $response->getDisplayIdentifier();
  244. oid_assert_allowed($display);
  245. oid_assert_allowed($canonical);
  246. $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
  247. if ($sreg_resp) {
  248. $sreg = $sreg_resp->contents();
  249. }
  250. // Launchpad teams extension
  251. if (!oid_check_teams($response)) {
  252. // TRANS: Message displayed when OpenID authentication is aborted.
  253. $this->message(_m('OpenID authentication aborted: You are not allowed to login to this site.'));
  254. return;
  255. }
  256. $user = oid_get_user($canonical);
  257. if ($user) {
  258. oid_set_last($display);
  259. // XXX: commented out at @edd's request until better
  260. // control over how data flows from OpenID provider.
  261. // oid_update_user($user, $sreg);
  262. common_set_user($user);
  263. common_real_login(true);
  264. if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
  265. common_rememberme($user);
  266. }
  267. unset($_SESSION['openid_rememberme']);
  268. $this->goHome($user->nickname);
  269. } else {
  270. $this->saveValues($display, $canonical, $sreg);
  271. $this->showForm(null, $this->bestNewNickname($display, $sreg));
  272. }
  273. }
  274. }
  275. public function message($msg)
  276. {
  277. $this->message_text = $msg;
  278. $this->showPage();
  279. }
  280. public function saveValues($display, $canonical, $sreg)
  281. {
  282. common_ensure_session();
  283. $_SESSION['openid_display'] = $display;
  284. $_SESSION['openid_canonical'] = $canonical;
  285. $_SESSION['openid_sreg'] = $sreg;
  286. }
  287. public function getSavedValues()
  288. {
  289. return [$_SESSION['openid_display'],
  290. $_SESSION['openid_canonical'],
  291. $_SESSION['openid_sreg']];
  292. }
  293. public function createNewUser()
  294. {
  295. // FIXME: save invite code before redirect, and check here
  296. if (!Event::handle('StartRegistrationTry', [$this])) {
  297. return;
  298. }
  299. if (common_config('site', 'closed')) {
  300. // TRANS: OpenID plugin message. No new user registration is allowed on the site.
  301. $this->clientError(_m('Registration not allowed.'));
  302. }
  303. $invite = null;
  304. if (common_config('site', 'inviteonly')) {
  305. $code = $_SESSION['invitecode'];
  306. if (empty($code)) {
  307. // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and none was provided.
  308. $this->clientError(_m('Registration not allowed.'));
  309. }
  310. $invite = Invitation::getKV($code);
  311. if (empty($invite)) {
  312. // TRANS: OpenID plugin message. No new user registration is allowed on the site without an invitation code, and the one provided was not valid.
  313. $this->clientError(_m('Not a valid invitation code.'));
  314. }
  315. }
  316. try {
  317. $nickname = Nickname::normalize($this->trimmed('newname'), true);
  318. } catch (NicknameException $e) {
  319. $this->showForm($e->getMessage());
  320. return;
  321. }
  322. list($display, $canonical, $sreg) = $this->getSavedValues();
  323. if (!$display || !$canonical) {
  324. // TRANS: OpenID plugin server error. A stored OpenID cannot be retrieved.
  325. $this->serverError(_m('Stored OpenID not found.'));
  326. }
  327. // Possible race condition... let's be paranoid
  328. $other = oid_get_user($canonical);
  329. if ($other) {
  330. // TRANS: OpenID plugin server error.
  331. $this->serverError(_m('Creating new account for OpenID that already has a user.'));
  332. }
  333. Event::handle('StartOpenIDCreateNewUser', [$canonical, &$sreg]);
  334. $location = '';
  335. if (!empty($sreg['country'])) {
  336. if ($sreg['postcode']) {
  337. // XXX: use postcode to get city and region
  338. // XXX: also, store postcode somewhere -- it's valuable!
  339. $location = $sreg['postcode'] . ', ' . $sreg['country'];
  340. } else {
  341. $location = $sreg['country'];
  342. }
  343. }
  344. if (!empty($sreg['fullname']) && mb_strlen($sreg['fullname']) <= 255) {
  345. $fullname = $sreg['fullname'];
  346. } else {
  347. $fullname = '';
  348. }
  349. $email = $this->getEmail();
  350. // XXX: add language
  351. // XXX: add timezone
  352. $args = ['nickname' => $nickname,
  353. 'email' => $email,
  354. 'fullname' => $fullname,
  355. 'location' => $location];
  356. if (!empty($invite)) {
  357. $args['code'] = $invite->code;
  358. }
  359. $user = User::register($args);
  360. $result = oid_link_user($user->id, $canonical, $display);
  361. Event::handle('EndOpenIDCreateNewUser', [$user, $canonical, $sreg]);
  362. oid_set_last($display);
  363. common_set_user($user);
  364. common_real_login(true);
  365. if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
  366. common_rememberme($user);
  367. }
  368. unset($_SESSION['openid_rememberme']);
  369. Event::handle('EndRegistrationTry', [$this]);
  370. common_redirect(common_local_url('showstream', ['nickname' => $user->nickname]), 303);
  371. }
  372. public function connectUser()
  373. {
  374. $nickname = $this->trimmed('nickname');
  375. $password = $this->trimmed('password');
  376. $synch = $this->boolean('openid-synch');
  377. if (!common_check_user($nickname, $password)) {
  378. // TRANS: OpenID plugin message.
  379. $this->showForm(_m('Invalid username or password.'));
  380. return;
  381. }
  382. // They're legit!
  383. $user = User::getKV('nickname', $nickname);
  384. list($display, $canonical, $sreg) = $this->getSavedValues();
  385. if (!$display || !$canonical) {
  386. // TRANS: OpenID plugin server error. A stored OpenID cannot be found.
  387. $this->serverError(_m('Stored OpenID not found.'));
  388. }
  389. $result = oid_link_user($user->id, $canonical, $display);
  390. if (!$result) {
  391. // TRANS: OpenID plugin server error. The user or user profile could not be saved.
  392. $this->serverError(_m('Error connecting user to OpenID.'));
  393. }
  394. if ($synch) {
  395. if (Event::handle('StartOpenIDUpdateUser', [$user, $canonical, &$sreg])) {
  396. oid_update_user($user, $sreg);
  397. }
  398. Event::handle('EndOpenIDUpdateUser', [$user, $canonical, $sreg]);
  399. }
  400. oid_set_last($display);
  401. common_set_user($user);
  402. common_real_login(true);
  403. if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
  404. common_rememberme($user);
  405. }
  406. unset($_SESSION['openid_rememberme']);
  407. $this->goHome($user->nickname);
  408. }
  409. public function goHome($nickname)
  410. {
  411. $url = common_get_returnto();
  412. if ($url) {
  413. // We don't have to return to it again
  414. common_set_returnto(null);
  415. $url = common_inject_session($url);
  416. } else {
  417. $url = common_local_url('all', ['nickname' => $nickname]);
  418. }
  419. common_redirect($url, 303);
  420. }
  421. public function bestNewNickname($display, $sreg)
  422. {
  423. // Try the passed-in nickname
  424. if (!empty($sreg['nickname'])) {
  425. $nickname = common_nicknamize($sreg['nickname']);
  426. if (Nickname::isValid($nickname, true)) {
  427. return $nickname;
  428. }
  429. }
  430. // Try the full name
  431. if (!empty($sreg['fullname'])) {
  432. $fullname = common_nicknamize($sreg['fullname']);
  433. if (Nickname::isValid($fullname, true)) {
  434. return $fullname;
  435. }
  436. }
  437. // Try the URL
  438. $from_url = $this->openidToNickname($display);
  439. if ($from_url && Nickname::isValid($from_url, true)) {
  440. return $from_url;
  441. }
  442. // XXX: others?
  443. return null;
  444. }
  445. public function openidToNickname($openid)
  446. {
  447. if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
  448. return $this->xriToNickname($openid);
  449. } else {
  450. return $this->urlToNickname($openid);
  451. }
  452. }
  453. // We try to use an OpenID URL as a legal StatusNet user name in this order
  454. // 1. Plain hostname, like http://evanp.myopenid.com/
  455. // 2. One element in path, like http://profile.typekey.com/EvanProdromou/
  456. // or http://getopenid.com/evanprodromou
  457. public function urlToNickname($openid)
  458. {
  459. return common_url_to_nickname($openid);
  460. }
  461. public function xriToNickname($xri)
  462. {
  463. $base = $this->xriBase($xri);
  464. if (!$base) {
  465. return null;
  466. } else {
  467. // =evan.prodromou
  468. // or @gratis*evan.prodromou
  469. $parts = explode('*', substr($base, 1));
  470. return common_nicknamize(array_pop($parts));
  471. }
  472. }
  473. public function xriBase($xri)
  474. {
  475. if (substr($xri, 0, 6) == 'xri://') {
  476. return substr($xri, 6);
  477. } else {
  478. return $xri;
  479. }
  480. }
  481. }