Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

348 lines
9.8KB

  1. <?php
  2. /**
  3. * @file src/Module/Login.php
  4. */
  5. namespace Friendica\Module;
  6. use Exception;
  7. use Friendica\BaseModule;
  8. use Friendica\Core\Addon;
  9. use Friendica\Core\Authentication;
  10. use Friendica\Core\Config;
  11. use Friendica\Core\L10n;
  12. use Friendica\Core\Logger;
  13. use Friendica\Core\Renderer;
  14. use Friendica\Core\System;
  15. use Friendica\Database\DBA;
  16. use Friendica\Model\User;
  17. use Friendica\Util\DateTimeFormat;
  18. use Friendica\Util\Network;
  19. use Friendica\Util\Strings;
  20. use LightOpenID;
  21. /**
  22. * Login module
  23. *
  24. * @author Hypolite Petovan <hypolite@mrpetovan.com>
  25. */
  26. class Login extends BaseModule
  27. {
  28. public static function content()
  29. {
  30. $a = self::getApp();
  31. if (!empty($_SESSION['theme'])) {
  32. unset($_SESSION['theme']);
  33. }
  34. if (!empty($_SESSION['mobile-theme'])) {
  35. unset($_SESSION['mobile-theme']);
  36. }
  37. if (local_user()) {
  38. $a->internalRedirect();
  39. }
  40. return self::form(defaults($_SESSION, 'return_path', null), intval(Config::get('config', 'register_policy')) !== REGISTER_CLOSED);
  41. }
  42. public static function post()
  43. {
  44. $return_path = $_SESSION['return_path'];
  45. session_unset();
  46. $_SESSION['return_path'] = $return_path;
  47. // OpenId Login
  48. if (
  49. empty($_POST['password'])
  50. && (
  51. !empty($_POST['openid_url'])
  52. || !empty($_POST['username'])
  53. )
  54. ) {
  55. $openid_url = trim(defaults($_POST, 'openid_url', $_POST['username']));
  56. self::openIdAuthentication($openid_url, !empty($_POST['remember']));
  57. }
  58. if (!empty($_POST['auth-params']) && $_POST['auth-params'] === 'login') {
  59. self::passwordAuthentication(
  60. trim($_POST['username']),
  61. trim($_POST['password']),
  62. !empty($_POST['remember'])
  63. );
  64. }
  65. }
  66. /**
  67. * Attempts to authenticate using OpenId
  68. *
  69. * @param string $openid_url OpenID URL string
  70. * @param bool $remember Whether to set the session remember flag
  71. */
  72. private static function openIdAuthentication($openid_url, $remember)
  73. {
  74. $noid = Config::get('system', 'no_openid');
  75. $a = self::getApp();
  76. // if it's an email address or doesn't resolve to a URL, fail.
  77. if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
  78. notice(L10n::t('Login failed.') . EOL);
  79. $a->internalRedirect();
  80. // NOTREACHED
  81. }
  82. // Otherwise it's probably an openid.
  83. try {
  84. $openid = new LightOpenID($a->getHostName());
  85. $openid->identity = $openid_url;
  86. $_SESSION['openid'] = $openid_url;
  87. $_SESSION['remember'] = $remember;
  88. $openid->returnUrl = $a->getBaseURL(true) . '/openid';
  89. System::externalRedirect($openid->authUrl());
  90. } catch (Exception $e) {
  91. notice(L10n::t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . '<br /><br >' . L10n::t('The error message was:') . ' ' . $e->getMessage());
  92. }
  93. }
  94. /**
  95. * Attempts to authenticate using login/password
  96. *
  97. * @param string $username User name
  98. * @param string $password Clear password
  99. * @param bool $remember Whether to set the session remember flag
  100. */
  101. private static function passwordAuthentication($username, $password, $remember)
  102. {
  103. $record = null;
  104. $addon_auth = [
  105. 'username' => $username,
  106. 'password' => $password,
  107. 'authenticated' => 0,
  108. 'user_record' => null
  109. ];
  110. $a = self::getApp();
  111. /*
  112. * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
  113. * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
  114. * and later addons should not interfere with an earlier one that succeeded.
  115. */
  116. Addon::callHooks('authenticate', $addon_auth);
  117. try {
  118. if ($addon_auth['authenticated']) {
  119. $record = $addon_auth['user_record'];
  120. if (empty($record)) {
  121. throw new Exception(L10n::t('Login failed.'));
  122. }
  123. } else {
  124. $record = DBA::selectFirst('user', [],
  125. ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
  126. );
  127. }
  128. } catch (Exception $e) {
  129. Logger::log('authenticate: failed login attempt: ' . Strings::escapeTags($username) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
  130. info('Login failed. Please check your credentials.' . EOL);
  131. $a->internalRedirect();
  132. }
  133. if (!$remember) {
  134. Authentication::setCookie(0); // 0 means delete on browser exit
  135. }
  136. // if we haven't failed up this point, log them in.
  137. $_SESSION['remember'] = $remember;
  138. $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
  139. Authentication::setAuthenticatedSessionForUser($record, true, true);
  140. if (!empty($_SESSION['return_path'])) {
  141. $return_path = $_SESSION['return_path'];
  142. unset($_SESSION['return_path']);
  143. } else {
  144. $return_path = '';
  145. }
  146. $a->internalRedirect($return_path);
  147. }
  148. /**
  149. * @brief Tries to auth the user from the cookie or session
  150. *
  151. * @todo Should be moved to Friendica\Core\Session when it's created
  152. */
  153. public static function sessionAuth()
  154. {
  155. $a = self::getApp();
  156. // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
  157. if (isset($_COOKIE["Friendica"])) {
  158. $data = json_decode($_COOKIE["Friendica"]);
  159. if (isset($data->uid)) {
  160. $user = DBA::selectFirst('user', [],
  161. [
  162. 'uid' => $data->uid,
  163. 'blocked' => false,
  164. 'account_expired' => false,
  165. 'account_removed' => false,
  166. 'verified' => true,
  167. ]
  168. );
  169. if (DBA::isResult($user)) {
  170. if ($data->hash != Authentication::getCookieHashForUser($user)) {
  171. Logger::log("Hash for user " . $data->uid . " doesn't fit.");
  172. Authentication::deleteSession();
  173. $a->internalRedirect();
  174. }
  175. // Renew the cookie
  176. // Expires after 7 days by default,
  177. // can be set via system.auth_cookie_lifetime
  178. $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
  179. Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
  180. // Do the authentification if not done by now
  181. if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
  182. Authentication::setAuthenticatedSessionForUser($user);
  183. if (Config::get('system', 'paranoia')) {
  184. $_SESSION['addr'] = $data->ip;
  185. }
  186. }
  187. }
  188. }
  189. }
  190. if (!empty($_SESSION['authenticated'])) {
  191. if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
  192. $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
  193. if (DBA::isResult($contact)) {
  194. self::getApp()->contact = $contact;
  195. }
  196. }
  197. if (!empty($_SESSION['uid'])) {
  198. // already logged in user returning
  199. $check = Config::get('system', 'paranoia');
  200. // extra paranoia - if the IP changed, log them out
  201. if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
  202. Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
  203. $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
  204. Authentication::deleteSession();
  205. $a->internalRedirect();
  206. }
  207. $user = DBA::selectFirst('user', [],
  208. [
  209. 'uid' => $_SESSION['uid'],
  210. 'blocked' => false,
  211. 'account_expired' => false,
  212. 'account_removed' => false,
  213. 'verified' => true,
  214. ]
  215. );
  216. if (!DBA::isResult($user)) {
  217. Authentication::deleteSession();
  218. $a->internalRedirect();
  219. }
  220. // Make sure to refresh the last login time for the user if the user
  221. // stays logged in for a long time, e.g. with "Remember Me"
  222. $login_refresh = false;
  223. if (empty($_SESSION['last_login_date'])) {
  224. $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
  225. }
  226. if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
  227. $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
  228. $login_refresh = true;
  229. }
  230. Authentication::setAuthenticatedSessionForUser($user, false, false, $login_refresh);
  231. }
  232. }
  233. }
  234. /**
  235. * @brief Wrapper for adding a login box.
  236. *
  237. * @param string $return_path The path relative to the base the user should be sent
  238. * back to after login completes
  239. * @param bool $register If $register == true provide a registration link.
  240. * This will most always depend on the value of config.register_policy.
  241. * @param array $hiddens optional
  242. *
  243. * @return string Returns the complete html for inserting into the page
  244. *
  245. * @hooks 'login_hook' string $o
  246. */
  247. public static function form($return_path = null, $register = false, $hiddens = [])
  248. {
  249. $a = self::getApp();
  250. $o = '';
  251. $reg = false;
  252. if ($register) {
  253. $reg = [
  254. 'title' => L10n::t('Create a New Account'),
  255. 'desc' => L10n::t('Register')
  256. ];
  257. }
  258. $noid = Config::get('system', 'no_openid');
  259. if (is_null($return_path)) {
  260. $return_path = $a->query_string;
  261. }
  262. if (local_user()) {
  263. $tpl = Renderer::getMarkupTemplate('logout.tpl');
  264. } else {
  265. $a->page['htmlhead'] .= Renderer::replaceMacros(
  266. Renderer::getMarkupTemplate('login_head.tpl'),
  267. [
  268. '$baseurl' => $a->getBaseURL(true)
  269. ]
  270. );
  271. $tpl = Renderer::getMarkupTemplate('login.tpl');
  272. $_SESSION['return_path'] = $return_path;
  273. }
  274. $o .= Renderer::replaceMacros(
  275. $tpl,
  276. [
  277. '$dest_url' => self::getApp()->getBaseURL(true) . '/login',
  278. '$logout' => L10n::t('Logout'),
  279. '$login' => L10n::t('Login'),
  280. '$lname' => ['username', L10n::t('Nickname or Email: ') , '', ''],
  281. '$lpassword' => ['password', L10n::t('Password: '), '', ''],
  282. '$lremember' => ['remember', L10n::t('Remember me'), 0, ''],
  283. '$openid' => !$noid,
  284. '$lopenid' => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
  285. '$hiddens' => $hiddens,
  286. '$register' => $reg,
  287. '$lostpass' => L10n::t('Forgot your password?'),
  288. '$lostlink' => L10n::t('Password Reset'),
  289. '$tostitle' => L10n::t('Website Terms of Service'),
  290. '$toslink' => L10n::t('terms of service'),
  291. '$privacytitle' => L10n::t('Website Privacy Policy'),
  292. '$privacylink' => L10n::t('privacy policy'),
  293. ]
  294. );
  295. Addon::callHooks('login_hook', $o);
  296. return $o;
  297. }
  298. }