3 namespace Friendica\Module;
5 use Friendica\BaseModule;
6 use Friendica\Core\Config;
7 use Friendica\Database\DBM;
8 use Friendica\Model\User;
11 require_once 'boot.php';
12 require_once 'include/datetime.php';
13 require_once 'include/pgettext.php';
14 require_once 'include/security.php';
15 require_once 'include/text.php';
20 * @author Hypolite Petovan mrpetovan@gmail.com
22 class Login extends BaseModule
24 public static function content()
28 if (x($_SESSION, 'theme')) {
29 unset($_SESSION['theme']);
32 if (x($_SESSION, 'mobile-theme')) {
33 unset($_SESSION['mobile-theme']);
37 goaway(self::getApp()->get_baseurl());
40 return self::form(self::getApp()->get_baseurl(), $a->config['register_policy'] != REGISTER_CLOSED);
43 public static function post()
48 !x($_POST, 'password')
50 x($_POST, 'openid_url')
51 || x($_POST, 'username')
54 $noid = Config::get('system', 'no_openid');
56 $openid_url = trim($_POST['openid_url'] ? : $_POST['username']);
58 // if it's an email address or doesn't resolve to a URL, fail.
59 if ($noid || strpos($openid_url, '@') || !validate_url($openid_url)) {
60 notice(t('Login failed.') . EOL);
61 goaway(self::getApp()->get_baseurl());
65 // Otherwise it's probably an openid.
67 require_once 'library/openid.php';
68 $openid = new LightOpenID;
69 $openid->identity = $openid_url;
70 $_SESSION['openid'] = $openid_url;
71 $_SESSION['remember'] = $_POST['remember'];
72 $openid->returnUrl = self::getApp()->get_baseurl(true) . '/openid';
73 goaway($openid->authUrl());
74 } catch (Exception $e) {
75 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());
80 if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') {
84 'username' => trim($_POST['username']),
85 'password' => trim($_POST['password']),
91 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
92 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
93 * and later plugins should not interfere with an earlier one that succeeded.
95 call_hooks('authenticate', $addon_auth);
97 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
98 $record = $addon_auth['user_record'];
100 $user_id = User::authenticate(trim($_POST['username']), trim($_POST['password']));
102 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
106 if (!$record || !count($record)) {
107 logger('authenticate: failed login attempt: ' . notags(trim($_POST['username'])) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
108 notice(t('Login failed.') . EOL);
109 goaway(self::getApp()->get_baseurl());
112 if (!$_POST['remember']) {
113 new_cookie(0); // 0 means delete on browser exit
116 // if we haven't failed up this point, log them in.
117 $_SESSION['remember'] = $_POST['remember'];
118 $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
119 authenticate_success($record, true, true);
121 if (x($_SESSION, 'return_url')) {
122 $return_url = $_SESSION['return_url'];
123 unset($_SESSION['return_url']);
133 * @brief Tries to auth the user from the cookie or session
135 * @todo Should be moved to Friendica\Core\Session when it's created
137 public static function sessionAuth()
139 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
140 if (isset($_COOKIE["Friendica"])) {
141 $data = json_decode($_COOKIE["Friendica"]);
142 if (isset($data->uid)) {
144 $user = dba::selectFirst('user', [],
148 'account_expired' => false,
149 'account_removed' => false,
153 if (DBM::is_result($user)) {
154 if ($data->hash != cookie_hash($user)) {
155 logger("Hash for user " . $data->uid . " doesn't fit.");
157 goaway(self::getApp()->get_baseurl());
161 // Expires after 7 days by default,
162 // can be set via system.auth_cookie_lifetime
163 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
164 new_cookie($authcookiedays * 24 * 60 * 60, $user);
166 // Do the authentification if not done by now
167 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
168 authenticate_success($user);
170 if (Config::get('system', 'paranoia')) {
171 $_SESSION['addr'] = $data->ip;
178 if (isset($_SESSION) && x($_SESSION, 'authenticated')) {
179 if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
180 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
181 intval($_SESSION['visitor_id'])
183 if (DBM::is_result($r)) {
184 self::getApp()->contact = $r[0];
188 if (x($_SESSION, 'uid')) {
189 // already logged in user returning
190 $check = Config::get('system', 'paranoia');
191 // extra paranoia - if the IP changed, log them out
192 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
193 logger('Session address changed. Paranoid setting in effect, blocking session. ' .
194 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
196 goaway(self::getApp()->get_baseurl());
199 $user = dba::selectFirst('user', [],
201 'uid' => $_SESSION['uid'],
203 'account_expired' => false,
204 'account_removed' => false,
208 if (!DBM::is_result($user)) {
210 goaway(self::getApp()->get_baseurl());
213 // Make sure to refresh the last login time for the user if the user
214 // stays logged in for a long time, e.g. with "Remember Me"
215 $login_refresh = false;
216 if (!x($_SESSION['last_login_date'])) {
217 $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
219 if (strcmp(datetime_convert('UTC', 'UTC', 'now - 12 hours'), $_SESSION['last_login_date']) > 0) {
220 $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
221 $login_refresh = true;
223 authenticate_success($user, false, false, $login_refresh);
229 * @brief Wrapper for adding a login box.
231 * @param string $return_url The url relative to the base the user should be sent
232 * back to after login completes
233 * @param bool $register If $register == true provide a registration link.
234 * This will most always depend on the value of $a->config['register_policy'].
235 * @param array $hiddens optional
237 * @return string Returns the complete html for inserting into the page
239 * @hooks 'login_hook' string $o
241 public static function form($return_url = null, $register = false, $hiddens = [])
248 'title' => t('Create a New Account'),
249 'desc' => t('Register')
253 $noid = Config::get('system', 'no_openid');
255 if (is_null($return_url)) {
256 $return_url = $a->query_string;
260 $tpl = get_markup_template('logout.tpl');
262 $a->page['htmlhead'] .= replace_macros(
263 get_markup_template('login_head.tpl'),
265 '$baseurl' => $a->get_baseurl(true)
269 $tpl = get_markup_template('login.tpl');
270 $_SESSION['return_url'] = $return_url;
273 $o .= replace_macros(
276 '$dest_url' => self::getApp()->get_baseurl(true) . '/login',
277 '$logout' => t('Logout'),
278 '$login' => t('Login'),
280 '$lname' => array('username', t('Nickname or Email: ') , '', ''),
281 '$lpassword' => array('password', t('Password: '), '', ''),
282 '$lremember' => array('remember', t('Remember me'), 0, ''),
285 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
287 '$hiddens' => $hiddens,
291 '$lostpass' => t('Forgot your password?'),
292 '$lostlink' => t('Password Reset'),
294 '$tostitle' => t('Website Terms of Service'),
295 '$toslink' => t('terms of service'),
297 '$privacytitle' => t('Website Privacy Policy'),
298 '$privacylink' => t('privacy policy'),
302 call_hooks('login_hook', $o);