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