]> git.mxchange.org Git - friendica.git/blob - src/Module/Login.php
Merge pull request #7167 from MrPetovan/bug/7150-unescape-xml-entities
[friendica.git] / src / Module / Login.php
1 <?php
2 /**
3  * @file src/Module/Login.php
4  */
5 namespace Friendica\Module;
6
7 use Exception;
8 use Friendica\BaseModule;
9 use Friendica\Core\Authentication;
10 use Friendica\Core\Config;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Renderer;
15 use Friendica\Core\Session;
16 use Friendica\Core\System;
17 use Friendica\Database\DBA;
18 use Friendica\Model\User;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Util\Strings;
22 use LightOpenID;
23
24 /**
25  * Login module
26  *
27  * @author Hypolite Petovan <hypolite@mrpetovan.com>
28  */
29 class Login extends BaseModule
30 {
31         public static function content()
32         {
33                 $a = self::getApp();
34
35                 if (!empty($_SESSION['theme'])) {
36                         unset($_SESSION['theme']);
37                 }
38
39                 if (!empty($_SESSION['mobile-theme'])) {
40                         unset($_SESSION['mobile-theme']);
41                 }
42
43                 if (local_user()) {
44                         $a->internalRedirect();
45                 }
46
47                 return self::form(defaults($_SESSION, 'return_path', null), intval(Config::get('config', 'register_policy')) !== \Friendica\Module\Register::CLOSED);
48         }
49
50         public static function post()
51         {
52                 $return_path = defaults($_SESSION, 'return_path', '');
53                 session_unset();
54                 $_SESSION['return_path'] = $return_path;
55
56                 // OpenId Login
57                 if (
58                         empty($_POST['password'])
59                         && (
60                                 !empty($_POST['openid_url'])
61                                 || !empty($_POST['username'])
62                         )
63                 ) {
64                         $openid_url = trim(defaults($_POST, 'openid_url', $_POST['username']));
65
66                         self::openIdAuthentication($openid_url, !empty($_POST['remember']));
67                 }
68
69                 if (!empty($_POST['auth-params']) && $_POST['auth-params'] === 'login') {
70                         self::passwordAuthentication(
71                                 trim($_POST['username']),
72                                 trim($_POST['password']),
73                                 !empty($_POST['remember'])
74                         );
75                 }
76         }
77
78         /**
79          * Attempts to authenticate using OpenId
80          *
81          * @param string $openid_url OpenID URL string
82          * @param bool   $remember   Whether to set the session remember flag
83          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
84          */
85         private static function openIdAuthentication($openid_url, $remember)
86         {
87                 $noid = Config::get('system', 'no_openid');
88
89                 $a = self::getApp();
90
91                 // if it's an email address or doesn't resolve to a URL, fail.
92                 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
93                         notice(L10n::t('Login failed.') . EOL);
94                         $a->internalRedirect();
95                         // NOTREACHED
96                 }
97
98                 // Otherwise it's probably an openid.
99                 try {
100                         $openid = new LightOpenID($a->getHostName());
101                         $openid->identity = $openid_url;
102                         $_SESSION['openid'] = $openid_url;
103                         $_SESSION['remember'] = $remember;
104                         $openid->returnUrl = $a->getBaseURL(true) . '/openid';
105                         System::externalRedirect($openid->authUrl());
106                 } catch (Exception $e) {
107                         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());
108                 }
109         }
110
111         /**
112          * Attempts to authenticate using login/password
113          *
114          * @param string $username User name
115          * @param string $password Clear password
116          * @param bool   $remember Whether to set the session remember flag
117          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
118          */
119         private static function passwordAuthentication($username, $password, $remember)
120         {
121                 $record = null;
122
123                 $addon_auth = [
124                         'username' => $username,
125                         'password' => $password,
126                         'authenticated' => 0,
127                         'user_record' => null
128                 ];
129
130                 $a = self::getApp();
131
132                 /*
133                  * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
134                  * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
135                  * and later addons should not interfere with an earlier one that succeeded.
136                  */
137                 Hook::callAll('authenticate', $addon_auth);
138
139                 try {
140                         if ($addon_auth['authenticated']) {
141                                 $record = $addon_auth['user_record'];
142
143                                 if (empty($record)) {
144                                         throw new Exception(L10n::t('Login failed.'));
145                                 }
146                         } else {
147                                 $record = DBA::selectFirst('user', [],
148                                         ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
149                                 );
150                         }
151                 } catch (Exception $e) {
152                         Logger::warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
153                         info('Login failed. Please check your credentials.' . EOL);
154                         $a->internalRedirect();
155                 }
156
157                 if (!$remember) {
158                         Authentication::setCookie(0); // 0 means delete on browser exit
159                 }
160
161                 // if we haven't failed up this point, log them in.
162                 $_SESSION['remember'] = $remember;
163                 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
164
165                 Session::setAuthenticatedForUser($a, $record, true, true);
166
167                 if (!empty($_SESSION['return_path'])) {
168                         $return_path = $_SESSION['return_path'];
169                         unset($_SESSION['return_path']);
170                 } else {
171                         $return_path = '';
172                 }
173
174                 $a->internalRedirect($return_path);
175         }
176
177         /**
178          * @brief Tries to auth the user from the cookie or session
179          *
180          * @todo Should be moved to Friendica\Core\Session when it's created
181          */
182         public static function sessionAuth()
183         {
184                 $a = self::getApp();
185
186                 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
187                 if (isset($_COOKIE["Friendica"])) {
188                         $data = json_decode($_COOKIE["Friendica"]);
189                         if (isset($data->uid)) {
190
191                                 $user = DBA::selectFirst('user', [],
192                                         [
193                                                 'uid'             => $data->uid,
194                                                 'blocked'         => false,
195                                                 'account_expired' => false,
196                                                 'account_removed' => false,
197                                                 'verified'        => true,
198                                         ]
199                                 );
200                                 if (DBA::isResult($user)) {
201                                         if ($data->hash != Authentication::getCookieHashForUser($user)) {
202                                                 Logger::log("Hash for user " . $data->uid . " doesn't fit.");
203                                                 Authentication::deleteSession();
204                                                 $a->internalRedirect();
205                                         }
206
207                                         // Renew the cookie
208                                         // Expires after 7 days by default,
209                                         // can be set via system.auth_cookie_lifetime
210                                         $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
211                                         Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
212
213                                         // Do the authentification if not done by now
214                                         if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
215                                                 Session::setAuthenticatedForUser($a, $user);
216
217                                                 if (Config::get('system', 'paranoia')) {
218                                                         $_SESSION['addr'] = $data->ip;
219                                                 }
220                                         }
221                                 }
222                         }
223                 }
224
225                 if (!empty($_SESSION['authenticated'])) {
226                         if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
227                                 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
228                                 if (DBA::isResult($contact)) {
229                                         self::getApp()->contact = $contact;
230                                 }
231                         }
232
233                         if (!empty($_SESSION['uid'])) {
234                                 // already logged in user returning
235                                 $check = Config::get('system', 'paranoia');
236                                 // extra paranoia - if the IP changed, log them out
237                                 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
238                                         Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
239                                                 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
240                                         Authentication::deleteSession();
241                                         $a->internalRedirect();
242                                 }
243
244                                 $user = DBA::selectFirst('user', [],
245                                         [
246                                                 'uid'             => $_SESSION['uid'],
247                                                 'blocked'         => false,
248                                                 'account_expired' => false,
249                                                 'account_removed' => false,
250                                                 'verified'        => true,
251                                         ]
252                                 );
253                                 if (!DBA::isResult($user)) {
254                                         Authentication::deleteSession();
255                                         $a->internalRedirect();
256                                 }
257
258                                 // Make sure to refresh the last login time for the user if the user
259                                 // stays logged in for a long time, e.g. with "Remember Me"
260                                 $login_refresh = false;
261                                 if (empty($_SESSION['last_login_date'])) {
262                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
263                                 }
264                                 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
265                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
266                                         $login_refresh = true;
267                                 }
268
269                                 Session::setAuthenticatedForUser($a, $user, false, false, $login_refresh);
270                         }
271                 }
272         }
273
274         /**
275          * @brief Wrapper for adding a login box.
276          *
277          * @param string $return_path  The path relative to the base the user should be sent
278          *                             back to after login completes
279          * @param bool   $register     If $register == true provide a registration link.
280          *                             This will most always depend on the value of config.register_policy.
281          * @param array  $hiddens      optional
282          *
283          * @return string Returns the complete html for inserting into the page
284          *
285          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
286          * @hooks 'login_hook' string $o
287          */
288         public static function form($return_path = null, $register = false, $hiddens = [])
289         {
290                 $a = self::getApp();
291                 $o = '';
292                 $reg = false;
293                 if ($register) {
294                         $reg = [
295                                 'title' => L10n::t('Create a New Account'),
296                                 'desc' => L10n::t('Register')
297                         ];
298                 }
299
300                 $noid = Config::get('system', 'no_openid');
301
302                 if (is_null($return_path)) {
303                         $return_path = $a->query_string;
304                 }
305
306                 if (local_user()) {
307                         $tpl = Renderer::getMarkupTemplate('logout.tpl');
308                 } else {
309                         $a->page['htmlhead'] .= Renderer::replaceMacros(
310                                 Renderer::getMarkupTemplate('login_head.tpl'),
311                                 [
312                                         '$baseurl' => $a->getBaseURL(true)
313                                 ]
314                         );
315
316                         $tpl = Renderer::getMarkupTemplate('login.tpl');
317                         $_SESSION['return_path'] = $return_path;
318                 }
319
320                 $o .= Renderer::replaceMacros(
321                         $tpl,
322                         [
323                                 '$dest_url'     => self::getApp()->getBaseURL(true) . '/login',
324                                 '$logout'       => L10n::t('Logout'),
325                                 '$login'        => L10n::t('Login'),
326
327                                 '$lname'        => ['username', L10n::t('Nickname or Email: ') , '', ''],
328                                 '$lpassword'    => ['password', L10n::t('Password: '), '', ''],
329                                 '$lremember'    => ['remember', L10n::t('Remember me'), 0,  ''],
330
331                                 '$openid'       => !$noid,
332                                 '$lopenid'      => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
333
334                                 '$hiddens'      => $hiddens,
335
336                                 '$register'     => $reg,
337
338                                 '$lostpass'     => L10n::t('Forgot your password?'),
339                                 '$lostlink'     => L10n::t('Password Reset'),
340
341                                 '$tostitle'     => L10n::t('Website Terms of Service'),
342                                 '$toslink'      => L10n::t('terms of service'),
343
344                                 '$privacytitle' => L10n::t('Website Privacy Policy'),
345                                 '$privacylink'  => L10n::t('privacy policy'),
346                         ]
347                 );
348
349                 Hook::callAll('login_hook', $o);
350
351                 return $o;
352         }
353 }