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\System;
16 use Friendica\Database\DBA;
17 use Friendica\Model\User;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Network;
20 use Friendica\Util\Strings;
26 * @author Hypolite Petovan <hypolite@mrpetovan.com>
28 class Login extends BaseModule
30 public static function content()
34 if (!empty($_SESSION['theme'])) {
35 unset($_SESSION['theme']);
38 if (!empty($_SESSION['mobile-theme'])) {
39 unset($_SESSION['mobile-theme']);
43 $a->internalRedirect();
46 return self::form(defaults($_SESSION, 'return_path', null), intval(Config::get('config', 'register_policy')) !== \Friendica\Module\Register::CLOSED);
49 public static function post()
51 $return_path = defaults($_SESSION, 'return_path', '');
53 $_SESSION['return_path'] = $return_path;
57 empty($_POST['password'])
59 !empty($_POST['openid_url'])
60 || !empty($_POST['username'])
63 $openid_url = trim(defaults($_POST, 'openid_url', $_POST['username']));
65 self::openIdAuthentication($openid_url, !empty($_POST['remember']));
68 if (!empty($_POST['auth-params']) && $_POST['auth-params'] === 'login') {
69 self::passwordAuthentication(
70 trim($_POST['username']),
71 trim($_POST['password']),
72 !empty($_POST['remember'])
78 * Attempts to authenticate using OpenId
80 * @param string $openid_url OpenID URL string
81 * @param bool $remember Whether to set the session remember flag
82 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
84 private static function openIdAuthentication($openid_url, $remember)
86 $noid = Config::get('system', 'no_openid');
90 // if it's an email address or doesn't resolve to a URL, fail.
91 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
92 notice(L10n::t('Login failed.') . EOL);
93 $a->internalRedirect();
97 // Otherwise it's probably an openid.
99 $openid = new LightOpenID($a->getHostName());
100 $openid->identity = $openid_url;
101 $_SESSION['openid'] = $openid_url;
102 $_SESSION['remember'] = $remember;
103 $openid->returnUrl = $a->getBaseURL(true) . '/openid';
104 System::externalRedirect($openid->authUrl());
105 } catch (Exception $e) {
106 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());
111 * Attempts to authenticate using login/password
113 * @param string $username User name
114 * @param string $password Clear password
115 * @param bool $remember Whether to set the session remember flag
116 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
118 private static function passwordAuthentication($username, $password, $remember)
123 'username' => $username,
124 'password' => $password,
125 'authenticated' => 0,
126 'user_record' => null
132 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
133 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
134 * and later addons should not interfere with an earlier one that succeeded.
136 Hook::callAll('authenticate', $addon_auth);
139 if ($addon_auth['authenticated']) {
140 $record = $addon_auth['user_record'];
142 if (empty($record)) {
143 throw new Exception(L10n::t('Login failed.'));
146 $record = DBA::selectFirst('user', [],
147 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
150 } catch (Exception $e) {
151 Logger::warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
152 info('Login failed. Please check your credentials.' . EOL);
153 $a->internalRedirect();
157 Authentication::setCookie(0); // 0 means delete on browser exit
160 // if we haven't failed up this point, log them in.
161 $_SESSION['remember'] = $remember;
162 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
163 Authentication::setAuthenticatedSessionForUser($record, true, true);
165 if (!empty($_SESSION['return_path'])) {
166 $return_path = $_SESSION['return_path'];
167 unset($_SESSION['return_path']);
172 $a->internalRedirect($return_path);
176 * @brief Tries to auth the user from the cookie or session
178 * @todo Should be moved to Friendica\Core\Session when it's created
180 public static function sessionAuth()
184 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
185 if (isset($_COOKIE["Friendica"])) {
186 $data = json_decode($_COOKIE["Friendica"]);
187 if (isset($data->uid)) {
189 $user = DBA::selectFirst('user', [],
193 'account_expired' => false,
194 'account_removed' => false,
198 if (DBA::isResult($user)) {
199 if ($data->hash != Authentication::getCookieHashForUser($user)) {
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 Authentication::setAuthenticatedSessionForUser($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('user', [],
244 'uid' => $_SESSION['uid'],
246 'account_expired' => false,
247 'account_removed' => false,
251 if (!DBA::isResult($user)) {
252 Authentication::deleteSession();
253 $a->internalRedirect();
256 // Make sure to refresh the last login time for the user if the user
257 // stays logged in for a long time, e.g. with "Remember Me"
258 $login_refresh = false;
259 if (empty($_SESSION['last_login_date'])) {
260 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
262 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
263 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
264 $login_refresh = true;
266 Authentication::setAuthenticatedSessionForUser($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 = [])
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);