3 * @file src/Module/Login.php
5 namespace Friendica\Module;
7 use Friendica\BaseModule;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Database\DBM;
12 use Friendica\Model\User;
13 use Friendica\Util\DateTimeFormat;
14 use Friendica\Util\Network;
19 require_once 'boot.php';
20 require_once 'include/security.php';
21 require_once 'include/text.php';
26 * @author Hypolite Petovan mrpetovan@gmail.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 goaway(self::getApp()->get_baseurl());
46 return self::form(self::getApp()->get_baseurl(), $a->config['register_policy'] != REGISTER_CLOSED);
49 public static function post()
54 empty($_POST['password'])
56 !empty($_POST['openid_url'])
57 || !empty($_POST['username'])
60 $openid_url = trim(defaults($_POST, 'openid_url', $_POST['username']));
62 self::openIdAuthentication($openid_url, !empty($_POST['remember']));
65 if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') {
66 self::passwordAuthentication(
67 trim($_POST['username']),
68 trim($_POST['password']),
69 !empty($_POST['remember'])
75 * Attempts to authenticate using OpenId
77 * @param string $openid_url OpenID URL string
78 * @param bool $remember Whether to set the session remember flag
80 private static function openIdAuthentication($openid_url, $remember)
82 $noid = Config::get('system', 'no_openid');
84 // if it's an email address or doesn't resolve to a URL, fail.
85 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
86 notice(L10n::t('Login failed.') . EOL);
87 goaway(self::getApp()->get_baseurl());
91 // Otherwise it's probably an openid.
94 $openid = new LightOpenID($a->get_hostname());
95 $openid->identity = $openid_url;
96 $_SESSION['openid'] = $openid_url;
97 $_SESSION['remember'] = $remember;
98 $openid->returnUrl = self::getApp()->get_baseurl(true) . '/openid';
99 goaway($openid->authUrl());
100 } catch (Exception $e) {
101 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());
106 * Attempts to authenticate using login/password
108 * @param string $username User name
109 * @param string $password Clear password
110 * @param bool $remember Whether to set the session remember flag
112 private static function passwordAuthentication($username, $password, $remember)
117 'username' => $username,
118 'password' => $password,
119 'authenticated' => 0,
120 'user_record' => null
124 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
125 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
126 * and later addons should not interfere with an earlier one that succeeded.
128 Addon::callHooks('authenticate', $addon_auth);
131 if ($addon_auth['authenticated']) {
132 $record = $addon_auth['user_record'];
134 if (empty($record)) {
135 throw new Exception(L10n::t('Login failed.'));
138 $record = dba::selectFirst('user', [],
139 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
142 } catch (Exception $e) {
143 logger('authenticate: failed login attempt: ' . notags($username) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
144 notice($e->getMessage() . EOL);
145 goaway(self::getApp()->get_baseurl() . '/login');
149 new_cookie(0); // 0 means delete on browser exit
152 // if we haven't failed up this point, log them in.
153 $_SESSION['remember'] = $remember;
154 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
155 authenticate_success($record, true, true);
157 if (x($_SESSION, 'return_url')) {
158 $return_url = $_SESSION['return_url'];
159 unset($_SESSION['return_url']);
168 * @brief Tries to auth the user from the cookie or session
170 * @todo Should be moved to Friendica\Core\Session when it's created
172 public static function sessionAuth()
174 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
175 if (isset($_COOKIE["Friendica"])) {
176 $data = json_decode($_COOKIE["Friendica"]);
177 if (isset($data->uid)) {
179 $user = dba::selectFirst('user', [],
183 'account_expired' => false,
184 'account_removed' => false,
188 if (DBM::is_result($user)) {
189 if ($data->hash != cookie_hash($user)) {
190 logger("Hash for user " . $data->uid . " doesn't fit.");
192 goaway(self::getApp()->get_baseurl());
196 // Expires after 7 days by default,
197 // can be set via system.auth_cookie_lifetime
198 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
199 new_cookie($authcookiedays * 24 * 60 * 60, $user);
201 // Do the authentification if not done by now
202 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
203 authenticate_success($user);
205 if (Config::get('system', 'paranoia')) {
206 $_SESSION['addr'] = $data->ip;
213 if (isset($_SESSION) && x($_SESSION, 'authenticated')) {
214 if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
215 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
216 intval($_SESSION['visitor_id'])
218 if (DBM::is_result($r)) {
219 self::getApp()->contact = $r[0];
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()->get_baseurl());
234 $user = dba::selectFirst('user', [],
236 'uid' => $_SESSION['uid'],
238 'account_expired' => false,
239 'account_removed' => false,
243 if (!DBM::is_result($user)) {
245 goaway(self::getApp()->get_baseurl());
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 (!x($_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 $a->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->get_baseurl(true)
304 $tpl = get_markup_template('login.tpl');
305 $_SESSION['return_url'] = $return_url;
308 $o .= replace_macros(
311 '$dest_url' => self::getApp()->get_baseurl(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);