]> git.mxchange.org Git - friendica.git/blob - src/Module/Login.php
Add new module and widget for managing saved searches
[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 (local_user()) {
36                         $a->internalRedirect();
37                 }
38
39                 return self::form(Session::get('return_path'), intval(Config::get('config', 'register_policy')) !== \Friendica\Module\Register::CLOSED);
40         }
41
42         public static function post()
43         {
44                 $return_path = Session::get('return_path');
45                 session_unset();
46                 Session::set('return_path', $return_path);
47
48                 // OpenId Login
49                 if (
50                         empty($_POST['password'])
51                         && (
52                                 !empty($_POST['openid_url'])
53                                 || !empty($_POST['username'])
54                         )
55                 ) {
56                         $openid_url = trim(defaults($_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('user', [],
140                                         ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
141                                 );
142                         }
143                 } catch (Exception $e) {
144                         Logger::warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
145                         info('Login failed. Please check your credentials.' . EOL);
146                         $a->internalRedirect();
147                 }
148
149                 if (!$remember) {
150                         Authentication::setCookie(0); // 0 means delete on browser exit
151                 }
152
153                 // if we haven't failed up this point, log them in.
154                 Session::set('remember', $remember);
155                 Session::set('last_login_date', DateTimeFormat::utcNow());
156
157                 Session::setAuthenticatedForUser($a, $record, true, true);
158
159                 $return_path = Session::get('return_path', '');
160                 Session::remove('return_path');
161
162                 $a->internalRedirect($return_path);
163         }
164
165         /**
166          * @brief Tries to auth the user from the cookie or session
167          *
168          * @todo Should be moved to Friendica\Core\Session when it's created
169          */
170         public static function sessionAuth()
171         {
172                 $a = self::getApp();
173
174                 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
175                 if (isset($_COOKIE["Friendica"])) {
176                         $data = json_decode($_COOKIE["Friendica"]);
177                         if (isset($data->uid)) {
178
179                                 $user = DBA::selectFirst('user', [],
180                                         [
181                                                 'uid'             => $data->uid,
182                                                 'blocked'         => false,
183                                                 'account_expired' => false,
184                                                 'account_removed' => false,
185                                                 'verified'        => true,
186                                         ]
187                                 );
188                                 if (DBA::isResult($user)) {
189                                         if ($data->hash != Authentication::getCookieHashForUser($user)) {
190                                                 Logger::log("Hash for user " . $data->uid . " doesn't fit.");
191                                                 Authentication::deleteSession();
192                                                 $a->internalRedirect();
193                                         }
194
195                                         // Renew the cookie
196                                         // Expires after 7 days by default,
197                                         // can be set via system.auth_cookie_lifetime
198                                         $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
199                                         Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
200
201                                         // Do the authentification if not done by now
202                                         if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
203                                                 Session::setAuthenticatedForUser($a, $user);
204
205                                                 if (Config::get('system', 'paranoia')) {
206                                                         $_SESSION['addr'] = $data->ip;
207                                                 }
208                                         }
209                                 }
210                         }
211                 }
212
213                 if (!empty($_SESSION['authenticated'])) {
214                         if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
215                                 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
216                                 if (DBA::isResult($contact)) {
217                                         self::getApp()->contact = $contact;
218                                 }
219                         }
220
221                         if (!empty($_SESSION['uid'])) {
222                                 // already logged in user returning
223                                 $check = Config::get('system', 'paranoia');
224                                 // extra paranoia - if the IP changed, log them out
225                                 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
226                                         Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
227                                                 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
228                                         Authentication::deleteSession();
229                                         $a->internalRedirect();
230                                 }
231
232                                 $user = DBA::selectFirst('user', [],
233                                         [
234                                                 'uid'             => $_SESSION['uid'],
235                                                 'blocked'         => false,
236                                                 'account_expired' => false,
237                                                 'account_removed' => false,
238                                                 'verified'        => true,
239                                         ]
240                                 );
241                                 if (!DBA::isResult($user)) {
242                                         Authentication::deleteSession();
243                                         $a->internalRedirect();
244                                 }
245
246                                 // Make sure to refresh the last login time for the user if the user
247                                 // stays logged in for a long time, e.g. with "Remember Me"
248                                 $login_refresh = false;
249                                 if (empty($_SESSION['last_login_date'])) {
250                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
251                                 }
252                                 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
253                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
254                                         $login_refresh = true;
255                                 }
256
257                                 Session::setAuthenticatedForUser($a, $user, false, false, $login_refresh);
258                         }
259                 }
260         }
261
262         /**
263          * @brief Wrapper for adding a login box.
264          *
265          * @param string $return_path  The path relative to the base the user should be sent
266          *                             back to after login completes
267          * @param bool   $register     If $register == true provide a registration link.
268          *                             This will most always depend on the value of config.register_policy.
269          * @param array  $hiddens      optional
270          *
271          * @return string Returns the complete html for inserting into the page
272          *
273          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
274          * @hooks 'login_hook' string $o
275          */
276         public static function form($return_path = null, $register = false, $hiddens = [])
277         {
278                 $a = self::getApp();
279                 $o = '';
280                 $reg = false;
281                 if ($register && intval($a->getConfig()->get('config', 'register_policy')) !== Register::CLOSED) {
282                         $reg = [
283                                 'title' => L10n::t('Create a New Account'),
284                                 'desc' => L10n::t('Register')
285                         ];
286                 }
287
288                 $noid = Config::get('system', 'no_openid');
289
290                 if (is_null($return_path)) {
291                         $return_path = $a->query_string;
292                 }
293
294                 if (local_user()) {
295                         $tpl = Renderer::getMarkupTemplate('logout.tpl');
296                 } else {
297                         $a->page['htmlhead'] .= Renderer::replaceMacros(
298                                 Renderer::getMarkupTemplate('login_head.tpl'),
299                                 [
300                                         '$baseurl' => $a->getBaseURL(true)
301                                 ]
302                         );
303
304                         $tpl = Renderer::getMarkupTemplate('login.tpl');
305                         $_SESSION['return_path'] = $return_path;
306                 }
307
308                 $o .= Renderer::replaceMacros(
309                         $tpl,
310                         [
311                                 '$dest_url'     => self::getApp()->getBaseURL(true) . '/login',
312                                 '$logout'       => L10n::t('Logout'),
313                                 '$login'        => L10n::t('Login'),
314
315                                 '$lname'        => ['username', L10n::t('Nickname or Email: ') , '', ''],
316                                 '$lpassword'    => ['password', L10n::t('Password: '), '', ''],
317                                 '$lremember'    => ['remember', L10n::t('Remember me'), 0,  ''],
318
319                                 '$openid'       => !$noid,
320                                 '$lopenid'      => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
321
322                                 '$hiddens'      => $hiddens,
323
324                                 '$register'     => $reg,
325
326                                 '$lostpass'     => L10n::t('Forgot your password?'),
327                                 '$lostlink'     => L10n::t('Password Reset'),
328
329                                 '$tostitle'     => L10n::t('Website Terms of Service'),
330                                 '$toslink'      => L10n::t('terms of service'),
331
332                                 '$privacytitle' => L10n::t('Website Privacy Policy'),
333                                 '$privacylink'  => L10n::t('privacy policy'),
334                         ]
335                 );
336
337                 Hook::callAll('login_hook', $o);
338
339                 return $o;
340         }
341 }