]> git.mxchange.org Git - friendica.git/blob - include/auth.php
181ba71a629699fad700c417b9a6a2de74f1cbb5
[friendica.git] / include / auth.php
1 <?php
2
3 use Friendica\App;
4 use Friendica\Core\System;
5 use Friendica\Core\Config;
6 use Friendica\Database\DBM;
7 use Friendica\Model\User;
8
9 require_once 'include/security.php';
10 require_once 'include/datetime.php';
11
12 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
13 if (isset($_COOKIE["Friendica"])) {
14         $data = json_decode($_COOKIE["Friendica"]);
15         if (isset($data->uid)) {
16                 $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
17                 FROM `user` WHERE `uid` = %d AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
18                         intval($data->uid)
19                 );
20
21                 if ($r) {
22                         if ($data->hash != cookie_hash($r[0])) {
23                                 logger("Hash for user " . $data->uid . " doesn't fit.");
24                                 nuke_session();
25                                 goaway(System::baseUrl());
26                         }
27
28                         // Renew the cookie
29                         // Expires after 7 days by default,
30                         // can be set via system.auth_cookie_lifetime
31                         $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
32                         new_cookie($authcookiedays * 24 * 60 * 60, $r[0]);
33
34                         // Do the authentification if not done by now
35                         if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
36                                 authenticate_success($r[0]);
37
38                                 if (Config::get('system', 'paranoia')) {
39                                         $_SESSION['addr'] = $data->ip;
40                                 }
41                         }
42                 }
43         }
44 }
45
46
47 // login/logout
48
49 if (isset($_SESSION) && x($_SESSION, 'authenticated') && (!x($_POST, 'auth-params') || ($_POST['auth-params'] !== 'login'))) {
50         if ((x($_POST, 'auth-params') && ($_POST['auth-params'] === 'logout')) || ($a->module === 'logout')) {
51                 // process logout request
52                 call_hooks("logging_out");
53                 nuke_session();
54                 info(t('Logged out.') . EOL);
55                 goaway(System::baseUrl());
56         }
57
58         if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
59                 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
60                         intval($_SESSION['visitor_id'])
61                 );
62                 if (DBM::is_result($r)) {
63                         $a->contact = $r[0];
64                 }
65         }
66
67         if (x($_SESSION, 'uid')) {
68                 // already logged in user returning
69                 $check = Config::get('system', 'paranoia');
70                 // extra paranoia - if the IP changed, log them out
71                 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
72                         logger('Session address changed. Paranoid setting in effect, blocking session. ' .
73                                 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
74                         nuke_session();
75                         goaway(System::baseUrl());
76                 }
77
78                 $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
79                 FROM `user` WHERE `uid` = %d AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
80                         intval($_SESSION['uid'])
81                 );
82
83                 if (!DBM::is_result($r)) {
84                         nuke_session();
85                         goaway(System::baseUrl());
86                 }
87
88                 // Make sure to refresh the last login time for the user if the user
89                 // stays logged in for a long time, e.g. with "Remember Me"
90                 $login_refresh = false;
91                 if (!x($_SESSION['last_login_date'])) {
92                         $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
93                 }
94                 if (strcmp(datetime_convert('UTC', 'UTC', 'now - 12 hours'), $_SESSION['last_login_date']) > 0) {
95                         $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
96                         $login_refresh = true;
97                 }
98                 authenticate_success($r[0], false, false, $login_refresh);
99         }
100 } else {
101         session_unset();
102         if (
103                 !(x($_POST, 'password') && strlen($_POST['password']))
104                 && (
105                         x($_POST, 'openid_url') && strlen($_POST['openid_url'])
106                         || x($_POST, 'username') && strlen($_POST['username'])
107                 )
108         ) {
109                 $noid = Config::get('system', 'no_openid');
110
111                 $openid_url = trim(strlen($_POST['openid_url']) ? $_POST['openid_url'] : $_POST['username']);
112
113                 // validate_url alters the calling parameter
114
115                 $temp_string = $openid_url;
116
117                 // if it's an email address or doesn't resolve to a URL, fail.
118
119                 if ($noid || strpos($temp_string, '@') || !validate_url($temp_string)) {
120                         $a = get_app();
121                         notice(t('Login failed.') . EOL);
122                         goaway(System::baseUrl());
123                         // NOTREACHED
124                 }
125
126                 // Otherwise it's probably an openid.
127
128                 try {
129                         require_once('library/openid.php');
130                         $openid = new LightOpenID;
131                         $openid->identity = $openid_url;
132                         $_SESSION['openid'] = $openid_url;
133                         $_SESSION['remember'] = $_POST['remember'];
134                         $openid->returnUrl = System::baseUrl(true) . '/openid';
135                         goaway($openid->authUrl());
136                 } catch (Exception $e) {
137                         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());
138                 }
139                 // NOTREACHED
140         }
141
142         if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') {
143                 $record = null;
144
145                 $addon_auth = array(
146                         'username' => trim($_POST['username']),
147                         'password' => trim($_POST['password']),
148                         'authenticated' => 0,
149                         'user_record' => null
150                 );
151
152                 /**
153                  *
154                  * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
155                  * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
156                  * and later plugins should not interfere with an earlier one that succeeded.
157                  *
158                  */
159                 call_hooks('authenticate', $addon_auth);
160
161                 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
162                         $record = $addon_auth['user_record'];
163                 } else {
164                         $user_id = User::authenticate(trim($_POST['username']), trim($_POST['password']));
165                         if ($user_id) {
166                                 $record = dba::select('user', [], ['uid' => $user_id], ['limit' => 1]);
167                         }
168                 }
169
170                 if (!$record || !count($record)) {
171                         logger('authenticate: failed login attempt: ' . notags(trim($_POST['username'])) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
172                         notice(t('Login failed.') . EOL);
173                         goaway(System::baseUrl());
174                 }
175
176                 if (!$_POST['remember']) {
177                         new_cookie(0); // 0 means delete on browser exit
178                 }
179
180                 // if we haven't failed up this point, log them in.
181                 $_SESSION['remember'] = $_POST['remember'];
182                 $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
183                 authenticate_success($record, true, true);
184         }
185 }
186
187 /**
188  * @brief Kills the "Friendica" cookie and all session data
189  */
190 function nuke_session()
191 {
192         new_cookie(-3600); // make sure cookie is deleted on browser close, as a security measure
193         session_unset();
194         session_destroy();
195 }