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