2 require_once('include/security.php');
3 require_once('include/datetime.php');
5 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
6 if (isset($_COOKIE["Friendica"])) {
7 $data = json_decode($_COOKIE["Friendica"]);
8 if (isset($data->uid)) {
9 $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
10 FROM `user` WHERE `uid` = %d AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
15 if ($data->hash != cookie_hash($r[0])) {
16 logger("Hash for user ".$data->uid." doesn't fit.");
22 new_cookie(604800, $r[0]);
24 // Do the authentification if not done by now
25 if (!isset($_SESSION) OR !isset($_SESSION['authenticated'])) {
26 authenticate_success($r[0]);
28 if (get_config('system','paranoia'))
29 $_SESSION['addr'] = $data->ip;
38 if (isset($_SESSION) && x($_SESSION,'authenticated') && (!x($_POST,'auth-params') || ($_POST['auth-params'] !== 'login'))) {
40 if ((x($_POST,'auth-params') && ($_POST['auth-params'] === 'logout')) || ($a->module === 'logout')) {
42 // process logout request
43 call_hooks("logging_out");
45 info(t('Logged out.').EOL);
49 if (x($_SESSION,'visitor_id') && !x($_SESSION,'uid')) {
50 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
51 intval($_SESSION['visitor_id'])
53 if (dbm::is_result($r)) {
58 if (x($_SESSION,'uid')) {
60 // already logged in user returning
62 $check = get_config('system','paranoia');
63 // extra paranoia - if the IP changed, log them out
64 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
65 logger('Session address changed. Paranoid setting in effect, blocking session. '.
66 $_SESSION['addr'].' != '.$_SERVER['REMOTE_ADDR']);
71 $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
72 FROM `user` WHERE `uid` = %d AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
73 intval($_SESSION['uid'])
76 if (!dbm::is_result($r)) {
81 // Make sure to refresh the last login time for the user if the user
82 // stays logged in for a long time, e.g. with "Remember Me"
83 $login_refresh = false;
84 if (!x($_SESSION['last_login_date'])) {
85 $_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
87 if (strcmp(datetime_convert('UTC','UTC','now - 12 hours'), $_SESSION['last_login_date']) > 0) {
89 $_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
90 $login_refresh = true;
92 authenticate_success($r[0], false, false, $login_refresh);
98 if (x($_POST,'password') && strlen($_POST['password']))
99 $encrypted = hash('whirlpool',trim($_POST['password']));
101 if ((x($_POST,'openid_url')) && strlen($_POST['openid_url']) ||
102 (x($_POST,'username')) && strlen($_POST['username'])) {
104 $noid = get_config('system','no_openid');
106 $openid_url = trim((strlen($_POST['openid_url'])?$_POST['openid_url']:$_POST['username']));
108 // validate_url alters the calling parameter
110 $temp_string = $openid_url;
112 // if it's an email address or doesn't resolve to a URL, fail.
114 if ($noid || strpos($temp_string,'@') || !validate_url($temp_string)) {
116 notice(t('Login failed.').EOL);
121 // Otherwise it's probably an openid.
124 require_once('library/openid.php');
125 $openid = new LightOpenID;
126 $openid->identity = $openid_url;
127 $_SESSION['openid'] = $openid_url;
128 $openid->returnUrl = App::get_baseurl(true).'/openid';
129 goaway($openid->authUrl());
130 } catch (Exception $e) {
131 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());
137 if (x($_POST,'auth-params') && $_POST['auth-params'] === 'login') {
142 'username' => trim($_POST['username']),
143 'password' => trim($_POST['password']),
144 'authenticated' => 0,
145 'user_record' => null
150 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
151 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
152 * and later plugins should not interfere with an earlier one that succeeded.
156 call_hooks('authenticate', $addon_auth);
158 if ($addon_auth['authenticated'] && count($addon_auth['user_record']))
159 $record = $addon_auth['user_record'];
162 // process normal login request
164 $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
165 FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
166 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
167 dbesc(trim($_POST['username'])),
168 dbesc(trim($_POST['username'])),
171 if (dbm::is_result($r))
175 if (!$record || !count($record)) {
176 logger('authenticate: failed login attempt: '.notags(trim($_POST['username'])).' from IP '.$_SERVER['REMOTE_ADDR']);
177 notice(t('Login failed.').EOL);
181 // If the user specified to remember the authentication, then set a cookie
182 // that expires after one week (the default is when the browser is closed).
183 // The cookie will be renewed automatically.
184 // The week ensures that sessions will expire after some inactivity.
185 if ($_POST['remember'])
186 new_cookie(604800, $r[0]);
188 new_cookie(0); // 0 means delete on browser exit
190 // if we haven't failed up this point, log them in.
192 $_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
193 authenticate_success($record, true, true);
198 * @brief Kills the "Friendica" cookie and all session data
200 function nuke_session() {
202 new_cookie(-3600); // make sure cookie is deleted on browser close, as a security measure
208 * @brief Calculate the hash that is needed for the "Friendica" cookie
210 * @param array $user Record from "user" table
212 * @return string Hashed data
214 function cookie_hash($user) {
215 return(hash("sha256", get_config("system", "site_prvkey").
221 * @brief Set the "Friendica" cookie
224 * @param array $user Record from "user" table
226 function new_cookie($time, $user = array()) {
229 $time = $time + time();
232 $value = json_encode(array("uid" => $user["uid"],
233 "hash" => cookie_hash($user),
234 "ip" => $_SERVER['REMOTE_ADDR']));
238 setcookie("Friendica", $value, $time, "/", "",
239 (get_config('system', 'ssl_policy') == SSL_POLICY_FULL), true);