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