3 * @file src/Module/Login.php
5 namespace Friendica\Module;
8 use Friendica\BaseModule;
9 use Friendica\Core\Addon;
10 use Friendica\Core\Authentication;
11 use Friendica\Core\Config;
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;
23 require_once 'boot.php';
24 require_once 'include/text.php';
29 * @author Hypolite Petovan <hypolite@mrpetovan.com>
31 class Login extends BaseModule
33 public static function content()
37 if (!empty($_SESSION['theme'])) {
38 unset($_SESSION['theme']);
41 if (!empty($_SESSION['mobile-theme'])) {
42 unset($_SESSION['mobile-theme']);
46 $a->internalRedirect();
49 return self::form(defaults($_SESSION, 'return_path', null), intval(Config::get('config', 'register_policy')) !== REGISTER_CLOSED);
52 public static function post()
54 $return_path = $_SESSION['return_path'];
56 $_SESSION['return_path'] = $return_path;
60 empty($_POST['password'])
62 !empty($_POST['openid_url'])
63 || !empty($_POST['username'])
66 $openid_url = trim(defaults($_POST, 'openid_url', $_POST['username']));
68 self::openIdAuthentication($openid_url, !empty($_POST['remember']));
71 if (!empty($_POST['auth-params']) && $_POST['auth-params'] === 'login') {
72 self::passwordAuthentication(
73 trim($_POST['username']),
74 trim($_POST['password']),
75 !empty($_POST['remember'])
81 * Attempts to authenticate using OpenId
83 * @param string $openid_url OpenID URL string
84 * @param bool $remember Whether to set the session remember flag
86 private static function openIdAuthentication($openid_url, $remember)
88 $noid = Config::get('system', 'no_openid');
92 // if it's an email address or doesn't resolve to a URL, fail.
93 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
94 notice(L10n::t('Login failed.') . EOL);
95 $a->internalRedirect();
99 // Otherwise it's probably an openid.
101 $openid = new LightOpenID($a->getHostName());
102 $openid->identity = $openid_url;
103 $_SESSION['openid'] = $openid_url;
104 $_SESSION['remember'] = $remember;
105 $openid->returnUrl = $a->getBaseURL(true) . '/openid';
106 System::externalRedirect($openid->authUrl());
107 } catch (Exception $e) {
108 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());
113 * Attempts to authenticate using login/password
115 * @param string $username User name
116 * @param string $password Clear password
117 * @param bool $remember Whether to set the session remember flag
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 Addon::callHooks('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::log('authenticate: failed login attempt: ' . Strings::escapeTags($username) . ' from 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();
164 Authentication::setAuthenticatedSessionForUser($record, true, true);
166 if (!empty($_SESSION['return_path'])) {
167 $return_path = $_SESSION['return_path'];
168 unset($_SESSION['return_path']);
173 $a->internalRedirect($return_path);
177 * @brief Tries to auth the user from the cookie or session
179 * @todo Should be moved to Friendica\Core\Session when it's created
181 public static function sessionAuth()
185 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
186 if (isset($_COOKIE["Friendica"])) {
187 $data = json_decode($_COOKIE["Friendica"]);
188 if (isset($data->uid)) {
190 $user = DBA::selectFirst('user', [],
194 'account_expired' => false,
195 'account_removed' => false,
199 if (DBA::isResult($user)) {
200 if ($data->hash != Authentication::getCookieHashForUser($user)) {
201 Logger::log("Hash for user " . $data->uid . " doesn't fit.");
202 Authentication::deleteSession();
203 $a->internalRedirect();
207 // Expires after 7 days by default,
208 // can be set via system.auth_cookie_lifetime
209 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
210 Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
212 // Do the authentification if not done by now
213 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
214 Authentication::setAuthenticatedSessionForUser($user);
216 if (Config::get('system', 'paranoia')) {
217 $_SESSION['addr'] = $data->ip;
224 if (!empty($_SESSION['authenticated'])) {
225 if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
226 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
227 if (DBA::isResult($contact)) {
228 self::getApp()->contact = $contact;
232 if (!empty($_SESSION['uid'])) {
233 // already logged in user returning
234 $check = Config::get('system', 'paranoia');
235 // extra paranoia - if the IP changed, log them out
236 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
237 Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
238 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
239 Authentication::deleteSession();
240 $a->internalRedirect();
243 $user = DBA::selectFirst('user', [],
245 'uid' => $_SESSION['uid'],
247 'account_expired' => false,
248 'account_removed' => false,
252 if (!DBA::isResult($user)) {
253 Authentication::deleteSession();
254 $a->internalRedirect();
257 // Make sure to refresh the last login time for the user if the user
258 // stays logged in for a long time, e.g. with "Remember Me"
259 $login_refresh = false;
260 if (empty($_SESSION['last_login_date'])) {
261 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
263 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
264 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
265 $login_refresh = true;
267 Authentication::setAuthenticatedSessionForUser($user, false, false, $login_refresh);
273 * @brief Wrapper for adding a login box.
275 * @param string $return_path The path relative to the base the user should be sent
276 * back to after login completes
277 * @param bool $register If $register == true provide a registration link.
278 * This will most always depend on the value of config.register_policy.
279 * @param array $hiddens optional
281 * @return string Returns the complete html for inserting into the page
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 Addon::callHooks('login_hook', $o);