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.
 
 
 
 
 
 

351 lines
10 KiB

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