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(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(
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)) {
193 // Time safe comparision of the two hashes.
194 $validSession = hash_equals(
195 Authentication::getCookieHashForUser($user),
199 if (!$validSession) {
200 Logger::log("Hash for user " . $data->uid . " doesn't fit.");
201 Authentication::deleteSession();
202 $a->internalRedirect();
206 // Expires after 7 days by default,
207 // can be set via system.auth_cookie_lifetime
208 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
209 Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
211 // Do the authentification if not done by now
212 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
213 Session::setAuthenticatedForUser($a, $user);
215 if (Config::get('system', 'paranoia')) {
216 $_SESSION['addr'] = $data->ip;
223 if (!empty($_SESSION['authenticated'])) {
224 if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
225 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
226 if (DBA::isResult($contact)) {
227 self::getApp()->contact = $contact;
231 if (!empty($_SESSION['uid'])) {
232 // already logged in user returning
233 $check = Config::get('system', 'paranoia');
234 // extra paranoia - if the IP changed, log them out
235 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
236 Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
237 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
238 Authentication::deleteSession();
239 $a->internalRedirect();
242 $user = DBA::selectFirst(
246 'uid' => $_SESSION['uid'],
248 'account_expired' => false,
249 'account_removed' => false,
253 if (!DBA::isResult($user)) {
254 Authentication::deleteSession();
255 $a->internalRedirect();
258 // Make sure to refresh the last login time for the user if the user
259 // stays logged in for a long time, e.g. with "Remember Me"
260 $login_refresh = false;
261 if (empty($_SESSION['last_login_date'])) {
262 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
264 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
265 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
266 $login_refresh = true;
269 Session::setAuthenticatedForUser($a, $user, false, false, $login_refresh);
275 * @brief Wrapper for adding a login box.
277 * @param string $return_path The path relative to the base the user should be sent
278 * back to after login completes
279 * @param bool $register If $register == true provide a registration link.
280 * This will most always depend on the value of config.register_policy.
281 * @param array $hiddens optional
283 * @return string Returns the complete html for inserting into the page
285 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
286 * @hooks 'login_hook' string $o
288 public static function form($return_path = null, $register = false, $hiddens = [])
293 if ($register && intval($a->getConfig()->get('config', 'register_policy')) !== Register::CLOSED) {
295 'title' => L10n::t('Create a New Account'),
296 'desc' => L10n::t('Register')
300 $noid = Config::get('system', 'no_openid');
302 if (is_null($return_path)) {
303 $return_path = $a->query_string;
307 $tpl = Renderer::getMarkupTemplate('logout.tpl');
309 $a->page['htmlhead'] .= Renderer::replaceMacros(
310 Renderer::getMarkupTemplate('login_head.tpl'),
312 '$baseurl' => $a->getBaseURL(true)
316 $tpl = Renderer::getMarkupTemplate('login.tpl');
317 $_SESSION['return_path'] = $return_path;
320 $o .= Renderer::replaceMacros(
323 '$dest_url' => self::getApp()->getBaseURL(true) . '/login',
324 '$logout' => L10n::t('Logout'),
325 '$login' => L10n::t('Login'),
327 '$lname' => ['username', L10n::t('Nickname or Email: '), '', ''],
328 '$lpassword' => ['password', L10n::t('Password: '), '', ''],
329 '$lremember' => ['remember', L10n::t('Remember me'), 0, ''],
332 '$lopenid' => ['openid_url', L10n::t('Or login using OpenID: '), '', ''],
334 '$hiddens' => $hiddens,
338 '$lostpass' => L10n::t('Forgot your password?'),
339 '$lostlink' => L10n::t('Password Reset'),
341 '$tostitle' => L10n::t('Website Terms of Service'),
342 '$toslink' => L10n::t('terms of service'),
344 '$privacytitle' => L10n::t('Website Privacy Policy'),
345 '$privacylink' => L10n::t('privacy policy'),
349 Hook::callAll('login_hook', $o);