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;
15 require_once 'boot.php';
16 require_once 'include/datetime.php';
17 require_once 'include/security.php';
18 require_once 'include/text.php';
23 * @author Hypolite Petovan mrpetovan@gmail.com
25 class Login extends BaseModule
27 public static function content()
31 if (x($_SESSION, 'theme')) {
32 unset($_SESSION['theme']);
35 if (x($_SESSION, 'mobile-theme')) {
36 unset($_SESSION['mobile-theme']);
40 goaway(self::getApp()->get_baseurl());
43 return self::form(self::getApp()->get_baseurl(), $a->config['register_policy'] != REGISTER_CLOSED);
46 public static function post()
51 !x($_POST, 'password')
53 x($_POST, 'openid_url')
54 || x($_POST, 'username')
57 $noid = Config::get('system', 'no_openid');
59 $openid_url = trim($_POST['openid_url'] ? : $_POST['username']);
61 // if it's an email address or doesn't resolve to a URL, fail.
62 if ($noid || strpos($openid_url, '@') || !validate_url($openid_url)) {
63 notice(L10n::t('Login failed.') . EOL);
64 goaway(self::getApp()->get_baseurl());
68 // Otherwise it's probably an openid.
70 require_once 'library/openid.php';
71 $openid = new \LightOpenID;
72 $openid->identity = $openid_url;
73 $_SESSION['openid'] = $openid_url;
74 $_SESSION['remember'] = $_POST['remember'];
75 $openid->returnUrl = self::getApp()->get_baseurl(true) . '/openid';
76 goaway($openid->authUrl());
77 } catch (Exception $e) {
78 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());
83 if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') {
87 'username' => trim($_POST['username']),
88 'password' => trim($_POST['password']),
94 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
95 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
96 * and later addons should not interfere with an earlier one that succeeded.
98 Addon::callHooks('authenticate', $addon_auth);
100 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
101 $record = $addon_auth['user_record'];
103 $user_id = User::authenticate(trim($_POST['username']), trim($_POST['password']));
105 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
109 if (!$record || !count($record)) {
110 logger('authenticate: failed login attempt: ' . notags(trim($_POST['username'])) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
111 notice(L10n::t('Login failed.') . EOL);
112 goaway(self::getApp()->get_baseurl());
115 if (!$_POST['remember']) {
116 new_cookie(0); // 0 means delete on browser exit
119 // if we haven't failed up this point, log them in.
120 $_SESSION['remember'] = $_POST['remember'];
121 $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
122 authenticate_success($record, true, true);
124 if (x($_SESSION, 'return_url')) {
125 $return_url = $_SESSION['return_url'];
126 unset($_SESSION['return_url']);
136 * @brief Tries to auth the user from the cookie or session
138 * @todo Should be moved to Friendica\Core\Session when it's created
140 public static function sessionAuth()
142 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
143 if (isset($_COOKIE["Friendica"])) {
144 $data = json_decode($_COOKIE["Friendica"]);
145 if (isset($data->uid)) {
147 $user = dba::selectFirst('user', [],
151 'account_expired' => false,
152 'account_removed' => false,
156 if (DBM::is_result($user)) {
157 if ($data->hash != cookie_hash($user)) {
158 logger("Hash for user " . $data->uid . " doesn't fit.");
160 goaway(self::getApp()->get_baseurl());
164 // Expires after 7 days by default,
165 // can be set via system.auth_cookie_lifetime
166 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
167 new_cookie($authcookiedays * 24 * 60 * 60, $user);
169 // Do the authentification if not done by now
170 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
171 authenticate_success($user);
173 if (Config::get('system', 'paranoia')) {
174 $_SESSION['addr'] = $data->ip;
181 if (isset($_SESSION) && x($_SESSION, 'authenticated')) {
182 if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
183 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
184 intval($_SESSION['visitor_id'])
186 if (DBM::is_result($r)) {
187 self::getApp()->contact = $r[0];
191 if (x($_SESSION, 'uid')) {
192 // already logged in user returning
193 $check = Config::get('system', 'paranoia');
194 // extra paranoia - if the IP changed, log them out
195 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
196 logger('Session address changed. Paranoid setting in effect, blocking session. ' .
197 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
199 goaway(self::getApp()->get_baseurl());
202 $user = dba::selectFirst('user', [],
204 'uid' => $_SESSION['uid'],
206 'account_expired' => false,
207 'account_removed' => false,
211 if (!DBM::is_result($user)) {
213 goaway(self::getApp()->get_baseurl());
216 // Make sure to refresh the last login time for the user if the user
217 // stays logged in for a long time, e.g. with "Remember Me"
218 $login_refresh = false;
219 if (!x($_SESSION['last_login_date'])) {
220 $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
222 if (strcmp(datetime_convert('UTC', 'UTC', 'now - 12 hours'), $_SESSION['last_login_date']) > 0) {
223 $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
224 $login_refresh = true;
226 authenticate_success($user, false, false, $login_refresh);
232 * @brief Wrapper for adding a login box.
234 * @param string $return_url The url relative to the base the user should be sent
235 * back to after login completes
236 * @param bool $register If $register == true provide a registration link.
237 * This will most always depend on the value of $a->config['register_policy'].
238 * @param array $hiddens optional
240 * @return string Returns the complete html for inserting into the page
242 * @hooks 'login_hook' string $o
244 public static function form($return_url = null, $register = false, $hiddens = [])
251 'title' => L10n::t('Create a New Account'),
252 'desc' => L10n::t('Register')
256 $noid = Config::get('system', 'no_openid');
258 if (is_null($return_url)) {
259 $return_url = $a->query_string;
263 $tpl = get_markup_template('logout.tpl');
265 $a->page['htmlhead'] .= replace_macros(
266 get_markup_template('login_head.tpl'),
268 '$baseurl' => $a->get_baseurl(true)
272 $tpl = get_markup_template('login.tpl');
273 $_SESSION['return_url'] = $return_url;
276 $o .= replace_macros(
279 '$dest_url' => self::getApp()->get_baseurl(true) . '/login',
280 '$logout' => L10n::t('Logout'),
281 '$login' => L10n::t('Login'),
283 '$lname' => ['username', L10n::t('Nickname or Email: ') , '', ''],
284 '$lpassword' => ['password', L10n::t('Password: '), '', ''],
285 '$lremember' => ['remember', L10n::t('Remember me'), 0, ''],
288 '$lopenid' => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
290 '$hiddens' => $hiddens,
294 '$lostpass' => L10n::t('Forgot your password?'),
295 '$lostlink' => L10n::t('Password Reset'),
297 '$tostitle' => L10n::t('Website Terms of Service'),
298 '$toslink' => L10n::t('terms of service'),
300 '$privacytitle' => L10n::t('Website Privacy Policy'),
301 '$privacylink' => L10n::t('privacy policy'),
305 Addon::callHooks('login_hook', $o);