4 * @file src/Module/Login.php
7 namespace Friendica\Module;
10 use Friendica\BaseModule;
11 use Friendica\Core\Authentication;
12 use Friendica\Core\Config;
13 use Friendica\Core\Hook;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Renderer;
17 use Friendica\Core\Session;
18 use Friendica\Core\System;
19 use Friendica\Database\DBA;
20 use Friendica\Model\User;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\Strings;
29 * @author Hypolite Petovan <hypolite@mrpetovan.com>
31 class Login extends BaseModule
33 public static function content()
38 $a->internalRedirect();
41 return self::form(Session::get('return_path'), intval(Config::get('config', 'register_policy')) !== \Friendica\Module\Register::CLOSED);
44 public static function post()
46 $return_path = Session::get('return_path');
48 Session::set('return_path', $return_path);
52 empty($_POST['password'])
53 && (!empty($_POST['openid_url'])
54 || !empty($_POST['username']))
56 $openid_url = trim(($_POST['openid_url'] ?? '') ?: $_POST['username']);
58 self::openIdAuthentication($openid_url, !empty($_POST['remember']));
61 if (!empty($_POST['auth-params']) && $_POST['auth-params'] === 'login') {
62 self::passwordAuthentication(
63 trim($_POST['username']),
64 trim($_POST['password']),
65 !empty($_POST['remember'])
71 * Attempts to authenticate using OpenId
73 * @param string $openid_url OpenID URL string
74 * @param bool $remember Whether to set the session remember flag
75 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
77 private static function openIdAuthentication($openid_url, $remember)
79 $noid = Config::get('system', 'no_openid');
83 // if it's an email address or doesn't resolve to a URL, fail.
84 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
85 notice(L10n::t('Login failed.') . EOL);
86 $a->internalRedirect();
90 // Otherwise it's probably an openid.
92 $openid = new LightOpenID($a->getHostName());
93 $openid->identity = $openid_url;
94 $_SESSION['openid'] = $openid_url;
95 $_SESSION['remember'] = $remember;
96 $openid->returnUrl = $a->getBaseURL(true) . '/openid';
97 System::externalRedirect($openid->authUrl());
98 } catch (Exception $e) {
99 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());
104 * Attempts to authenticate using login/password
106 * @param string $username User name
107 * @param string $password Clear password
108 * @param bool $remember Whether to set the session remember flag
109 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
111 private static function passwordAuthentication($username, $password, $remember)
116 'username' => $username,
117 'password' => $password,
118 'authenticated' => 0,
119 'user_record' => null
125 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
126 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
127 * and later addons should not interfere with an earlier one that succeeded.
129 Hook::callAll('authenticate', $addon_auth);
132 if ($addon_auth['authenticated']) {
133 $record = $addon_auth['user_record'];
135 if (empty($record)) {
136 throw new Exception(L10n::t('Login failed.'));
139 $record = DBA::selectFirst(
142 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
145 } catch (Exception $e) {
146 Logger::warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
147 info('Login failed. Please check your credentials.' . EOL);
148 $a->internalRedirect();
152 Authentication::setCookie(0); // 0 means delete on browser exit
155 // if we haven't failed up this point, log them in.
156 Session::set('remember', $remember);
157 Session::set('last_login_date', DateTimeFormat::utcNow());
159 Session::setAuthenticatedForUser($a, $record, true, true);
161 $return_path = Session::get('return_path', '');
162 Session::remove('return_path');
164 $a->internalRedirect($return_path);
168 * @brief Tries to auth the user from the cookie or session
170 * @todo Should be moved to Friendica\Core\Session when it's created
172 public static function sessionAuth()
176 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
177 if (isset($_COOKIE["Friendica"])) {
178 $data = json_decode($_COOKIE["Friendica"]);
179 if (isset($data->uid)) {
181 $user = DBA::selectFirst(
187 'account_expired' => false,
188 'account_removed' => false,
192 if (DBA::isResult($user)) {
194 Authentication::getCookieHashForUser($user),
197 Logger::log("Hash for user " . $data->uid . " doesn't fit.");
198 Authentication::deleteSession();
199 $a->internalRedirect();
203 // Expires after 7 days by default,
204 // can be set via system.auth_cookie_lifetime
205 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
206 Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
208 // Do the authentification if not done by now
209 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
210 Session::setAuthenticatedForUser($a, $user);
212 if (Config::get('system', 'paranoia')) {
213 $_SESSION['addr'] = $data->ip;
220 if (!empty($_SESSION['authenticated'])) {
221 if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
222 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
223 if (DBA::isResult($contact)) {
224 self::getApp()->contact = $contact;
228 if (!empty($_SESSION['uid'])) {
229 // already logged in user returning
230 $check = Config::get('system', 'paranoia');
231 // extra paranoia - if the IP changed, log them out
232 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
233 Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
234 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
235 Authentication::deleteSession();
236 $a->internalRedirect();
239 $user = DBA::selectFirst(
243 'uid' => $_SESSION['uid'],
245 'account_expired' => false,
246 'account_removed' => false,
250 if (!DBA::isResult($user)) {
251 Authentication::deleteSession();
252 $a->internalRedirect();
255 // Make sure to refresh the last login time for the user if the user
256 // stays logged in for a long time, e.g. with "Remember Me"
257 $login_refresh = false;
258 if (empty($_SESSION['last_login_date'])) {
259 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
261 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
262 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
263 $login_refresh = true;
266 Session::setAuthenticatedForUser($a, $user, false, false, $login_refresh);
272 * @brief Wrapper for adding a login box.
274 * @param string $return_path The path relative to the base the user should be sent
275 * back to after login completes
276 * @param bool $register If $register == true provide a registration link.
277 * This will most always depend on the value of config.register_policy.
278 * @param array $hiddens optional
280 * @return string Returns the complete html for inserting into the page
282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
283 * @hooks 'login_hook' string $o
285 public static function form($return_path = null, $register = false, $hiddens = [])
290 if ($register && intval($a->getConfig()->get('config', 'register_policy')) !== Register::CLOSED) {
292 'title' => L10n::t('Create a New Account'),
293 'desc' => L10n::t('Register')
297 $noid = Config::get('system', 'no_openid');
299 if (is_null($return_path)) {
300 $return_path = $a->query_string;
304 $tpl = Renderer::getMarkupTemplate('logout.tpl');
306 $a->page['htmlhead'] .= Renderer::replaceMacros(
307 Renderer::getMarkupTemplate('login_head.tpl'),
309 '$baseurl' => $a->getBaseURL(true)
313 $tpl = Renderer::getMarkupTemplate('login.tpl');
314 $_SESSION['return_path'] = $return_path;
317 $o .= Renderer::replaceMacros(
320 '$dest_url' => self::getApp()->getBaseURL(true) . '/login',
321 '$logout' => L10n::t('Logout'),
322 '$login' => L10n::t('Login'),
324 '$lname' => ['username', L10n::t('Nickname or Email: '), '', ''],
325 '$lpassword' => ['password', L10n::t('Password: '), '', ''],
326 '$lremember' => ['remember', L10n::t('Remember me'), 0, ''],
329 '$lopenid' => ['openid_url', L10n::t('Or login using OpenID: '), '', ''],
331 '$hiddens' => $hiddens,
335 '$lostpass' => L10n::t('Forgot your password?'),
336 '$lostlink' => L10n::t('Password Reset'),
338 '$tostitle' => L10n::t('Website Terms of Service'),
339 '$toslink' => L10n::t('terms of service'),
341 '$privacytitle' => L10n::t('Website Privacy Policy'),
342 '$privacylink' => L10n::t('privacy policy'),
346 Hook::callAll('login_hook', $o);