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