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()
35 Session::remove('theme');
36 Session::remove('mobile-theme');
39 $a->internalRedirect();
42 return self::form(Session::get('return_path'), intval(Config::get('config', 'register_policy')) !== \Friendica\Module\Register::CLOSED);
45 public static function post()
47 $return_path = Session::get('return_path');
49 Session::set('return_path', $return_path);
53 empty($_POST['password'])
55 !empty($_POST['openid_url'])
56 || !empty($_POST['username'])
59 $openid_url = trim(defaults($_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'])
74 * Attempts to authenticate using OpenId
76 * @param string $openid_url OpenID URL string
77 * @param bool $remember Whether to set the session remember flag
78 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
80 private static function openIdAuthentication($openid_url, $remember)
82 $noid = Config::get('system', 'no_openid');
86 // if it's an email address or doesn't resolve to a URL, fail.
87 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
88 notice(L10n::t('Login failed.') . EOL);
89 $a->internalRedirect();
93 // Otherwise it's probably an openid.
95 $openid = new LightOpenID($a->getHostName());
96 $openid->identity = $openid_url;
97 $_SESSION['openid'] = $openid_url;
98 $_SESSION['remember'] = $remember;
99 $openid->returnUrl = $a->getBaseURL(true) . '/openid';
100 System::externalRedirect($openid->authUrl());
101 } catch (Exception $e) {
102 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());
107 * Attempts to authenticate using login/password
109 * @param string $username User name
110 * @param string $password Clear password
111 * @param bool $remember Whether to set the session remember flag
112 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
114 private static function passwordAuthentication($username, $password, $remember)
119 'username' => $username,
120 'password' => $password,
121 'authenticated' => 0,
122 'user_record' => null
128 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
129 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
130 * and later addons should not interfere with an earlier one that succeeded.
132 Hook::callAll('authenticate', $addon_auth);
135 if ($addon_auth['authenticated']) {
136 $record = $addon_auth['user_record'];
138 if (empty($record)) {
139 throw new Exception(L10n::t('Login failed.'));
142 $record = DBA::selectFirst('user', [],
143 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
146 } catch (Exception $e) {
147 Logger::warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
148 info('Login failed. Please check your credentials.' . EOL);
149 $a->internalRedirect();
153 Authentication::setCookie(0); // 0 means delete on browser exit
156 // if we haven't failed up this point, log them in.
157 Session::set('remember', $remember);
158 Session::set('last_login_date', DateTimeFormat::utcNow());
160 Session::setAuthenticatedForUser($a, $record, true, true);
162 $return_path = Session::get('return_path', '');
163 Session::remove('return_path');
165 $a->internalRedirect($return_path);
169 * @brief Tries to auth the user from the cookie or session
171 * @todo Should be moved to Friendica\Core\Session when it's created
173 public static function sessionAuth()
177 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
178 if (isset($_COOKIE["Friendica"])) {
179 $data = json_decode($_COOKIE["Friendica"]);
180 if (isset($data->uid)) {
182 $user = DBA::selectFirst('user', [],
186 'account_expired' => false,
187 'account_removed' => false,
191 if (DBA::isResult($user)) {
192 if ($data->hash != Authentication::getCookieHashForUser($user)) {
193 Logger::log("Hash for user " . $data->uid . " doesn't fit.");
194 Authentication::deleteSession();
195 $a->internalRedirect();
199 // Expires after 7 days by default,
200 // can be set via system.auth_cookie_lifetime
201 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
202 Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
204 // Do the authentification if not done by now
205 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
206 Session::setAuthenticatedForUser($a, $user);
208 if (Config::get('system', 'paranoia')) {
209 $_SESSION['addr'] = $data->ip;
216 if (!empty($_SESSION['authenticated'])) {
217 if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
218 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
219 if (DBA::isResult($contact)) {
220 self::getApp()->contact = $contact;
224 if (!empty($_SESSION['uid'])) {
225 // already logged in user returning
226 $check = Config::get('system', 'paranoia');
227 // extra paranoia - if the IP changed, log them out
228 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
229 Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
230 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
231 Authentication::deleteSession();
232 $a->internalRedirect();
235 $user = DBA::selectFirst('user', [],
237 'uid' => $_SESSION['uid'],
239 'account_expired' => false,
240 'account_removed' => false,
244 if (!DBA::isResult($user)) {
245 Authentication::deleteSession();
246 $a->internalRedirect();
249 // Make sure to refresh the last login time for the user if the user
250 // stays logged in for a long time, e.g. with "Remember Me"
251 $login_refresh = false;
252 if (empty($_SESSION['last_login_date'])) {
253 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
255 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
256 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
257 $login_refresh = true;
260 Session::setAuthenticatedForUser($a, $user, false, false, $login_refresh);
266 * @brief Wrapper for adding a login box.
268 * @param string $return_path The path relative to the base the user should be sent
269 * back to after login completes
270 * @param bool $register If $register == true provide a registration link.
271 * This will most always depend on the value of config.register_policy.
272 * @param array $hiddens optional
274 * @return string Returns the complete html for inserting into the page
276 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
277 * @hooks 'login_hook' string $o
279 public static function form($return_path = null, $register = false, $hiddens = [])
284 if ($register && intval($a->getConfig()->get('config', 'register_policy')) !== Register::CLOSED) {
286 'title' => L10n::t('Create a New Account'),
287 'desc' => L10n::t('Register')
291 $noid = Config::get('system', 'no_openid');
293 if (is_null($return_path)) {
294 $return_path = $a->query_string;
298 $tpl = Renderer::getMarkupTemplate('logout.tpl');
300 $a->page['htmlhead'] .= Renderer::replaceMacros(
301 Renderer::getMarkupTemplate('login_head.tpl'),
303 '$baseurl' => $a->getBaseURL(true)
307 $tpl = Renderer::getMarkupTemplate('login.tpl');
308 $_SESSION['return_path'] = $return_path;
311 $o .= Renderer::replaceMacros(
314 '$dest_url' => self::getApp()->getBaseURL(true) . '/login',
315 '$logout' => L10n::t('Logout'),
316 '$login' => L10n::t('Login'),
318 '$lname' => ['username', L10n::t('Nickname or Email: ') , '', ''],
319 '$lpassword' => ['password', L10n::t('Password: '), '', ''],
320 '$lremember' => ['remember', L10n::t('Remember me'), 0, ''],
323 '$lopenid' => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
325 '$hiddens' => $hiddens,
329 '$lostpass' => L10n::t('Forgot your password?'),
330 '$lostlink' => L10n::t('Password Reset'),
332 '$tostitle' => L10n::t('Website Terms of Service'),
333 '$toslink' => L10n::t('terms of service'),
335 '$privacytitle' => L10n::t('Website Privacy Policy'),
336 '$privacylink' => L10n::t('privacy policy'),
340 Hook::callAll('login_hook', $o);