]> git.mxchange.org Git - friendica.git/blob - src/Module/Login.php
Rename DBM method calls to DBA method calls
[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 mrpetovan@gmail.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                         notice($e->getMessage() . EOL);
144                         goaway(self::getApp()->get_baseurl() . '/login');
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::is_result($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                                 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
215                                         intval($_SESSION['visitor_id'])
216                                 );
217                                 if (DBA::is_result($r)) {
218                                         self::getApp()->contact = $r[0];
219                                 }
220                         }
221
222                         if (x($_SESSION, 'uid')) {
223                                 // already logged in user returning
224                                 $check = Config::get('system', 'paranoia');
225                                 // extra paranoia - if the IP changed, log them out
226                                 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
227                                         logger('Session address changed. Paranoid setting in effect, blocking session. ' .
228                                                 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
229                                         nuke_session();
230                                         goaway(self::getApp()->get_baseurl());
231                                 }
232
233                                 $user = DBA::selectFirst('user', [],
234                                         [
235                                                 'uid'             => $_SESSION['uid'],
236                                                 'blocked'         => false,
237                                                 'account_expired' => false,
238                                                 'account_removed' => false,
239                                                 'verified'        => true,
240                                         ]
241                                 );
242                                 if (!DBA::is_result($user)) {
243                                         nuke_session();
244                                         goaway(self::getApp()->get_baseurl());
245                                 }
246
247                                 // Make sure to refresh the last login time for the user if the user
248                                 // stays logged in for a long time, e.g. with "Remember Me"
249                                 $login_refresh = false;
250                                 if (empty($_SESSION['last_login_date'])) {
251                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
252                                 }
253                                 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
254                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
255                                         $login_refresh = true;
256                                 }
257                                 authenticate_success($user, false, false, $login_refresh);
258                         }
259                 }
260         }
261
262         /**
263          * @brief Wrapper for adding a login box.
264          *
265          * @param string $return_url The url relative to the base the user should be sent
266          *                                                       back to after login completes
267          * @param bool $register If $register == true provide a registration link.
268          *                                               This will most always depend on the value of config.register_policy.
269          * @param array $hiddens  optional
270          *
271          * @return string Returns the complete html for inserting into the page
272          *
273          * @hooks 'login_hook' string $o
274          */
275         public static function form($return_url = null, $register = false, $hiddens = [])
276         {
277                 $a = self::getApp();
278                 $o = '';
279                 $reg = false;
280                 if ($register) {
281                         $reg = [
282                                 'title' => L10n::t('Create a New Account'),
283                                 'desc' => L10n::t('Register')
284                         ];
285                 }
286
287                 $noid = Config::get('system', 'no_openid');
288
289                 if (is_null($return_url)) {
290                         $return_url = $a->query_string;
291                 }
292
293                 if (local_user()) {
294                         $tpl = get_markup_template('logout.tpl');
295                 } else {
296                         $a->page['htmlhead'] .= replace_macros(
297                                 get_markup_template('login_head.tpl'),
298                                 [
299                                         '$baseurl' => $a->get_baseurl(true)
300                                 ]
301                         );
302
303                         $tpl = get_markup_template('login.tpl');
304                         $_SESSION['return_url'] = $return_url;
305                 }
306
307                 $o .= replace_macros(
308                         $tpl,
309                         [
310                                 '$dest_url'     => self::getApp()->get_baseurl(true) . '/login',
311                                 '$logout'       => L10n::t('Logout'),
312                                 '$login'        => L10n::t('Login'),
313
314                                 '$lname'        => ['username', L10n::t('Nickname or Email: ') , '', ''],
315                                 '$lpassword'    => ['password', L10n::t('Password: '), '', ''],
316                                 '$lremember'    => ['remember', L10n::t('Remember me'), 0,  ''],
317
318                                 '$openid'       => !$noid,
319                                 '$lopenid'      => ['openid_url', L10n::t('Or login using OpenID: '),'',''],
320
321                                 '$hiddens'      => $hiddens,
322
323                                 '$register'     => $reg,
324
325                                 '$lostpass'     => L10n::t('Forgot your password?'),
326                                 '$lostlink'     => L10n::t('Password Reset'),
327
328                                 '$tostitle'     => L10n::t('Website Terms of Service'),
329                                 '$toslink'      => L10n::t('terms of service'),
330
331                                 '$privacytitle' => L10n::t('Website Privacy Policy'),
332                                 '$privacylink'  => L10n::t('privacy policy'),
333                         ]
334                 );
335
336                 Addon::callHooks('login_hook', $o);
337
338                 return $o;
339         }
340 }