]> git.mxchange.org Git - friendica.git/blob - src/Module/Login.php
Added parameters
[friendica.git] / src / Module / Login.php
1 <?php
2
3 /**
4  * @file src/Module/Login.php
5  */
6
7 namespace Friendica\Module;
8
9 use Exception;
10 use Friendica\BaseModule;
11 use Friendica\Core\Authentication;
12 use Friendica\Core\Config;
13 use Friendica\Core\Hook;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Renderer;
17 use Friendica\Core\Session;
18 use Friendica\Core\System;
19 use Friendica\Database\DBA;
20 use Friendica\Model\User;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\Strings;
24 use LightOpenID;
25
26 /**
27  * Login module
28  *
29  * @author Hypolite Petovan <hypolite@mrpetovan.com>
30  */
31 class Login extends BaseModule
32 {
33         public static function content($parameters)
34         {
35                 $a = self::getApp();
36
37                 if (local_user()) {
38                         $a->internalRedirect();
39                 }
40
41                 return self::form(Session::get('return_path'), intval(Config::get('config', 'register_policy')) !== \Friendica\Module\Register::CLOSED);
42         }
43
44         public static function post($parameters)
45         {
46                 $openid_identity = Session::get('openid_identity');
47                 $openid_server = Session::get('openid_server');
48
49                 $return_path = Session::get('return_path');
50                 session_unset();
51                 Session::set('return_path', $return_path);
52
53                 // OpenId Login
54                 if (
55                         empty($_POST['password'])
56                         && (!empty($_POST['openid_url'])
57                                 || !empty($_POST['username']))
58                 ) {
59                         $openid_url = trim(($_POST['openid_url'] ?? '') ?: $_POST['username']);
60
61                         self::openIdAuthentication($openid_url, !empty($_POST['remember']));
62                 }
63
64                 if (!empty($_POST['auth-params']) && $_POST['auth-params'] === 'login') {
65                         self::passwordAuthentication(
66                                 trim($_POST['username']),
67                                 trim($_POST['password']),
68                                 !empty($_POST['remember']),
69                                 $openid_identity,
70                                 $openid_server
71                         );
72                 }
73         }
74
75         /**
76          * Attempts to authenticate using OpenId
77          *
78          * @param string $openid_url OpenID URL string
79          * @param bool   $remember   Whether to set the session remember flag
80          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
81          */
82         private static function openIdAuthentication($openid_url, $remember)
83         {
84                 $noid = Config::get('system', 'no_openid');
85
86                 $a = self::getApp();
87
88                 // if it's an email address or doesn't resolve to a URL, fail.
89                 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
90                         notice(L10n::t('Login failed.') . EOL);
91                         $a->internalRedirect();
92                         // NOTREACHED
93                 }
94
95                 // Otherwise it's probably an openid.
96                 try {
97                         $openid = new LightOpenID($a->getHostName());
98                         $openid->identity = $openid_url;
99                         Session::set('openid', $openid_url);
100                         Session::set('remember', $remember);
101                         $openid->returnUrl = $a->getBaseURL(true) . '/openid';
102                         $openid->optional = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
103                         System::externalRedirect($openid->authUrl());
104                 } catch (Exception $e) {
105                         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());
106                 }
107         }
108
109         /**
110          * Attempts to authenticate using login/password
111          *
112          * @param string $username        User name
113          * @param string $password        Clear password
114          * @param bool   $remember        Whether to set the session remember flag
115          * @param string $openid_identity OpenID identity
116          * @param string $openid_server   OpenID URL
117          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
118          */
119         private static function passwordAuthentication($username, $password, $remember, $openid_identity, $openid_server)
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(
148                                         'user',
149                                         [],
150                                         ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
151                                 );
152                         }
153                 } catch (Exception $e) {
154                         Logger::warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
155                         info('Login failed. Please check your credentials.' . EOL);
156                         $a->internalRedirect();
157                 }
158
159                 if (!$remember) {
160                         Authentication::setCookie(0); // 0 means delete on browser exit
161                 }
162
163                 // if we haven't failed up this point, log them in.
164                 Session::set('remember', $remember);
165                 Session::set('last_login_date', DateTimeFormat::utcNow());
166
167                 if (!empty($openid_identity) || !empty($openid_server)) {
168                         DBA::update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
169                 }
170
171                 Session::setAuthenticatedForUser($a, $record, true, true);
172
173                 $return_path = Session::get('return_path', '');
174                 Session::remove('return_path');
175
176                 $a->internalRedirect($return_path);
177         }
178
179         /**
180          * @brief Tries to auth the user from the cookie or session
181          *
182          * @todo Should be moved to Friendica\Core\Session when it's created
183          */
184         public static function sessionAuth()
185         {
186                 $a = self::getApp();
187
188                 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
189                 if (isset($_COOKIE["Friendica"])) {
190                         $data = json_decode($_COOKIE["Friendica"]);
191                         if (isset($data->uid)) {
192
193                                 $user = DBA::selectFirst(
194                                         'user',
195                                         [],
196                                         [
197                                                 'uid'             => $data->uid,
198                                                 'blocked'         => false,
199                                                 'account_expired' => false,
200                                                 'account_removed' => false,
201                                                 'verified'        => true,
202                                         ]
203                                 );
204                                 if (DBA::isResult($user)) {
205                                         if (!hash_equals(
206                                                 Authentication::getCookieHashForUser($user),
207                                                 $data->hash
208                                         )) {
209                                                 Logger::log("Hash for user " . $data->uid . " doesn't fit.");
210                                                 Authentication::deleteSession();
211                                                 $a->internalRedirect();
212                                         }
213
214                                         // Renew the cookie
215                                         // Expires after 7 days by default,
216                                         // can be set via system.auth_cookie_lifetime
217                                         $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
218                                         Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
219
220                                         // Do the authentification if not done by now
221                                         if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
222                                                 Session::setAuthenticatedForUser($a, $user);
223
224                                                 if (Config::get('system', 'paranoia')) {
225                                                         $_SESSION['addr'] = $data->ip;
226                                                 }
227                                         }
228                                 }
229                         }
230                 }
231
232                 if (!empty($_SESSION['authenticated'])) {
233                         if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
234                                 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
235                                 if (DBA::isResult($contact)) {
236                                         self::getApp()->contact = $contact;
237                                 }
238                         }
239
240                         if (!empty($_SESSION['uid'])) {
241                                 // already logged in user returning
242                                 $check = Config::get('system', 'paranoia');
243                                 // extra paranoia - if the IP changed, log them out
244                                 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
245                                         Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
246                                                 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
247                                         Authentication::deleteSession();
248                                         $a->internalRedirect();
249                                 }
250
251                                 $user = DBA::selectFirst(
252                                         'user',
253                                         [],
254                                         [
255                                                 'uid'             => $_SESSION['uid'],
256                                                 'blocked'         => false,
257                                                 'account_expired' => false,
258                                                 'account_removed' => false,
259                                                 'verified'        => true,
260                                         ]
261                                 );
262                                 if (!DBA::isResult($user)) {
263                                         Authentication::deleteSession();
264                                         $a->internalRedirect();
265                                 }
266
267                                 // Make sure to refresh the last login time for the user if the user
268                                 // stays logged in for a long time, e.g. with "Remember Me"
269                                 $login_refresh = false;
270                                 if (empty($_SESSION['last_login_date'])) {
271                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
272                                 }
273                                 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
274                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
275                                         $login_refresh = true;
276                                 }
277
278                                 Session::setAuthenticatedForUser($a, $user, false, false, $login_refresh);
279                         }
280                 }
281         }
282
283         /**
284          * @brief Wrapper for adding a login box.
285          *
286          * @param string $return_path  The path relative to the base the user should be sent
287          *                             back to after login completes
288          * @param bool   $register     If $register == true provide a registration link.
289          *                             This will most always depend on the value of config.register_policy.
290          * @param array  $hiddens      optional
291          *
292          * @return string Returns the complete html for inserting into the page
293          *
294          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
295          * @hooks 'login_hook' string $o
296          */
297         public static function form($return_path = null, $register = false, $hiddens = [])
298         {
299                 $a = self::getApp();
300                 $o = '';
301
302                 $noid = Config::get('system', 'no_openid');
303
304                 if ($noid) {
305                         Session::remove('openid_identity');
306                         Session::remove('openid_attributes');
307                 }
308
309                 $reg = false;
310                 if ($register && intval($a->getConfig()->get('config', 'register_policy')) !== Register::CLOSED) {
311                         $reg = [
312                                 'title' => L10n::t('Create a New Account'),
313                                 'desc' => L10n::t('Register'),
314                                 'url' => self::getRegisterURL()
315                         ];
316                 }
317
318                 if (is_null($return_path)) {
319                         $return_path = $a->query_string;
320                 }
321
322                 if (local_user()) {
323                         $tpl = Renderer::getMarkupTemplate('logout.tpl');
324                 } else {
325                         $a->page['htmlhead'] .= Renderer::replaceMacros(
326                                 Renderer::getMarkupTemplate('login_head.tpl'),
327                                 [
328                                         '$baseurl' => $a->getBaseURL(true)
329                                 ]
330                         );
331
332                         $tpl = Renderer::getMarkupTemplate('login.tpl');
333                         $_SESSION['return_path'] = $return_path;
334                 }
335
336                 if (!empty(Session::get('openid_identity'))) {
337                         $openid_title = L10n::t('Your OpenID: ');
338                         $openid_readonly = true;
339                         $identity = Session::get('openid_identity');
340                         $username_desc = L10n::t('Please enter your username and password to add the OpenID to your existing account.');
341                 } else {
342                         $openid_title = L10n::t('Or login using OpenID: ');
343                         $openid_readonly = false;
344                         $identity = '';
345                         $username_desc = '';
346                 }
347
348                 $o .= Renderer::replaceMacros(
349                         $tpl,
350                         [
351                                 '$dest_url'     => self::getApp()->getBaseURL(true) . '/login',
352                                 '$logout'       => L10n::t('Logout'),
353                                 '$login'        => L10n::t('Login'),
354
355                                 '$lname'        => ['username', L10n::t('Nickname or Email: '), '', $username_desc],
356                                 '$lpassword'    => ['password', L10n::t('Password: '), '', ''],
357                                 '$lremember'    => ['remember', L10n::t('Remember me'), 0,  ''],
358
359                                 '$openid'       => !$noid,
360                                 '$lopenid'      => ['openid_url', $openid_title, $identity, '', $openid_readonly],
361
362                                 '$hiddens'      => $hiddens,
363
364                                 '$register'     => $reg,
365
366                                 '$lostpass'     => L10n::t('Forgot your password?'),
367                                 '$lostlink'     => L10n::t('Password Reset'),
368
369                                 '$tostitle'     => L10n::t('Website Terms of Service'),
370                                 '$toslink'      => L10n::t('terms of service'),
371
372                                 '$privacytitle' => L10n::t('Website Privacy Policy'),
373                                 '$privacylink'  => L10n::t('privacy policy'),
374                         ]
375                 );
376
377                 Hook::callAll('login_hook', $o);
378
379                 return $o;
380         }
381
382         /**
383          * Get the URL to the register page and add OpenID parameters to it
384          */
385         private static function getRegisterURL()
386         {
387                 if (empty(Session::get('openid_identity'))) {
388                         return 'register';
389                 }
390
391                 $args = [];
392                 $attr = Session::get('openid_attributes', []);
393
394                 if (is_array($attr) && count($attr)) {
395                         foreach ($attr as $k => $v) {
396                                 if ($k === 'namePerson/friendly') {
397                                         $nick = Strings::escapeTags(trim($v));
398                                 }
399                                 if ($k === 'namePerson/first') {
400                                         $first = Strings::escapeTags(trim($v));
401                                 }
402                                 if ($k === 'namePerson') {
403                                         $args['username'] = Strings::escapeTags(trim($v));
404                                 }
405                                 if ($k === 'contact/email') {
406                                         $args['email'] = Strings::escapeTags(trim($v));
407                                 }
408                                 if ($k === 'media/image/aspect11') {
409                                         $photosq = bin2hex(trim($v));
410                                 }
411                                 if ($k === 'media/image/default') {
412                                         $photo = bin2hex(trim($v));
413                                 }
414                         }
415                 }
416
417                 if (!empty($nick)) {
418                         $args['nickname'] = $nick;
419                 } elseif (!empty($first)) {
420                         $args['nickname'] = $first;
421                 }
422
423                 if (!empty($photosq)) {
424                         $args['photo'] = $photosq;
425                 } elseif (!empty($photo)) {
426                         $args['photo'] = $photo;
427                 }
428
429                 $args['openid_url'] = Strings::escapeTags(trim(Session::get('openid_identity')));
430
431                 return 'register?' . http_build_query($args);
432         }
433 }