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\System;
15 use Friendica\Database\DBA;
16 use Friendica\Model\User;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Network;
21 require_once 'boot.php';
22 require_once 'include/text.php';
27 * @author Hypolite Petovan <hypolite@mrpetovan.com>
29 class Login extends BaseModule
31 public static function content()
35 if (x($_SESSION, 'theme')) {
36 unset($_SESSION['theme']);
39 if (x($_SESSION, 'mobile-theme')) {
40 unset($_SESSION['mobile-theme']);
44 $a->internalRedirect();
47 return self::form($_SESSION['return_path'], intval(Config::get('config', 'register_policy')) !== REGISTER_CLOSED);
50 public static function post()
52 $return_path = $_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 (x($_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
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
117 private static function passwordAuthentication($username, $password, $remember)
122 'username' => $username,
123 'password' => $password,
124 'authenticated' => 0,
125 'user_record' => null
131 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
132 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
133 * and later addons should not interfere with an earlier one that succeeded.
135 Addon::callHooks('authenticate', $addon_auth);
138 if ($addon_auth['authenticated']) {
139 $record = $addon_auth['user_record'];
141 if (empty($record)) {
142 throw new Exception(L10n::t('Login failed.'));
145 $record = DBA::selectFirst('user', [],
146 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
149 } catch (Exception $e) {
150 Logger::log('authenticate: failed login attempt: ' . notags($username) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
151 info('Login failed. Please check your credentials.' . EOL);
152 $a->internalRedirect();
156 Authentication::setCookie(0); // 0 means delete on browser exit
159 // if we haven't failed up this point, log them in.
160 $_SESSION['remember'] = $remember;
161 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
162 Authentication::setAuthenticatedSessionForUser($record, true, true);
164 if (x($_SESSION, 'return_path')) {
165 $return_path = $_SESSION['return_path'];
166 unset($_SESSION['return_path']);
171 $a->internalRedirect($return_path);
175 * @brief Tries to auth the user from the cookie or session
177 * @todo Should be moved to Friendica\Core\Session when it's created
179 public static function sessionAuth()
183 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
184 if (isset($_COOKIE["Friendica"])) {
185 $data = json_decode($_COOKIE["Friendica"]);
186 if (isset($data->uid)) {
188 $user = DBA::selectFirst('user', [],
192 'account_expired' => false,
193 'account_removed' => false,
197 if (DBA::isResult($user)) {
198 if ($data->hash != Authentication::getCookieHashForUser($user)) {
199 Logger::log("Hash for user " . $data->uid . " doesn't fit.");
200 Authentication::deleteSession();
201 $a->internalRedirect();
205 // Expires after 7 days by default,
206 // can be set via system.auth_cookie_lifetime
207 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
208 Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
210 // Do the authentification if not done by now
211 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
212 Authentication::setAuthenticatedSessionForUser($user);
214 if (Config::get('system', 'paranoia')) {
215 $_SESSION['addr'] = $data->ip;
222 if (isset($_SESSION) && x($_SESSION, 'authenticated')) {
223 if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
224 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
225 if (DBA::isResult($contact)) {
226 self::getApp()->contact = $contact;
230 if (x($_SESSION, 'uid')) {
231 // already logged in user returning
232 $check = Config::get('system', 'paranoia');
233 // extra paranoia - if the IP changed, log them out
234 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
235 Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
236 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
237 Authentication::deleteSession();
238 $a->internalRedirect();
241 $user = DBA::selectFirst('user', [],
243 'uid' => $_SESSION['uid'],
245 'account_expired' => false,
246 'account_removed' => false,
250 if (!DBA::isResult($user)) {
251 Authentication::deleteSession();
252 $a->internalRedirect();
255 // Make sure to refresh the last login time for the user if the user
256 // stays logged in for a long time, e.g. with "Remember Me"
257 $login_refresh = false;
258 if (empty($_SESSION['last_login_date'])) {
259 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
261 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
262 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
263 $login_refresh = true;
265 Authentication::setAuthenticatedSessionForUser($user, false, false, $login_refresh);
271 * @brief Wrapper for adding a login box.
273 * @param string $return_path The path relative to the base the user should be sent
274 * back to after login completes
275 * @param bool $register If $register == true provide a registration link.
276 * This will most always depend on the value of config.register_policy.
277 * @param array $hiddens optional
279 * @return string Returns the complete html for inserting into the page
281 * @hooks 'login_hook' string $o
283 public static function form($return_path = null, $register = false, $hiddens = [])
290 'title' => L10n::t('Create a New Account'),
291 'desc' => L10n::t('Register')
295 $noid = Config::get('system', 'no_openid');
297 if (is_null($return_path)) {
298 $return_path = $a->query_string;
302 $tpl = get_markup_template('logout.tpl');
304 $a->page['htmlhead'] .= replace_macros(
305 get_markup_template('login_head.tpl'),
307 '$baseurl' => $a->getBaseURL(true)
311 $tpl = get_markup_template('login.tpl');
312 $_SESSION['return_path'] = $return_path;
315 $o .= replace_macros(
318 '$dest_url' => self::getApp()->getBaseURL(true) . '/login',
319 '$logout' => L10n::t('Logout'),
320 '$login' => L10n::t('Login'),
322 '$lname' => ['username', L10n::t('Nickname or Email: ') , '', ''],
323 '$lpassword' => ['password', L10n::t('Password: '), '', ''],
324 '$lremember' => ['remember', L10n::t('Remember me'), 0, ''],
327 '$lopenid' => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
329 '$hiddens' => $hiddens,
333 '$lostpass' => L10n::t('Forgot your password?'),
334 '$lostlink' => L10n::t('Password Reset'),
336 '$tostitle' => L10n::t('Website Terms of Service'),
337 '$toslink' => L10n::t('terms of service'),
339 '$privacytitle' => L10n::t('Website Privacy Policy'),
340 '$privacylink' => L10n::t('privacy policy'),
344 Addon::callHooks('login_hook', $o);