3 * @file src/Module/Login.php
5 namespace Friendica\Module;
8 use Friendica\BaseModule;
9 use Friendica\Core\Authentication;
10 use Friendica\Core\Config;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Renderer;
15 use Friendica\Core\Session;
16 use Friendica\Core\System;
17 use Friendica\Database\DBA;
18 use Friendica\Model\User;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Util\Strings;
27 * @author Hypolite Petovan <hypolite@mrpetovan.com>
29 class Login extends BaseModule
31 public static function content()
36 $a->internalRedirect();
39 return self::form(Session::get('return_path'), intval(Config::get('config', 'register_policy')) !== \Friendica\Module\Register::CLOSED);
42 public static function post()
44 $return_path = Session::get('return_path');
46 Session::set('return_path', $return_path);
50 empty($_POST['password'])
52 !empty($_POST['openid_url'])
53 || !empty($_POST['username'])
56 $openid_url = trim(defaults($_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('user', [],
140 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
143 } catch (Exception $e) {
144 Logger::warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
145 info('Login failed. Please check your credentials.' . EOL);
146 $a->internalRedirect();
150 Authentication::setCookie(0); // 0 means delete on browser exit
153 // if we haven't failed up this point, log them in.
154 Session::set('remember', $remember);
155 Session::set('last_login_date', DateTimeFormat::utcNow());
157 Session::setAuthenticatedForUser($a, $record, true, true);
159 $return_path = Session::get('return_path', '');
160 Session::remove('return_path');
162 $a->internalRedirect($return_path);
166 * @brief Tries to auth the user from the cookie or session
168 * @todo Should be moved to Friendica\Core\Session when it's created
170 public static function sessionAuth()
174 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
175 if (isset($_COOKIE["Friendica"])) {
176 $data = json_decode($_COOKIE["Friendica"]);
177 if (isset($data->uid)) {
179 $user = DBA::selectFirst('user', [],
183 'account_expired' => false,
184 'account_removed' => false,
188 if (DBA::isResult($user)) {
189 if ($data->hash != Authentication::getCookieHashForUser($user)) {
190 Logger::log("Hash for user " . $data->uid . " doesn't fit.");
191 Authentication::deleteSession();
192 $a->internalRedirect();
196 // Expires after 7 days by default,
197 // can be set via system.auth_cookie_lifetime
198 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
199 Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
201 // Do the authentification if not done by now
202 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
203 Session::setAuthenticatedForUser($a, $user);
205 if (Config::get('system', 'paranoia')) {
206 $_SESSION['addr'] = $data->ip;
213 if (!empty($_SESSION['authenticated'])) {
214 if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
215 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
216 if (DBA::isResult($contact)) {
217 self::getApp()->contact = $contact;
221 if (!empty($_SESSION['uid'])) {
222 // already logged in user returning
223 $check = Config::get('system', 'paranoia');
224 // extra paranoia - if the IP changed, log them out
225 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
226 Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
227 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
228 Authentication::deleteSession();
229 $a->internalRedirect();
232 $user = DBA::selectFirst('user', [],
234 'uid' => $_SESSION['uid'],
236 'account_expired' => false,
237 'account_removed' => false,
241 if (!DBA::isResult($user)) {
242 Authentication::deleteSession();
243 $a->internalRedirect();
246 // Make sure to refresh the last login time for the user if the user
247 // stays logged in for a long time, e.g. with "Remember Me"
248 $login_refresh = false;
249 if (empty($_SESSION['last_login_date'])) {
250 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
252 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
253 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
254 $login_refresh = true;
257 Session::setAuthenticatedForUser($a, $user, false, false, $login_refresh);
263 * @brief Wrapper for adding a login box.
265 * @param string $return_path The path relative to the base the user should be sent
266 * back to after login completes
267 * @param bool $register If $register == true provide a registration link.
268 * This will most always depend on the value of config.register_policy.
269 * @param array $hiddens optional
271 * @return string Returns the complete html for inserting into the page
273 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
274 * @hooks 'login_hook' string $o
276 public static function form($return_path = null, $register = false, $hiddens = [])
281 if ($register && intval($a->getConfig()->get('config', 'register_policy')) !== Register::CLOSED) {
283 'title' => L10n::t('Create a New Account'),
284 'desc' => L10n::t('Register')
288 $noid = Config::get('system', 'no_openid');
290 if (is_null($return_path)) {
291 $return_path = $a->query_string;
295 $tpl = Renderer::getMarkupTemplate('logout.tpl');
297 $a->page['htmlhead'] .= Renderer::replaceMacros(
298 Renderer::getMarkupTemplate('login_head.tpl'),
300 '$baseurl' => $a->getBaseURL(true)
304 $tpl = Renderer::getMarkupTemplate('login.tpl');
305 $_SESSION['return_path'] = $return_path;
308 $o .= Renderer::replaceMacros(
311 '$dest_url' => self::getApp()->getBaseURL(true) . '/login',
312 '$logout' => L10n::t('Logout'),
313 '$login' => L10n::t('Login'),
315 '$lname' => ['username', L10n::t('Nickname or Email: ') , '', ''],
316 '$lpassword' => ['password', L10n::t('Password: '), '', ''],
317 '$lremember' => ['remember', L10n::t('Remember me'), 0, ''],
320 '$lopenid' => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
322 '$hiddens' => $hiddens,
326 '$lostpass' => L10n::t('Forgot your password?'),
327 '$lostlink' => L10n::t('Password Reset'),
329 '$tostitle' => L10n::t('Website Terms of Service'),
330 '$toslink' => L10n::t('terms of service'),
332 '$privacytitle' => L10n::t('Website Privacy Policy'),
333 '$privacylink' => L10n::t('privacy policy'),
337 Hook::callAll('login_hook', $o);