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'])
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'])
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;
129 $openid->returnUrl = $a->get_baseurl(true).'/openid';
130 goaway($openid->authUrl());
131 } catch (Exception $e) {
132 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 if (x($_POST,'auth-params') && $_POST['auth-params'] === 'login') {
143 'username' => trim($_POST['username']),
144 'password' => trim($_POST['password']),
145 'authenticated' => 0,
146 'user_record' => null
151 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
152 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
153 * and later plugins should not interfere with an earlier one that succeeded.
157 call_hooks('authenticate', $addon_auth);
159 if ($addon_auth['authenticated'] && count($addon_auth['user_record']))
160 $record = $addon_auth['user_record'];
163 // process normal login request
165 $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
166 FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
167 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
168 dbesc(trim($_POST['username'])),
169 dbesc(trim($_POST['username'])),
176 if (!$record || !count($record)) {
177 logger('authenticate: failed login attempt: '.notags(trim($_POST['username'])).' from IP '.$_SERVER['REMOTE_ADDR']);
178 notice(t('Login failed.').EOL);
182 // If the user specified to remember the authentication, then set a cookie
183 // that expires after one week (the default is when the browser is closed).
184 // The cookie will be renewed automatically.
185 // The week ensures that sessions will expire after some inactivity.
186 if ($_POST['remember'])
187 new_cookie(604800, $r[0]);
189 new_cookie(0); // 0 means delete on browser exit
191 // if we haven't failed up this point, log them in.
193 $_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
194 authenticate_success($record, true, true);
199 * @brief Kills the "Friendica" cookie and all session data
201 function nuke_session() {
203 new_cookie(-3600); // make sure cookie is deleted on browser close, as a security measure
209 * @brief Calculate the hash that is needed for the "Friendica" cookie
211 * @param array $user Record from "user" table
213 * @return string Hashed data
215 function cookie_hash($user) {
216 return(hash("sha256", get_config("system", "site_prvkey").
222 * @brief Set the "Friendica" cookie
225 * @param array $user Record from "user" table
227 function new_cookie($time, $user = array()) {
230 $time = $time + time();
233 $value = json_encode(array("uid" => $user["uid"],
234 "hash" => cookie_hash($user),
235 "ip" => $_SERVER['REMOTE_ADDR']));
239 setcookie("Friendica", $value, $time, "/", "",
240 (get_config('system', 'ssl_policy') == SSL_POLICY_FULL), true);