finishopenidlogin.php 20 KB

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