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