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.
 
 
 
 
 
 

311 lines
8.9 KiB

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