]> git.mxchange.org Git - friendica.git/blob - src/Module/Login.php
fccf8b9d85f6e347ee044987ada3fc9fbf456708
[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\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Database\DBA;
13 use Friendica\Database\DBM;
14 use Friendica\Model\User;
15 use Friendica\Util\DateTimeFormat;
16 use Friendica\Util\Network;
17 use LightOpenID;
18
19 require_once 'boot.php';
20 require_once 'include/security.php';
21 require_once 'include/text.php';
22
23 /**
24  * Login module
25  *
26  * @author Hypolite Petovan mrpetovan@gmail.com
27  */
28 class Login extends BaseModule
29 {
30         public static function content()
31         {
32                 $a = self::getApp();
33
34                 if (x($_SESSION, 'theme')) {
35                         unset($_SESSION['theme']);
36                 }
37
38                 if (x($_SESSION, 'mobile-theme')) {
39                         unset($_SESSION['mobile-theme']);
40                 }
41
42                 if (local_user()) {
43                         goaway(self::getApp()->get_baseurl());
44                 }
45
46                 return self::form(self::getApp()->get_baseurl(), intval(Config::get('config', 'register_policy')) !== REGISTER_CLOSED);
47         }
48
49         public static function post()
50         {
51                 session_unset();
52                 // OpenId Login
53                 if (
54                         empty($_POST['password'])
55                         && (
56                                 !empty($_POST['openid_url'])
57                                 || !empty($_POST['username'])
58                         )
59                 ) {
60                         $openid_url = trim(defaults($_POST, 'openid_url', $_POST['username']));
61
62                         self::openIdAuthentication($openid_url, !empty($_POST['remember']));
63                 }
64
65                 if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') {
66                         self::passwordAuthentication(
67                                 trim($_POST['username']),
68                                 trim($_POST['password']),
69                                 !empty($_POST['remember'])
70                         );
71                 }
72         }
73
74         /**
75          * Attempts to authenticate using OpenId
76          *
77          * @param string $openid_url OpenID URL string
78          * @param bool   $remember   Whether to set the session remember flag
79          */
80         private static function openIdAuthentication($openid_url, $remember)
81         {
82                 $noid = Config::get('system', 'no_openid');
83
84                 // if it's an email address or doesn't resolve to a URL, fail.
85                 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
86                         notice(L10n::t('Login failed.') . EOL);
87                         goaway(self::getApp()->get_baseurl());
88                         // NOTREACHED
89                 }
90
91                 // Otherwise it's probably an openid.
92                 try {
93                         $a = get_app();
94                         $openid = new LightOpenID($a->get_hostname());
95                         $openid->identity = $openid_url;
96                         $_SESSION['openid'] = $openid_url;
97                         $_SESSION['remember'] = $remember;
98                         $openid->returnUrl = self::getApp()->get_baseurl(true) . '/openid';
99                         goaway($openid->authUrl());
100                 } catch (Exception $e) {
101                         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());
102                 }
103         }
104
105         /**
106          * Attempts to authenticate using login/password
107          *
108          * @param string $username User name
109          * @param string $password Clear password
110          * @param bool   $remember Whether to set the session remember flag
111          */
112         private static function passwordAuthentication($username, $password, $remember)
113         {
114                 $record = null;
115
116                 $addon_auth = [
117                         'username' => $username,
118                         'password' => $password,
119                         'authenticated' => 0,
120                         'user_record' => null
121                 ];
122
123                 /*
124                  * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
125                  * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
126                  * and later addons should not interfere with an earlier one that succeeded.
127                  */
128                 Addon::callHooks('authenticate', $addon_auth);
129
130                 try {
131                         if ($addon_auth['authenticated']) {
132                                 $record = $addon_auth['user_record'];
133
134                                 if (empty($record)) {
135                                         throw new Exception(L10n::t('Login failed.'));
136                                 }
137                         } else {
138                                 $record = DBA::selectFirst('user', [],
139                                         ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
140                                 );
141                         }
142                 } catch (Exception $e) {
143                         logger('authenticate: failed login attempt: ' . notags($username) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
144                         notice($e->getMessage() . EOL);
145                         goaway(self::getApp()->get_baseurl() . '/login');
146                 }
147
148                 if (!$remember) {
149                         new_cookie(0); // 0 means delete on browser exit
150                 }
151
152                 // if we haven't failed up this point, log them in.
153                 $_SESSION['remember'] = $remember;
154                 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
155                 authenticate_success($record, true, true);
156
157                 if (x($_SESSION, 'return_url')) {
158                         $return_url = $_SESSION['return_url'];
159                         unset($_SESSION['return_url']);
160                 } else {
161                         $return_url = '';
162                 }
163
164                 goaway($return_url);
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                 // 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 (DBM::is_result($user)) {
189                                         if ($data->hash != cookie_hash($user)) {
190                                                 logger("Hash for user " . $data->uid . " doesn't fit.");
191                                                 nuke_session();
192                                                 goaway(self::getApp()->get_baseurl());
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                                         new_cookie($authcookiedays * 24 * 60 * 60, $user);
200
201                                         // Do the authentification if not done by now
202                                         if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
203                                                 authenticate_success($user);
204
205                                                 if (Config::get('system', 'paranoia')) {
206                                                         $_SESSION['addr'] = $data->ip;
207                                                 }
208                                         }
209                                 }
210                         }
211                 }
212
213                 if (isset($_SESSION) && x($_SESSION, 'authenticated')) {
214                         if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
215                                 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
216                                         intval($_SESSION['visitor_id'])
217                                 );
218                                 if (DBM::is_result($r)) {
219                                         self::getApp()->contact = $r[0];
220                                 }
221                         }
222
223                         if (x($_SESSION, 'uid')) {
224                                 // already logged in user returning
225                                 $check = Config::get('system', 'paranoia');
226                                 // extra paranoia - if the IP changed, log them out
227                                 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
228                                         logger('Session address changed. Paranoid setting in effect, blocking session. ' .
229                                                 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
230                                         nuke_session();
231                                         goaway(self::getApp()->get_baseurl());
232                                 }
233
234                                 $user = DBA::selectFirst('user', [],
235                                         [
236                                                 'uid'             => $_SESSION['uid'],
237                                                 'blocked'         => false,
238                                                 'account_expired' => false,
239                                                 'account_removed' => false,
240                                                 'verified'        => true,
241                                         ]
242                                 );
243                                 if (!DBM::is_result($user)) {
244                                         nuke_session();
245                                         goaway(self::getApp()->get_baseurl());
246                                 }
247
248                                 // Make sure to refresh the last login time for the user if the user
249                                 // stays logged in for a long time, e.g. with "Remember Me"
250                                 $login_refresh = false;
251                                 if (empty($_SESSION['last_login_date'])) {
252                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
253                                 }
254                                 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
255                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
256                                         $login_refresh = true;
257                                 }
258                                 authenticate_success($user, false, false, $login_refresh);
259                         }
260                 }
261         }
262
263         /**
264          * @brief Wrapper for adding a login box.
265          *
266          * @param string $return_url The url relative to the base the user should be sent
267          *                                                       back to after login completes
268          * @param bool $register If $register == true provide a registration link.
269          *                                               This will most always depend on the value of config.register_policy.
270          * @param array $hiddens  optional
271          *
272          * @return string Returns the complete html for inserting into the page
273          *
274          * @hooks 'login_hook' string $o
275          */
276         public static function form($return_url = null, $register = false, $hiddens = [])
277         {
278                 $a = self::getApp();
279                 $o = '';
280                 $reg = false;
281                 if ($register) {
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_url)) {
291                         $return_url = $a->query_string;
292                 }
293
294                 if (local_user()) {
295                         $tpl = get_markup_template('logout.tpl');
296                 } else {
297                         $a->page['htmlhead'] .= replace_macros(
298                                 get_markup_template('login_head.tpl'),
299                                 [
300                                         '$baseurl' => $a->get_baseurl(true)
301                                 ]
302                         );
303
304                         $tpl = get_markup_template('login.tpl');
305                         $_SESSION['return_url'] = $return_url;
306                 }
307
308                 $o .= replace_macros(
309                         $tpl,
310                         [
311                                 '$dest_url'     => self::getApp()->get_baseurl(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                 Addon::callHooks('login_hook', $o);
338
339                 return $o;
340         }
341 }