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