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\System;
14 use Friendica\Database\DBA;
15 use Friendica\Model\User;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Network;
20 require_once 'boot.php';
21 require_once 'include/text.php';
26 * @author Hypolite Petovan <hypolite@mrpetovan.com>
28 class Login extends BaseModule
30 public static function content()
34 if (x($_SESSION, 'theme')) {
35 unset($_SESSION['theme']);
38 if (x($_SESSION, 'mobile-theme')) {
39 unset($_SESSION['mobile-theme']);
43 $a->internalRedirect();
46 return self::form($_SESSION['return_path'], intval(Config::get('config', 'register_policy')) !== REGISTER_CLOSED);
49 public static function post()
51 $return_path = $_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 (x($_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
83 private static function openIdAuthentication($openid_url, $remember)
85 $noid = Config::get('system', 'no_openid');
89 // if it's an email address or doesn't resolve to a URL, fail.
90 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
91 notice(L10n::t('Login failed.') . EOL);
92 $a->internalRedirect();
96 // Otherwise it's probably an openid.
98 $openid = new LightOpenID($a->getHostName());
99 $openid->identity = $openid_url;
100 $_SESSION['openid'] = $openid_url;
101 $_SESSION['remember'] = $remember;
102 $openid->returnUrl = $a->getBaseURL(true) . '/openid';
103 System::externalRedirect($openid->authUrl());
104 } catch (Exception $e) {
105 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());
110 * Attempts to authenticate using login/password
112 * @param string $username User name
113 * @param string $password Clear password
114 * @param bool $remember Whether to set the session remember flag
116 private static function passwordAuthentication($username, $password, $remember)
121 'username' => $username,
122 'password' => $password,
123 'authenticated' => 0,
124 'user_record' => null
130 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
131 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
132 * and later addons should not interfere with an earlier one that succeeded.
134 Addon::callHooks('authenticate', $addon_auth);
137 if ($addon_auth['authenticated']) {
138 $record = $addon_auth['user_record'];
140 if (empty($record)) {
141 throw new Exception(L10n::t('Login failed.'));
144 $record = DBA::selectFirst('user', [],
145 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
148 } catch (Exception $e) {
149 logger('authenticate: failed login attempt: ' . notags($username) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
150 info('Login failed. Please check your credentials.' . EOL);
151 $a->internalRedirect();
155 Authentication::setCookie(0); // 0 means delete on browser exit
158 // if we haven't failed up this point, log them in.
159 $_SESSION['remember'] = $remember;
160 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
161 Authentication::setAuthenticatedSessionForUser($record, true, true);
163 if (x($_SESSION, 'return_path')) {
164 $return_path = $_SESSION['return_path'];
165 unset($_SESSION['return_path']);
170 $a->internalRedirect($return_path);
174 * @brief Tries to auth the user from the cookie or session
176 * @todo Should be moved to Friendica\Core\Session when it's created
178 public static function sessionAuth()
182 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
183 if (isset($_COOKIE["Friendica"])) {
184 $data = json_decode($_COOKIE["Friendica"]);
185 if (isset($data->uid)) {
187 $user = DBA::selectFirst('user', [],
191 'account_expired' => false,
192 'account_removed' => false,
196 if (DBA::isResult($user)) {
197 if ($data->hash != Authentication::getCookieHashForUser($user)) {
198 logger("Hash for user " . $data->uid . " doesn't fit.");
199 Authentication::deleteSession();
200 $a->internalRedirect();
204 // Expires after 7 days by default,
205 // can be set via system.auth_cookie_lifetime
206 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
207 Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
209 // Do the authentification if not done by now
210 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
211 Authentication::setAuthenticatedSessionForUser($user);
213 if (Config::get('system', 'paranoia')) {
214 $_SESSION['addr'] = $data->ip;
221 if (isset($_SESSION) && x($_SESSION, 'authenticated')) {
222 if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
223 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
224 if (DBA::isResult($contact)) {
225 self::getApp()->contact = $contact;
229 if (x($_SESSION, 'uid')) {
230 // already logged in user returning
231 $check = Config::get('system', 'paranoia');
232 // extra paranoia - if the IP changed, log them out
233 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
234 logger('Session address changed. Paranoid setting in effect, blocking session. ' .
235 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
236 Authentication::deleteSession();
237 $a->internalRedirect();
240 $user = DBA::selectFirst('user', [],
242 'uid' => $_SESSION['uid'],
244 'account_expired' => false,
245 'account_removed' => false,
249 if (!DBA::isResult($user)) {
250 Authentication::deleteSession();
251 $a->internalRedirect();
254 // Make sure to refresh the last login time for the user if the user
255 // stays logged in for a long time, e.g. with "Remember Me"
256 $login_refresh = false;
257 if (empty($_SESSION['last_login_date'])) {
258 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
260 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
261 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
262 $login_refresh = true;
264 Authentication::setAuthenticatedSessionForUser($user, false, false, $login_refresh);
270 * @brief Wrapper for adding a login box.
272 * @param string $return_path The path relative to the base the user should be sent
273 * back to after login completes
274 * @param bool $register If $register == true provide a registration link.
275 * This will most always depend on the value of config.register_policy.
276 * @param array $hiddens optional
278 * @return string Returns the complete html for inserting into the page
280 * @hooks 'login_hook' string $o
282 public static function form($return_path = null, $register = false, $hiddens = [])
289 'title' => L10n::t('Create a New Account'),
290 'desc' => L10n::t('Register')
294 $noid = Config::get('system', 'no_openid');
296 if (is_null($return_path)) {
297 $return_path = $a->query_string;
301 $tpl = get_markup_template('logout.tpl');
303 $a->page['htmlhead'] .= replace_macros(
304 get_markup_template('login_head.tpl'),
306 '$baseurl' => $a->getBaseURL(true)
310 $tpl = get_markup_template('login.tpl');
311 $_SESSION['return_path'] = $return_path;
314 $o .= replace_macros(
317 '$dest_url' => self::getApp()->getBaseURL(true) . '/login',
318 '$logout' => L10n::t('Logout'),
319 '$login' => L10n::t('Login'),
321 '$lname' => ['username', L10n::t('Nickname or Email: ') , '', ''],
322 '$lpassword' => ['password', L10n::t('Password: '), '', ''],
323 '$lremember' => ['remember', L10n::t('Remember me'), 0, ''],
326 '$lopenid' => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
328 '$hiddens' => $hiddens,
332 '$lostpass' => L10n::t('Forgot your password?'),
333 '$lostlink' => L10n::t('Password Reset'),
335 '$tostitle' => L10n::t('Website Terms of Service'),
336 '$toslink' => L10n::t('terms of service'),
338 '$privacytitle' => L10n::t('Website Privacy Policy'),
339 '$privacylink' => L10n::t('privacy policy'),
343 Addon::callHooks('login_hook', $o);