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