]> git.mxchange.org Git - friendica.git/blob - src/Module/Login.php
Merge pull request #5967 from annando/ap-nick
[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\Database\DBA;
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/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()->getBaseURL());
43                 }
44
45                 return self::form($_SESSION['return_url'], intval(Config::get('config', 'register_policy')) !== REGISTER_CLOSED);
46         }
47
48         public static function post()
49         {
50                 $return_url = $_SESSION['return_url'];
51                 session_unset();
52                 $_SESSION['return_url'] = $return_url;
53                 
54                 // OpenId Login
55                 if (
56                         empty($_POST['password'])
57                         && (
58                                 !empty($_POST['openid_url'])
59                                 || !empty($_POST['username'])
60                         )
61                 ) {
62                         $openid_url = trim(defaults($_POST, 'openid_url', $_POST['username']));
63
64                         self::openIdAuthentication($openid_url, !empty($_POST['remember']));
65                 }
66
67                 if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') {
68                         self::passwordAuthentication(
69                                 trim($_POST['username']),
70                                 trim($_POST['password']),
71                                 !empty($_POST['remember'])
72                         );
73                 }
74         }
75
76         /**
77          * Attempts to authenticate using OpenId
78          *
79          * @param string $openid_url OpenID URL string
80          * @param bool   $remember   Whether to set the session remember flag
81          */
82         private static function openIdAuthentication($openid_url, $remember)
83         {
84                 $noid = Config::get('system', 'no_openid');
85
86                 // if it's an email address or doesn't resolve to a URL, fail.
87                 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
88                         notice(L10n::t('Login failed.') . EOL);
89                         goaway(self::getApp()->getBaseURL());
90                         // NOTREACHED
91                 }
92
93                 // Otherwise it's probably an openid.
94                 try {
95                         $a = get_app();
96                         $openid = new LightOpenID($a->getHostName());
97                         $openid->identity = $openid_url;
98                         $_SESSION['openid'] = $openid_url;
99                         $_SESSION['remember'] = $remember;
100                         $openid->returnUrl = self::getApp()->getBaseURL(true) . '/openid';
101                         goaway($openid->authUrl());
102                 } catch (Exception $e) {
103                         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());
104                 }
105         }
106
107         /**
108          * Attempts to authenticate using login/password
109          *
110          * @param string $username User name
111          * @param string $password Clear password
112          * @param bool   $remember Whether to set the session remember flag
113          */
114         private static function passwordAuthentication($username, $password, $remember)
115         {
116                 $record = null;
117
118                 $addon_auth = [
119                         'username' => $username,
120                         'password' => $password,
121                         'authenticated' => 0,
122                         'user_record' => null
123                 ];
124
125                 /*
126                  * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
127                  * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
128                  * and later addons should not interfere with an earlier one that succeeded.
129                  */
130                 Addon::callHooks('authenticate', $addon_auth);
131
132                 try {
133                         if ($addon_auth['authenticated']) {
134                                 $record = $addon_auth['user_record'];
135
136                                 if (empty($record)) {
137                                         throw new Exception(L10n::t('Login failed.'));
138                                 }
139                         } else {
140                                 $record = DBA::selectFirst('user', [],
141                                         ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
142                                 );
143                         }
144                 } catch (Exception $e) {
145                         logger('authenticate: failed login attempt: ' . notags($username) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
146                         info('Login failed. Please check your credentials.' . EOL);
147                         goaway('/');
148                 }
149
150                 if (!$remember) {
151                         Authentication::setCookie(0); // 0 means delete on browser exit
152                 }
153
154                 // if we haven't failed up this point, log them in.
155                 $_SESSION['remember'] = $remember;
156                 $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
157                 Authentication::setAuthenticatedSessionForUser($record, true, true);
158
159                 if (x($_SESSION, 'return_url')) {
160                         $return_url = $_SESSION['return_url'];
161                         unset($_SESSION['return_url']);
162                 } else {
163                         $return_url = '';
164                 }
165
166                 goaway($return_url);
167         }
168
169         /**
170          * @brief Tries to auth the user from the cookie or session
171          *
172          * @todo Should be moved to Friendica\Core\Session when it's created
173          */
174         public static function sessionAuth()
175         {
176                 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
177                 if (isset($_COOKIE["Friendica"])) {
178                         $data = json_decode($_COOKIE["Friendica"]);
179                         if (isset($data->uid)) {
180
181                                 $user = DBA::selectFirst('user', [],
182                                         [
183                                                 'uid'             => $data->uid,
184                                                 'blocked'         => false,
185                                                 'account_expired' => false,
186                                                 'account_removed' => false,
187                                                 'verified'        => true,
188                                         ]
189                                 );
190                                 if (DBA::isResult($user)) {
191                                         if ($data->hash != Authentication::getCookieHashForUser($user)) {
192                                                 logger("Hash for user " . $data->uid . " doesn't fit.");
193                                                 Authentication::deleteSession();
194                                                 goaway(self::getApp()->getBaseURL());
195                                         }
196
197                                         // Renew the cookie
198                                         // Expires after 7 days by default,
199                                         // can be set via system.auth_cookie_lifetime
200                                         $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
201                                         Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
202
203                                         // Do the authentification if not done by now
204                                         if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
205                                                 Authentication::setAuthenticatedSessionForUser($user);
206
207                                                 if (Config::get('system', 'paranoia')) {
208                                                         $_SESSION['addr'] = $data->ip;
209                                                 }
210                                         }
211                                 }
212                         }
213                 }
214
215                 if (isset($_SESSION) && x($_SESSION, 'authenticated')) {
216                         if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
217                                 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
218                                 if (DBA::isResult($contact)) {
219                                         self::getApp()->contact = $contact;
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                                         Authentication::deleteSession();
231                                         goaway(self::getApp()->getBaseURL());
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 (!DBA::isResult($user)) {
244                                         Authentication::deleteSession();
245                                         goaway(self::getApp()->getBaseURL());
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                                 Authentication::setAuthenticatedSessionForUser($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->getBaseURL(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()->getBaseURL(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 }