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 if (!empty($_SESSION['theme'])) {
36 unset($_SESSION['theme']);
39 if (!empty($_SESSION['mobile-theme'])) {
40 unset($_SESSION['mobile-theme']);
44 $a->internalRedirect();
47 return self::form(defaults($_SESSION, 'return_path', null), intval(Config::get('config', 'register_policy')) !== \Friendica\Module\Register::CLOSED);
50 public static function post()
52 $return_path = defaults($_SESSION, 'return_path', '');
54 $_SESSION['return_path'] = $return_path;
58 empty($_POST['password'])
60 !empty($_POST['openid_url'])
61 || !empty($_POST['username'])
64 $openid_url = trim(defaults($_POST, 'openid_url', $_POST['username']));
66 self::openIdAuthentication($openid_url, !empty($_POST['remember']));
69 if (!empty($_POST['auth-params']) && $_POST['auth-params'] === 'login') {
70 self::passwordAuthentication(
71 trim($_POST['username']),
72 trim($_POST['password']),
73 !empty($_POST['remember'])
79 * Attempts to authenticate using OpenId
81 * @param string $openid_url OpenID URL string
82 * @param bool $remember Whether to set the session remember flag
83 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
85 private static function openIdAuthentication($openid_url, $remember)
87 $noid = Config::get('system', 'no_openid');
91 // if it's an email address or doesn't resolve to a URL, fail.
92 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
93 notice(L10n::t('Login failed.') . EOL);
94 $a->internalRedirect();
98 // Otherwise it's probably an openid.
100 $openid = new LightOpenID($a->getHostName());
101 $openid->identity = $openid_url;
102 $_SESSION['openid'] = $openid_url;
103 $_SESSION['remember'] = $remember;
104 $openid->returnUrl = $a->getBaseURL(true) . '/openid';
105 System::externalRedirect($openid->authUrl());
106 } catch (Exception $e) {
107 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());
112 * Attempts to authenticate using login/password
114 * @param string $username User name
115 * @param string $password Clear password
116 * @param bool $remember Whether to set the session remember flag
117 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
119 private static function passwordAuthentication($username, $password, $remember)
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('user', [],
148 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
151 } catch (Exception $e) {
152 Logger::warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
153 info('Login failed. Please check your credentials.' . EOL);
154 $a->internalRedirect();
158 Authentication::setCookie(0); // 0 means delete on browser exit
161 // if we haven't failed up this point, log them in.
162 $_SESSION['remember'] = $remember;
163 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
165 Session::setAuthenticatedForUser($a, $record, true, true);
167 if (!empty($_SESSION['return_path'])) {
168 $return_path = $_SESSION['return_path'];
169 unset($_SESSION['return_path']);
174 $a->internalRedirect($return_path);
178 * @brief Tries to auth the user from the cookie or session
180 * @todo Should be moved to Friendica\Core\Session when it's created
182 public static function sessionAuth()
186 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
187 if (isset($_COOKIE["Friendica"])) {
188 $data = json_decode($_COOKIE["Friendica"]);
189 if (isset($data->uid)) {
191 $user = DBA::selectFirst('user', [],
195 'account_expired' => false,
196 'account_removed' => false,
200 if (DBA::isResult($user)) {
201 if ($data->hash != Authentication::getCookieHashForUser($user)) {
202 Logger::log("Hash for user " . $data->uid . " doesn't fit.");
203 Authentication::deleteSession();
204 $a->internalRedirect();
208 // Expires after 7 days by default,
209 // can be set via system.auth_cookie_lifetime
210 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
211 Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
213 // Do the authentification if not done by now
214 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
215 Session::setAuthenticatedForUser($a, $user);
217 if (Config::get('system', 'paranoia')) {
218 $_SESSION['addr'] = $data->ip;
225 if (!empty($_SESSION['authenticated'])) {
226 if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
227 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
228 if (DBA::isResult($contact)) {
229 self::getApp()->contact = $contact;
233 if (!empty($_SESSION['uid'])) {
234 // already logged in user returning
235 $check = Config::get('system', 'paranoia');
236 // extra paranoia - if the IP changed, log them out
237 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
238 Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
239 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
240 Authentication::deleteSession();
241 $a->internalRedirect();
244 $user = DBA::selectFirst('user', [],
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 = [])
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);