]> git.mxchange.org Git - friendica.git/blob - src/Module/Login.php
Fix mods/README.md format
[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\Renderer;
15 use Friendica\Core\System;
16 use Friendica\Database\DBA;
17 use Friendica\Model\User;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Network;
20 use Friendica\Util\Strings;
21 use LightOpenID;
22
23 require_once 'boot.php';
24 require_once 'include/text.php';
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 (!empty($_SESSION['theme'])) {
38                         unset($_SESSION['theme']);
39                 }
40
41                 if (!empty($_SESSION['mobile-theme'])) {
42                         unset($_SESSION['mobile-theme']);
43                 }
44
45                 if (local_user()) {
46                         $a->internalRedirect();
47                 }
48
49                 return self::form(defaults($_SESSION, 'return_path', null), intval(Config::get('config', 'register_policy')) !== REGISTER_CLOSED);
50         }
51
52         public static function post()
53         {
54                 $return_path = $_SESSION['return_path'];
55                 session_unset();
56                 $_SESSION['return_path'] = $return_path;
57                 
58                 // OpenId Login
59                 if (
60                         empty($_POST['password'])
61                         && (
62                                 !empty($_POST['openid_url'])
63                                 || !empty($_POST['username'])
64                         )
65                 ) {
66                         $openid_url = trim(defaults($_POST, 'openid_url', $_POST['username']));
67
68                         self::openIdAuthentication($openid_url, !empty($_POST['remember']));
69                 }
70
71                 if (!empty($_POST['auth-params']) && $_POST['auth-params'] === 'login') {
72                         self::passwordAuthentication(
73                                 trim($_POST['username']),
74                                 trim($_POST['password']),
75                                 !empty($_POST['remember'])
76                         );
77                 }
78         }
79
80         /**
81          * Attempts to authenticate using OpenId
82          *
83          * @param string $openid_url OpenID URL string
84          * @param bool   $remember   Whether to set the session remember flag
85          */
86         private static function openIdAuthentication($openid_url, $remember)
87         {
88                 $noid = Config::get('system', 'no_openid');
89
90                 $a = self::getApp();
91
92                 // if it's an email address or doesn't resolve to a URL, fail.
93                 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
94                         notice(L10n::t('Login failed.') . EOL);
95                         $a->internalRedirect();
96                         // NOTREACHED
97                 }
98
99                 // Otherwise it's probably an openid.
100                 try {
101                         $openid = new LightOpenID($a->getHostName());
102                         $openid->identity = $openid_url;
103                         $_SESSION['openid'] = $openid_url;
104                         $_SESSION['remember'] = $remember;
105                         $openid->returnUrl = $a->getBaseURL(true) . '/openid';
106                         System::externalRedirect($openid->authUrl());
107                 } catch (Exception $e) {
108                         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());
109                 }
110         }
111
112         /**
113          * Attempts to authenticate using login/password
114          *
115          * @param string $username User name
116          * @param string $password Clear password
117          * @param bool   $remember Whether to set the session remember flag
118          */
119         private static function passwordAuthentication($username, $password, $remember)
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                 Addon::callHooks('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('user', [],
148                                         ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
149                                 );
150                         }
151                 } catch (Exception $e) {
152                         Logger::log('authenticate: failed login attempt: ' . Strings::escapeTags($username) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
153                         info('Login failed. Please check your credentials.' . EOL);
154                         $a->internalRedirect();
155                 }
156
157                 if (!$remember) {
158                         Authentication::setCookie(0); // 0 means delete on browser exit
159                 }
160
161                 // if we haven't failed up this point, log them in.
162                 $_SESSION['remember'] = $remember;
163                 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
164                 Authentication::setAuthenticatedSessionForUser($record, true, true);
165
166                 if (!empty($_SESSION['return_path'])) {
167                         $return_path = $_SESSION['return_path'];
168                         unset($_SESSION['return_path']);
169                 } else {
170                         $return_path = '';
171                 }
172
173                 $a->internalRedirect($return_path);
174         }
175
176         /**
177          * @brief Tries to auth the user from the cookie or session
178          *
179          * @todo Should be moved to Friendica\Core\Session when it's created
180          */
181         public static function sessionAuth()
182         {
183                 $a = self::getApp();
184
185                 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
186                 if (isset($_COOKIE["Friendica"])) {
187                         $data = json_decode($_COOKIE["Friendica"]);
188                         if (isset($data->uid)) {
189
190                                 $user = DBA::selectFirst('user', [],
191                                         [
192                                                 'uid'             => $data->uid,
193                                                 'blocked'         => false,
194                                                 'account_expired' => false,
195                                                 'account_removed' => false,
196                                                 'verified'        => true,
197                                         ]
198                                 );
199                                 if (DBA::isResult($user)) {
200                                         if ($data->hash != Authentication::getCookieHashForUser($user)) {
201                                                 Logger::log("Hash for user " . $data->uid . " doesn't fit.");
202                                                 Authentication::deleteSession();
203                                                 $a->internalRedirect();
204                                         }
205
206                                         // Renew the cookie
207                                         // Expires after 7 days by default,
208                                         // can be set via system.auth_cookie_lifetime
209                                         $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
210                                         Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
211
212                                         // Do the authentification if not done by now
213                                         if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
214                                                 Authentication::setAuthenticatedSessionForUser($user);
215
216                                                 if (Config::get('system', 'paranoia')) {
217                                                         $_SESSION['addr'] = $data->ip;
218                                                 }
219                                         }
220                                 }
221                         }
222                 }
223
224                 if (!empty($_SESSION['authenticated'])) {
225                         if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
226                                 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
227                                 if (DBA::isResult($contact)) {
228                                         self::getApp()->contact = $contact;
229                                 }
230                         }
231
232                         if (!empty($_SESSION['uid'])) {
233                                 // already logged in user returning
234                                 $check = Config::get('system', 'paranoia');
235                                 // extra paranoia - if the IP changed, log them out
236                                 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
237                                         Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
238                                                 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
239                                         Authentication::deleteSession();
240                                         $a->internalRedirect();
241                                 }
242
243                                 $user = DBA::selectFirst('user', [],
244                                         [
245                                                 'uid'             => $_SESSION['uid'],
246                                                 'blocked'         => false,
247                                                 'account_expired' => false,
248                                                 'account_removed' => false,
249                                                 'verified'        => true,
250                                         ]
251                                 );
252                                 if (!DBA::isResult($user)) {
253                                         Authentication::deleteSession();
254                                         $a->internalRedirect();
255                                 }
256
257                                 // Make sure to refresh the last login time for the user if the user
258                                 // stays logged in for a long time, e.g. with "Remember Me"
259                                 $login_refresh = false;
260                                 if (empty($_SESSION['last_login_date'])) {
261                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
262                                 }
263                                 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
264                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
265                                         $login_refresh = true;
266                                 }
267                                 Authentication::setAuthenticatedSessionForUser($user, false, false, $login_refresh);
268                         }
269                 }
270         }
271
272         /**
273          * @brief Wrapper for adding a login box.
274          *
275          * @param string $return_path The path relative to the base the user should be sent
276          *                                                       back to after login completes
277          * @param bool $register If $register == true provide a registration link.
278          *                                               This will most always depend on the value of config.register_policy.
279          * @param array $hiddens  optional
280          *
281          * @return string Returns the complete html for inserting into the page
282          *
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) {
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                 Addon::callHooks('login_hook', $o);
347
348                 return $o;
349         }
350 }