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 <hypolite@mrpetovan.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 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
215 if (DBA::isResult($contact)) {
216 self::getApp()->contact = $contact;
220 if (x($_SESSION, 'uid')) {
221 // already logged in user returning
222 $check = Config::get('system', 'paranoia');
223 // extra paranoia - if the IP changed, log them out
224 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
225 logger('Session address changed. Paranoid setting in effect, blocking session. ' .
226 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
228 goaway(self::getApp()->get_baseurl());
231 $user = DBA::selectFirst('user', [],
233 'uid' => $_SESSION['uid'],
235 'account_expired' => false,
236 'account_removed' => false,
240 if (!DBA::isResult($user)) {
242 goaway(self::getApp()->get_baseurl());
245 // Make sure to refresh the last login time for the user if the user
246 // stays logged in for a long time, e.g. with "Remember Me"
247 $login_refresh = false;
248 if (empty($_SESSION['last_login_date'])) {
249 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
251 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
252 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
253 $login_refresh = true;
255 authenticate_success($user, false, false, $login_refresh);
261 * @brief Wrapper for adding a login box.
263 * @param string $return_url The url relative to the base the user should be sent
264 * back to after login completes
265 * @param bool $register If $register == true provide a registration link.
266 * This will most always depend on the value of config.register_policy.
267 * @param array $hiddens optional
269 * @return string Returns the complete html for inserting into the page
271 * @hooks 'login_hook' string $o
273 public static function form($return_url = null, $register = false, $hiddens = [])
280 'title' => L10n::t('Create a New Account'),
281 'desc' => L10n::t('Register')
285 $noid = Config::get('system', 'no_openid');
287 if (is_null($return_url)) {
288 $return_url = $a->query_string;
292 $tpl = get_markup_template('logout.tpl');
294 $a->page['htmlhead'] .= replace_macros(
295 get_markup_template('login_head.tpl'),
297 '$baseurl' => $a->get_baseurl(true)
301 $tpl = get_markup_template('login.tpl');
302 $_SESSION['return_url'] = $return_url;
305 $o .= replace_macros(
308 '$dest_url' => self::getApp()->get_baseurl(true) . '/login',
309 '$logout' => L10n::t('Logout'),
310 '$login' => L10n::t('Login'),
312 '$lname' => ['username', L10n::t('Nickname or Email: ') , '', ''],
313 '$lpassword' => ['password', L10n::t('Password: '), '', ''],
314 '$lremember' => ['remember', L10n::t('Remember me'), 0, ''],
317 '$lopenid' => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
319 '$hiddens' => $hiddens,
323 '$lostpass' => L10n::t('Forgot your password?'),
324 '$lostlink' => L10n::t('Password Reset'),
326 '$tostitle' => L10n::t('Website Terms of Service'),
327 '$toslink' => L10n::t('terms of service'),
329 '$privacytitle' => L10n::t('Website Privacy Policy'),
330 '$privacylink' => L10n::t('privacy policy'),
334 Addon::callHooks('login_hook', $o);