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