3 * @file src/Module/Login.php
5 namespace Friendica\Module;
7 use Friendica\BaseModule;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Database\DBM;
12 use Friendica\Model\User;
13 use Friendica\Util\Network;
16 require_once 'boot.php';
17 require_once 'include/datetime.php';
18 require_once 'include/security.php';
19 require_once 'include/text.php';
24 * @author Hypolite Petovan mrpetovan@gmail.com
26 class Login extends BaseModule
28 public static function content()
32 if (x($_SESSION, 'theme')) {
33 unset($_SESSION['theme']);
36 if (x($_SESSION, 'mobile-theme')) {
37 unset($_SESSION['mobile-theme']);
41 goaway(self::getApp()->get_baseurl());
44 return self::form(self::getApp()->get_baseurl(), $a->config['register_policy'] != REGISTER_CLOSED);
47 public static function post()
52 !x($_POST, 'password')
54 x($_POST, 'openid_url')
55 || x($_POST, 'username')
58 $noid = Config::get('system', 'no_openid');
60 $openid_url = trim($_POST['openid_url'] ? : $_POST['username']);
62 // if it's an email address or doesn't resolve to a URL, fail.
63 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
64 notice(L10n::t('Login failed.') . EOL);
65 goaway(self::getApp()->get_baseurl());
69 // Otherwise it's probably an openid.
71 require_once 'library/openid.php';
72 $openid = new \LightOpenID;
73 $openid->identity = $openid_url;
74 $_SESSION['openid'] = $openid_url;
75 $_SESSION['remember'] = $_POST['remember'];
76 $openid->returnUrl = self::getApp()->get_baseurl(true) . '/openid';
77 goaway($openid->authUrl());
78 } catch (Exception $e) {
79 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());
84 if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') {
88 'username' => trim($_POST['username']),
89 'password' => trim($_POST['password']),
95 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
96 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
97 * and later addons should not interfere with an earlier one that succeeded.
99 Addon::callHooks('authenticate', $addon_auth);
101 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
102 $record = $addon_auth['user_record'];
104 $user_id = User::authenticate(trim($_POST['username']), trim($_POST['password']));
106 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
110 if (!$record || !count($record)) {
111 logger('authenticate: failed login attempt: ' . notags(trim($_POST['username'])) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
112 notice(L10n::t('Login failed.') . EOL);
113 goaway(self::getApp()->get_baseurl());
116 if (!$_POST['remember']) {
117 new_cookie(0); // 0 means delete on browser exit
120 // if we haven't failed up this point, log them in.
121 $_SESSION['remember'] = $_POST['remember'];
122 $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
123 authenticate_success($record, true, true);
125 if (x($_SESSION, 'return_url')) {
126 $return_url = $_SESSION['return_url'];
127 unset($_SESSION['return_url']);
137 * @brief Tries to auth the user from the cookie or session
139 * @todo Should be moved to Friendica\Core\Session when it's created
141 public static function sessionAuth()
143 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
144 if (isset($_COOKIE["Friendica"])) {
145 $data = json_decode($_COOKIE["Friendica"]);
146 if (isset($data->uid)) {
148 $user = dba::selectFirst('user', [],
152 'account_expired' => false,
153 'account_removed' => false,
157 if (DBM::is_result($user)) {
158 if ($data->hash != cookie_hash($user)) {
159 logger("Hash for user " . $data->uid . " doesn't fit.");
161 goaway(self::getApp()->get_baseurl());
165 // Expires after 7 days by default,
166 // can be set via system.auth_cookie_lifetime
167 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
168 new_cookie($authcookiedays * 24 * 60 * 60, $user);
170 // Do the authentification if not done by now
171 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
172 authenticate_success($user);
174 if (Config::get('system', 'paranoia')) {
175 $_SESSION['addr'] = $data->ip;
182 if (isset($_SESSION) && x($_SESSION, 'authenticated')) {
183 if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
184 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
185 intval($_SESSION['visitor_id'])
187 if (DBM::is_result($r)) {
188 self::getApp()->contact = $r[0];
192 if (x($_SESSION, 'uid')) {
193 // already logged in user returning
194 $check = Config::get('system', 'paranoia');
195 // extra paranoia - if the IP changed, log them out
196 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
197 logger('Session address changed. Paranoid setting in effect, blocking session. ' .
198 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
200 goaway(self::getApp()->get_baseurl());
203 $user = dba::selectFirst('user', [],
205 'uid' => $_SESSION['uid'],
207 'account_expired' => false,
208 'account_removed' => false,
212 if (!DBM::is_result($user)) {
214 goaway(self::getApp()->get_baseurl());
217 // Make sure to refresh the last login time for the user if the user
218 // stays logged in for a long time, e.g. with "Remember Me"
219 $login_refresh = false;
220 if (!x($_SESSION['last_login_date'])) {
221 $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
223 if (strcmp(datetime_convert('UTC', 'UTC', 'now - 12 hours'), $_SESSION['last_login_date']) > 0) {
224 $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
225 $login_refresh = true;
227 authenticate_success($user, false, false, $login_refresh);
233 * @brief Wrapper for adding a login box.
235 * @param string $return_url The url relative to the base the user should be sent
236 * back to after login completes
237 * @param bool $register If $register == true provide a registration link.
238 * This will most always depend on the value of $a->config['register_policy'].
239 * @param array $hiddens optional
241 * @return string Returns the complete html for inserting into the page
243 * @hooks 'login_hook' string $o
245 public static function form($return_url = null, $register = false, $hiddens = [])
252 'title' => L10n::t('Create a New Account'),
253 'desc' => L10n::t('Register')
257 $noid = Config::get('system', 'no_openid');
259 if (is_null($return_url)) {
260 $return_url = $a->query_string;
264 $tpl = get_markup_template('logout.tpl');
266 $a->page['htmlhead'] .= replace_macros(
267 get_markup_template('login_head.tpl'),
269 '$baseurl' => $a->get_baseurl(true)
273 $tpl = get_markup_template('login.tpl');
274 $_SESSION['return_url'] = $return_url;
277 $o .= replace_macros(
280 '$dest_url' => self::getApp()->get_baseurl(true) . '/login',
281 '$logout' => L10n::t('Logout'),
282 '$login' => L10n::t('Login'),
284 '$lname' => ['username', L10n::t('Nickname or Email: ') , '', ''],
285 '$lpassword' => ['password', L10n::t('Password: '), '', ''],
286 '$lremember' => ['remember', L10n::t('Remember me'), 0, ''],
289 '$lopenid' => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
291 '$hiddens' => $hiddens,
295 '$lostpass' => L10n::t('Forgot your password?'),
296 '$lostlink' => L10n::t('Password Reset'),
298 '$tostitle' => L10n::t('Website Terms of Service'),
299 '$toslink' => L10n::t('terms of service'),
301 '$privacytitle' => L10n::t('Website Privacy Policy'),
302 '$privacylink' => L10n::t('privacy policy'),
306 Addon::callHooks('login_hook', $o);