3 namespace Friendica\Module;
5 use Friendica\BaseModule;
6 use Friendica\Core\Addon;
7 use Friendica\Core\Config;
8 use Friendica\Database\DBM;
9 use Friendica\Model\User;
12 require_once 'boot.php';
13 require_once 'include/datetime.php';
14 require_once 'include/pgettext.php';
15 require_once 'include/security.php';
16 require_once 'include/text.php';
21 * @author Hypolite Petovan mrpetovan@gmail.com
23 class Login extends BaseModule
25 public static function content()
29 if (x($_SESSION, 'theme')) {
30 unset($_SESSION['theme']);
33 if (x($_SESSION, 'mobile-theme')) {
34 unset($_SESSION['mobile-theme']);
38 goaway(self::getApp()->get_baseurl());
41 return self::form(self::getApp()->get_baseurl(), $a->config['register_policy'] != REGISTER_CLOSED);
44 public static function post()
49 !x($_POST, 'password')
51 x($_POST, 'openid_url')
52 || x($_POST, 'username')
55 $noid = Config::get('system', 'no_openid');
57 $openid_url = trim($_POST['openid_url'] ? : $_POST['username']);
59 // if it's an email address or doesn't resolve to a URL, fail.
60 if ($noid || strpos($openid_url, '@') || !validate_url($openid_url)) {
61 notice(t('Login failed.') . EOL);
62 goaway(self::getApp()->get_baseurl());
66 // Otherwise it's probably an openid.
68 require_once 'library/openid.php';
69 $openid = new \LightOpenID;
70 $openid->identity = $openid_url;
71 $_SESSION['openid'] = $openid_url;
72 $_SESSION['remember'] = $_POST['remember'];
73 $openid->returnUrl = self::getApp()->get_baseurl(true) . '/openid';
74 goaway($openid->authUrl());
75 } catch (Exception $e) {
76 notice(t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . '<br /><br >' . t('The error message was:') . ' ' . $e->getMessage());
81 if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') {
85 'username' => trim($_POST['username']),
86 'password' => trim($_POST['password']),
92 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
93 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
94 * and later addons should not interfere with an earlier one that succeeded.
96 Addon::callHooks('authenticate', $addon_auth);
98 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
99 $record = $addon_auth['user_record'];
101 $user_id = User::authenticate(trim($_POST['username']), trim($_POST['password']));
103 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
107 if (!$record || !count($record)) {
108 logger('authenticate: failed login attempt: ' . notags(trim($_POST['username'])) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
109 notice(t('Login failed.') . EOL);
110 goaway(self::getApp()->get_baseurl());
113 if (!$_POST['remember']) {
114 new_cookie(0); // 0 means delete on browser exit
117 // if we haven't failed up this point, log them in.
118 $_SESSION['remember'] = $_POST['remember'];
119 $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
120 authenticate_success($record, true, true);
122 if (x($_SESSION, 'return_url')) {
123 $return_url = $_SESSION['return_url'];
124 unset($_SESSION['return_url']);
134 * @brief Tries to auth the user from the cookie or session
136 * @todo Should be moved to Friendica\Core\Session when it's created
138 public static function sessionAuth()
140 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
141 if (isset($_COOKIE["Friendica"])) {
142 $data = json_decode($_COOKIE["Friendica"]);
143 if (isset($data->uid)) {
145 $user = dba::selectFirst('user', [],
149 'account_expired' => false,
150 'account_removed' => false,
154 if (DBM::is_result($user)) {
155 if ($data->hash != cookie_hash($user)) {
156 logger("Hash for user " . $data->uid . " doesn't fit.");
158 goaway(self::getApp()->get_baseurl());
162 // Expires after 7 days by default,
163 // can be set via system.auth_cookie_lifetime
164 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
165 new_cookie($authcookiedays * 24 * 60 * 60, $user);
167 // Do the authentification if not done by now
168 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
169 authenticate_success($user);
171 if (Config::get('system', 'paranoia')) {
172 $_SESSION['addr'] = $data->ip;
179 if (isset($_SESSION) && x($_SESSION, 'authenticated')) {
180 if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
181 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
182 intval($_SESSION['visitor_id'])
184 if (DBM::is_result($r)) {
185 self::getApp()->contact = $r[0];
189 if (x($_SESSION, 'uid')) {
190 // already logged in user returning
191 $check = Config::get('system', 'paranoia');
192 // extra paranoia - if the IP changed, log them out
193 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
194 logger('Session address changed. Paranoid setting in effect, blocking session. ' .
195 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
197 goaway(self::getApp()->get_baseurl());
200 $user = dba::selectFirst('user', [],
202 'uid' => $_SESSION['uid'],
204 'account_expired' => false,
205 'account_removed' => false,
209 if (!DBM::is_result($user)) {
211 goaway(self::getApp()->get_baseurl());
214 // Make sure to refresh the last login time for the user if the user
215 // stays logged in for a long time, e.g. with "Remember Me"
216 $login_refresh = false;
217 if (!x($_SESSION['last_login_date'])) {
218 $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
220 if (strcmp(datetime_convert('UTC', 'UTC', 'now - 12 hours'), $_SESSION['last_login_date']) > 0) {
221 $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
222 $login_refresh = true;
224 authenticate_success($user, false, false, $login_refresh);
230 * @brief Wrapper for adding a login box.
232 * @param string $return_url The url relative to the base the user should be sent
233 * back to after login completes
234 * @param bool $register If $register == true provide a registration link.
235 * This will most always depend on the value of $a->config['register_policy'].
236 * @param array $hiddens optional
238 * @return string Returns the complete html for inserting into the page
240 * @hooks 'login_hook' string $o
242 public static function form($return_url = null, $register = false, $hiddens = [])
249 'title' => t('Create a New Account'),
250 'desc' => t('Register')
254 $noid = Config::get('system', 'no_openid');
256 if (is_null($return_url)) {
257 $return_url = $a->query_string;
261 $tpl = get_markup_template('logout.tpl');
263 $a->page['htmlhead'] .= replace_macros(
264 get_markup_template('login_head.tpl'),
266 '$baseurl' => $a->get_baseurl(true)
270 $tpl = get_markup_template('login.tpl');
271 $_SESSION['return_url'] = $return_url;
274 $o .= replace_macros(
277 '$dest_url' => self::getApp()->get_baseurl(true) . '/login',
278 '$logout' => t('Logout'),
279 '$login' => t('Login'),
281 '$lname' => ['username', t('Nickname or Email: ') , '', ''],
282 '$lpassword' => ['password', t('Password: '), '', ''],
283 '$lremember' => ['remember', t('Remember me'), 0, ''],
286 '$lopenid' => ['openid_url', t('Or login using OpenID: '),'',''],
288 '$hiddens' => $hiddens,
292 '$lostpass' => t('Forgot your password?'),
293 '$lostlink' => t('Password Reset'),
295 '$tostitle' => t('Website Terms of Service'),
296 '$toslink' => t('terms of service'),
298 '$privacytitle' => t('Website Privacy Policy'),
299 '$privacylink' => t('privacy policy'),
303 Addon::callHooks('login_hook', $o);