3 * @file src/Module/Login.php
5 namespace Friendica\Module;
8 use Friendica\BaseModule;
9 use Friendica\Core\Addon;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Database\DBA;
13 use Friendica\Model\User;
14 use Friendica\Util\DateTimeFormat;
15 use Friendica\Util\Network;
18 require_once 'boot.php';
19 require_once 'include/security.php';
20 require_once 'include/text.php';
25 * @author Hypolite Petovan <hypolite@mrpetovan.com>
27 class Login extends BaseModule
29 public static function content()
33 if (x($_SESSION, 'theme')) {
34 unset($_SESSION['theme']);
37 if (x($_SESSION, 'mobile-theme')) {
38 unset($_SESSION['mobile-theme']);
42 goaway(self::getApp()->getBaseURL());
45 return self::form($_SESSION['return_url'], intval(Config::get('config', 'register_policy')) !== REGISTER_CLOSED);
48 public static function post()
50 $return_url = $_SESSION['return_url'];
52 $_SESSION['return_url'] = $return_url;
56 empty($_POST['password'])
58 !empty($_POST['openid_url'])
59 || !empty($_POST['username'])
62 $openid_url = trim(defaults($_POST, 'openid_url', $_POST['username']));
64 self::openIdAuthentication($openid_url, !empty($_POST['remember']));
67 if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') {
68 self::passwordAuthentication(
69 trim($_POST['username']),
70 trim($_POST['password']),
71 !empty($_POST['remember'])
77 * Attempts to authenticate using OpenId
79 * @param string $openid_url OpenID URL string
80 * @param bool $remember Whether to set the session remember flag
82 private static function openIdAuthentication($openid_url, $remember)
84 $noid = Config::get('system', 'no_openid');
86 // if it's an email address or doesn't resolve to a URL, fail.
87 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
88 notice(L10n::t('Login failed.') . EOL);
89 goaway(self::getApp()->getBaseURL());
93 // Otherwise it's probably an openid.
96 $openid = new LightOpenID($a->getHostName());
97 $openid->identity = $openid_url;
98 $_SESSION['openid'] = $openid_url;
99 $_SESSION['remember'] = $remember;
100 $openid->returnUrl = self::getApp()->getBaseURL(true) . '/openid';
101 goaway($openid->authUrl());
102 } catch (Exception $e) {
103 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());
108 * Attempts to authenticate using login/password
110 * @param string $username User name
111 * @param string $password Clear password
112 * @param bool $remember Whether to set the session remember flag
114 private static function passwordAuthentication($username, $password, $remember)
119 'username' => $username,
120 'password' => $password,
121 'authenticated' => 0,
122 'user_record' => null
126 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
127 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
128 * and later addons should not interfere with an earlier one that succeeded.
130 Addon::callHooks('authenticate', $addon_auth);
133 if ($addon_auth['authenticated']) {
134 $record = $addon_auth['user_record'];
136 if (empty($record)) {
137 throw new Exception(L10n::t('Login failed.'));
140 $record = DBA::selectFirst('user', [],
141 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
144 } catch (Exception $e) {
145 logger('authenticate: failed login attempt: ' . notags($username) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
146 info('Login failed. Please check your credentials.' . EOL);
151 new_cookie(0); // 0 means delete on browser exit
154 // if we haven't failed up this point, log them in.
155 $_SESSION['remember'] = $remember;
156 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
157 authenticate_success($record, true, true);
159 if (x($_SESSION, 'return_url')) {
160 $return_url = $_SESSION['return_url'];
161 unset($_SESSION['return_url']);
170 * @brief Tries to auth the user from the cookie or session
172 * @todo Should be moved to Friendica\Core\Session when it's created
174 public static function sessionAuth()
176 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
177 if (isset($_COOKIE["Friendica"])) {
178 $data = json_decode($_COOKIE["Friendica"]);
179 if (isset($data->uid)) {
181 $user = DBA::selectFirst('user', [],
185 'account_expired' => false,
186 'account_removed' => false,
190 if (DBA::isResult($user)) {
191 if ($data->hash != cookie_hash($user)) {
192 logger("Hash for user " . $data->uid . " doesn't fit.");
194 goaway(self::getApp()->getBaseURL());
198 // Expires after 7 days by default,
199 // can be set via system.auth_cookie_lifetime
200 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
201 new_cookie($authcookiedays * 24 * 60 * 60, $user);
203 // Do the authentification if not done by now
204 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
205 authenticate_success($user);
207 if (Config::get('system', 'paranoia')) {
208 $_SESSION['addr'] = $data->ip;
215 if (isset($_SESSION) && x($_SESSION, 'authenticated')) {
216 if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
217 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
218 if (DBA::isResult($contact)) {
219 self::getApp()->contact = $contact;
223 if (x($_SESSION, 'uid')) {
224 // already logged in user returning
225 $check = Config::get('system', 'paranoia');
226 // extra paranoia - if the IP changed, log them out
227 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
228 logger('Session address changed. Paranoid setting in effect, blocking session. ' .
229 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
231 goaway(self::getApp()->getBaseURL());
234 $user = DBA::selectFirst('user', [],
236 'uid' => $_SESSION['uid'],
238 'account_expired' => false,
239 'account_removed' => false,
243 if (!DBA::isResult($user)) {
245 goaway(self::getApp()->getBaseURL());
248 // Make sure to refresh the last login time for the user if the user
249 // stays logged in for a long time, e.g. with "Remember Me"
250 $login_refresh = false;
251 if (empty($_SESSION['last_login_date'])) {
252 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
254 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
255 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
256 $login_refresh = true;
258 authenticate_success($user, false, false, $login_refresh);
264 * @brief Wrapper for adding a login box.
266 * @param string $return_url The url relative to the base the user should be sent
267 * back to after login completes
268 * @param bool $register If $register == true provide a registration link.
269 * This will most always depend on the value of config.register_policy.
270 * @param array $hiddens optional
272 * @return string Returns the complete html for inserting into the page
274 * @hooks 'login_hook' string $o
276 public static function form($return_url = null, $register = false, $hiddens = [])
283 'title' => L10n::t('Create a New Account'),
284 'desc' => L10n::t('Register')
288 $noid = Config::get('system', 'no_openid');
290 if (is_null($return_url)) {
291 $return_url = $a->query_string;
295 $tpl = get_markup_template('logout.tpl');
297 $a->page['htmlhead'] .= replace_macros(
298 get_markup_template('login_head.tpl'),
300 '$baseurl' => $a->getBaseURL(true)
304 $tpl = get_markup_template('login.tpl');
305 $_SESSION['return_url'] = $return_url;
308 $o .= replace_macros(
311 '$dest_url' => self::getApp()->getBaseURL(true) . '/login',
312 '$logout' => L10n::t('Logout'),
313 '$login' => L10n::t('Login'),
315 '$lname' => ['username', L10n::t('Nickname or Email: ') , '', ''],
316 '$lpassword' => ['password', L10n::t('Password: '), '', ''],
317 '$lremember' => ['remember', L10n::t('Remember me'), 0, ''],
320 '$lopenid' => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
322 '$hiddens' => $hiddens,
326 '$lostpass' => L10n::t('Forgot your password?'),
327 '$lostlink' => L10n::t('Password Reset'),
329 '$tostitle' => L10n::t('Website Terms of Service'),
330 '$toslink' => L10n::t('terms of service'),
332 '$privacytitle' => L10n::t('Website Privacy Policy'),
333 '$privacylink' => L10n::t('privacy policy'),
337 Addon::callHooks('login_hook', $o);