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 mrpetovan@gmail.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()->get_baseurl());
45 return self::form(self::getApp()->get_baseurl(), intval(Config::get('config', 'register_policy')) !== REGISTER_CLOSED);
48 public static function post()
53 empty($_POST['password'])
55 !empty($_POST['openid_url'])
56 || !empty($_POST['username'])
59 $openid_url = trim(defaults($_POST, 'openid_url', $_POST['username']));
61 self::openIdAuthentication($openid_url, !empty($_POST['remember']));
64 if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') {
65 self::passwordAuthentication(
66 trim($_POST['username']),
67 trim($_POST['password']),
68 !empty($_POST['remember'])
74 * Attempts to authenticate using OpenId
76 * @param string $openid_url OpenID URL string
77 * @param bool $remember Whether to set the session remember flag
79 private static function openIdAuthentication($openid_url, $remember)
81 $noid = Config::get('system', 'no_openid');
83 // if it's an email address or doesn't resolve to a URL, fail.
84 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
85 notice(L10n::t('Login failed.') . EOL);
86 goaway(self::getApp()->get_baseurl());
90 // Otherwise it's probably an openid.
93 $openid = new LightOpenID($a->get_hostname());
94 $openid->identity = $openid_url;
95 $_SESSION['openid'] = $openid_url;
96 $_SESSION['remember'] = $remember;
97 $openid->returnUrl = self::getApp()->get_baseurl(true) . '/openid';
98 goaway($openid->authUrl());
99 } catch (Exception $e) {
100 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());
105 * Attempts to authenticate using login/password
107 * @param string $username User name
108 * @param string $password Clear password
109 * @param bool $remember Whether to set the session remember flag
111 private static function passwordAuthentication($username, $password, $remember)
116 'username' => $username,
117 'password' => $password,
118 'authenticated' => 0,
119 'user_record' => null
123 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
124 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
125 * and later addons should not interfere with an earlier one that succeeded.
127 Addon::callHooks('authenticate', $addon_auth);
130 if ($addon_auth['authenticated']) {
131 $record = $addon_auth['user_record'];
133 if (empty($record)) {
134 throw new Exception(L10n::t('Login failed.'));
137 $record = DBA::selectFirst('user', [],
138 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
141 } catch (Exception $e) {
142 logger('authenticate: failed login attempt: ' . notags($username) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
143 notice($e->getMessage() . EOL);
144 goaway(self::getApp()->get_baseurl() . '/login');
148 new_cookie(0); // 0 means delete on browser exit
151 // if we haven't failed up this point, log them in.
152 $_SESSION['remember'] = $remember;
153 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
154 authenticate_success($record, true, true);
156 if (x($_SESSION, 'return_url')) {
157 $return_url = $_SESSION['return_url'];
158 unset($_SESSION['return_url']);
167 * @brief Tries to auth the user from the cookie or session
169 * @todo Should be moved to Friendica\Core\Session when it's created
171 public static function sessionAuth()
173 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
174 if (isset($_COOKIE["Friendica"])) {
175 $data = json_decode($_COOKIE["Friendica"]);
176 if (isset($data->uid)) {
178 $user = DBA::selectFirst('user', [],
182 'account_expired' => false,
183 'account_removed' => false,
187 if (DBA::isResult($user)) {
188 if ($data->hash != cookie_hash($user)) {
189 logger("Hash for user " . $data->uid . " doesn't fit.");
191 goaway(self::getApp()->get_baseurl());
195 // Expires after 7 days by default,
196 // can be set via system.auth_cookie_lifetime
197 $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
198 new_cookie($authcookiedays * 24 * 60 * 60, $user);
200 // Do the authentification if not done by now
201 if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
202 authenticate_success($user);
204 if (Config::get('system', 'paranoia')) {
205 $_SESSION['addr'] = $data->ip;
212 if (isset($_SESSION) && x($_SESSION, 'authenticated')) {
213 if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
214 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
215 intval($_SESSION['visitor_id'])
217 if (DBA::isResult($r)) {
218 self::getApp()->contact = $r[0];
222 if (x($_SESSION, 'uid')) {
223 // already logged in user returning
224 $check = Config::get('system', 'paranoia');
225 // extra paranoia - if the IP changed, log them out
226 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
227 logger('Session address changed. Paranoid setting in effect, blocking session. ' .
228 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
230 goaway(self::getApp()->get_baseurl());
233 $user = DBA::selectFirst('user', [],
235 'uid' => $_SESSION['uid'],
237 'account_expired' => false,
238 'account_removed' => false,
242 if (!DBA::isResult($user)) {
244 goaway(self::getApp()->get_baseurl());
247 // Make sure to refresh the last login time for the user if the user
248 // stays logged in for a long time, e.g. with "Remember Me"
249 $login_refresh = false;
250 if (empty($_SESSION['last_login_date'])) {
251 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
253 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
254 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
255 $login_refresh = true;
257 authenticate_success($user, false, false, $login_refresh);
263 * @brief Wrapper for adding a login box.
265 * @param string $return_url The url relative to the base the user should be sent
266 * back to after login completes
267 * @param bool $register If $register == true provide a registration link.
268 * This will most always depend on the value of config.register_policy.
269 * @param array $hiddens optional
271 * @return string Returns the complete html for inserting into the page
273 * @hooks 'login_hook' string $o
275 public static function form($return_url = null, $register = false, $hiddens = [])
282 'title' => L10n::t('Create a New Account'),
283 'desc' => L10n::t('Register')
287 $noid = Config::get('system', 'no_openid');
289 if (is_null($return_url)) {
290 $return_url = $a->query_string;
294 $tpl = get_markup_template('logout.tpl');
296 $a->page['htmlhead'] .= replace_macros(
297 get_markup_template('login_head.tpl'),
299 '$baseurl' => $a->get_baseurl(true)
303 $tpl = get_markup_template('login.tpl');
304 $_SESSION['return_url'] = $return_url;
307 $o .= replace_macros(
310 '$dest_url' => self::getApp()->get_baseurl(true) . '/login',
311 '$logout' => L10n::t('Logout'),
312 '$login' => L10n::t('Login'),
314 '$lname' => ['username', L10n::t('Nickname or Email: ') , '', ''],
315 '$lpassword' => ['password', L10n::t('Password: '), '', ''],
316 '$lremember' => ['remember', L10n::t('Remember me'), 0, ''],
319 '$lopenid' => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
321 '$hiddens' => $hiddens,
325 '$lostpass' => L10n::t('Forgot your password?'),
326 '$lostlink' => L10n::t('Password Reset'),
328 '$tostitle' => L10n::t('Website Terms of Service'),
329 '$toslink' => L10n::t('terms of service'),
331 '$privacytitle' => L10n::t('Website Privacy Policy'),
332 '$privacylink' => L10n::t('privacy policy'),
336 Addon::callHooks('login_hook', $o);