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 $openid_identity = Session::get('openid_identity');
47 $openid_server = Session::get('openid_server');
49 $return_path = Session::get('return_path');
51 Session::set('return_path', $return_path);
55 empty($_POST['password'])
56 && (!empty($_POST['openid_url'])
57 || !empty($_POST['username']))
59 $openid_url = trim(($_POST['openid_url'] ?? '') ?: $_POST['username']);
61 self::openIdAuthentication($openid_url, !empty($_POST['remember']));
64 if (!empty($_POST['auth-params']) && $_POST['auth-params'] === 'login') {
65 self::passwordAuthentication(
66 trim($_POST['username']),
67 trim($_POST['password']),
68 !empty($_POST['remember']),
76 * Attempts to authenticate using OpenId
78 * @param string $openid_url OpenID URL string
79 * @param bool $remember Whether to set the session remember flag
80 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
82 private static function openIdAuthentication($openid_url, $remember)
84 $noid = Config::get('system', 'no_openid');
88 // if it's an email address or doesn't resolve to a URL, fail.
89 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
90 notice(L10n::t('Login failed.') . EOL);
91 $a->internalRedirect();
95 // Otherwise it's probably an openid.
97 $openid = new LightOpenID($a->getHostName());
98 $openid->identity = $openid_url;
99 Session::set('openid', $openid_url);
100 Session::set('remember', $remember);
101 $openid->returnUrl = $a->getBaseURL(true) . '/openid';
102 $openid->optional = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
103 System::externalRedirect($openid->authUrl());
104 } catch (Exception $e) {
105 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());
110 * Attempts to authenticate using login/password
112 * @param string $username User name
113 * @param string $password Clear password
114 * @param bool $remember Whether to set the session remember flag
115 * @param string $openid_identity OpenID identity
116 * @param string $openid_server OpenID URL
117 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
119 private static function passwordAuthentication($username, $password, $remember, $openid_identity, $openid_server)
124 'username' => $username,
125 'password' => $password,
126 'authenticated' => 0,
127 'user_record' => null
133 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
134 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
135 * and later addons should not interfere with an earlier one that succeeded.
137 Hook::callAll('authenticate', $addon_auth);
140 if ($addon_auth['authenticated']) {
141 $record = $addon_auth['user_record'];
143 if (empty($record)) {
144 throw new Exception(L10n::t('Login failed.'));
147 $record = DBA::selectFirst(
150 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
153 } catch (Exception $e) {
154 Logger::warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
155 info('Login failed. Please check your credentials.' . EOL);
156 $a->internalRedirect();
160 Authentication::setCookie(0); // 0 means delete on browser exit
163 // if we haven't failed up this point, log them in.
164 Session::set('remember', $remember);
165 Session::set('last_login_date', DateTimeFormat::utcNow());
167 if (!empty($openid_identity) || !empty($openid_server)) {
168 DBA::update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
171 Session::setAuthenticatedForUser($a, $record, true, true);
173 $return_path = Session::get('return_path', '');
174 Session::remove('return_path');
176 $a->internalRedirect($return_path);
180 * @brief Tries to auth the user from the cookie or session
182 * @todo Should be moved to Friendica\Core\Session when it's created
184 public static function sessionAuth()
188 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
189 if (isset($_COOKIE["Friendica"])) {
190 $data = json_decode($_COOKIE["Friendica"]);
191 if (isset($data->uid)) {
193 $user = DBA::selectFirst(
199 'account_expired' => false,
200 'account_removed' => false,
204 if (DBA::isResult($user)) {
206 Authentication::getCookieHashForUser($user),
209 Logger::log("Hash for user " . $data->uid . " doesn't fit.");
210 Authentication::deleteSession();
211 $a->internalRedirect();
215 // Expires after 7 days by default,
216 // can be set via system.auth_cookie_lifetime
217 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
218 Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
220 // Do the authentification if not done by now
221 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
222 Session::setAuthenticatedForUser($a, $user);
224 if (Config::get('system', 'paranoia')) {
225 $_SESSION['addr'] = $data->ip;
232 if (!empty($_SESSION['authenticated'])) {
233 if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
234 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
235 if (DBA::isResult($contact)) {
236 self::getApp()->contact = $contact;
240 if (!empty($_SESSION['uid'])) {
241 // already logged in user returning
242 $check = Config::get('system', 'paranoia');
243 // extra paranoia - if the IP changed, log them out
244 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
245 Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
246 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
247 Authentication::deleteSession();
248 $a->internalRedirect();
251 $user = DBA::selectFirst(
255 'uid' => $_SESSION['uid'],
257 'account_expired' => false,
258 'account_removed' => false,
262 if (!DBA::isResult($user)) {
263 Authentication::deleteSession();
264 $a->internalRedirect();
267 // Make sure to refresh the last login time for the user if the user
268 // stays logged in for a long time, e.g. with "Remember Me"
269 $login_refresh = false;
270 if (empty($_SESSION['last_login_date'])) {
271 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
273 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
274 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
275 $login_refresh = true;
278 Session::setAuthenticatedForUser($a, $user, false, false, $login_refresh);
284 * @brief Wrapper for adding a login box.
286 * @param string $return_path The path relative to the base the user should be sent
287 * back to after login completes
288 * @param bool $register If $register == true provide a registration link.
289 * This will most always depend on the value of config.register_policy.
290 * @param array $hiddens optional
292 * @return string Returns the complete html for inserting into the page
294 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
295 * @hooks 'login_hook' string $o
297 public static function form($return_path = null, $register = false, $hiddens = [])
302 $noid = Config::get('system', 'no_openid');
305 Session::remove('openid_identity');
306 Session::remove('openid_attributes');
310 if ($register && intval($a->getConfig()->get('config', 'register_policy')) !== Register::CLOSED) {
312 'title' => L10n::t('Create a New Account'),
313 'desc' => L10n::t('Register'),
314 'url' => self::getRegisterURL()
318 if (is_null($return_path)) {
319 $return_path = $a->query_string;
323 $tpl = Renderer::getMarkupTemplate('logout.tpl');
325 $a->page['htmlhead'] .= Renderer::replaceMacros(
326 Renderer::getMarkupTemplate('login_head.tpl'),
328 '$baseurl' => $a->getBaseURL(true)
332 $tpl = Renderer::getMarkupTemplate('login.tpl');
333 $_SESSION['return_path'] = $return_path;
336 if (!empty(Session::get('openid_identity'))) {
337 $openid_title = L10n::t('Your OpenID: ');
338 $openid_readonly = true;
339 $identity = Session::get('openid_identity');
340 $username_desc = L10n::t('Please enter your username and password to add the OpenID to your existing account.');
342 $openid_title = L10n::t('Or login using OpenID: ');
343 $openid_readonly = false;
348 $o .= Renderer::replaceMacros(
351 '$dest_url' => self::getApp()->getBaseURL(true) . '/login',
352 '$logout' => L10n::t('Logout'),
353 '$login' => L10n::t('Login'),
355 '$lname' => ['username', L10n::t('Nickname or Email: '), '', $username_desc],
356 '$lpassword' => ['password', L10n::t('Password: '), '', ''],
357 '$lremember' => ['remember', L10n::t('Remember me'), 0, ''],
360 '$lopenid' => ['openid_url', $openid_title, $identity, '', $openid_readonly],
362 '$hiddens' => $hiddens,
366 '$lostpass' => L10n::t('Forgot your password?'),
367 '$lostlink' => L10n::t('Password Reset'),
369 '$tostitle' => L10n::t('Website Terms of Service'),
370 '$toslink' => L10n::t('terms of service'),
372 '$privacytitle' => L10n::t('Website Privacy Policy'),
373 '$privacylink' => L10n::t('privacy policy'),
377 Hook::callAll('login_hook', $o);
383 * Get the URL to the register page and add OpenID parameters to it
385 private static function getRegisterURL()
387 if (empty(Session::get('openid_identity'))) {
392 $attr = Session::get('openid_attributes', []);
394 if (is_array($attr) && count($attr)) {
395 foreach ($attr as $k => $v) {
396 if ($k === 'namePerson/friendly') {
397 $nick = Strings::escapeTags(trim($v));
399 if ($k === 'namePerson/first') {
400 $first = Strings::escapeTags(trim($v));
402 if ($k === 'namePerson') {
403 $args['username'] = Strings::escapeTags(trim($v));
405 if ($k === 'contact/email') {
406 $args['email'] = Strings::escapeTags(trim($v));
408 if ($k === 'media/image/aspect11') {
409 $photosq = bin2hex(trim($v));
411 if ($k === 'media/image/default') {
412 $photo = bin2hex(trim($v));
418 $args['nickname'] = $nick;
419 } elseif (!empty($first)) {
420 $args['nickname'] = $first;
423 if (!empty($photosq)) {
424 $args['photo'] = $photosq;
425 } elseif (!empty($photo)) {
426 $args['photo'] = $photo;
429 $args['openid_url'] = Strings::escapeTags(trim(Session::get('openid_identity')));
431 return 'register?' . http_build_query($args);