Merge pull request #3970 from MrPetovan/task/3942-add-user-authenticate

Migrate password hashing Part 1: Add User::authenticate
This commit is contained in:
Michael Vogel 2017-11-27 15:14:36 +01:00 committed by GitHub
commit 3f448d9a42
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 205 additions and 268 deletions

View File

@ -12,6 +12,7 @@ use Friendica\Core\Config;
use Friendica\Core\NotificationsManager; use Friendica\Core\NotificationsManager;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBM; use Friendica\Database\DBM;
use Friendica\Model\User;
use Friendica\Network\HTTPException; use Friendica\Network\HTTPException;
use Friendica\Network\HTTPException\BadRequestException; use Friendica\Network\HTTPException\BadRequestException;
use Friendica\Network\HTTPException\ForbiddenException; use Friendica\Network\HTTPException\ForbiddenException;
@ -190,7 +191,6 @@ function api_login(App $a)
$user = $_SERVER['PHP_AUTH_USER']; $user = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW']; $password = $_SERVER['PHP_AUTH_PW'];
$encrypted = hash('whirlpool', trim($password));
// allow "user@server" login (but ignore 'server' part) // allow "user@server" login (but ignore 'server' part)
$at = strstr($user, "@", true); $at = strstr($user, "@", true);
@ -218,16 +218,9 @@ function api_login(App $a)
if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) { if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
$record = $addon_auth['user_record']; $record = $addon_auth['user_record'];
} else { } else {
// process normal login request $user_id = User::authenticate(trim($user), trim($password));
$r = q( if ($user_id) {
"SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s') $record = dba::select('user', [], ['uid' => $user_id], ['limit' => 1]);
AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
dbesc(trim($user)),
dbesc(trim($user)),
dbesc($encrypted)
);
if (DBM::is_result($r)) {
$record = $r[0];
} }
} }

View File

@ -4,22 +4,31 @@ use Friendica\App;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Database\DBM; use Friendica\Database\DBM;
use Friendica\Model\User;
require_once('include/security.php'); require_once 'include/security.php';
require_once('include/datetime.php'); require_once 'include/datetime.php';
// When the "Friendica" cookie is set, take the value to authenticate and renew the cookie. // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
if (isset($_COOKIE["Friendica"])) { if (isset($_COOKIE["Friendica"])) {
$data = json_decode($_COOKIE["Friendica"]); $data = json_decode($_COOKIE["Friendica"]);
if (isset($data->uid)) { if (isset($data->uid)) {
$r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
FROM `user` WHERE `uid` = %d AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1", $user = dba::select('user',
intval($data->uid) [],
[
'uid' => $data->uid,
'blocked' => false,
'account_expired' => false,
'account_removed' => false,
'verified' => true,
],
['limit' => 1]
); );
if ($r) { if (DBM::is_result($user)) {
if ($data->hash != cookie_hash($r[0])) { if ($data->hash != cookie_hash($user)) {
logger("Hash for user ".$data->uid." doesn't fit."); logger("Hash for user " . $data->uid . " doesn't fit.");
nuke_session(); nuke_session();
goaway(System::baseUrl()); goaway(System::baseUrl());
} }
@ -28,14 +37,15 @@ if (isset($_COOKIE["Friendica"])) {
// Expires after 7 days by default, // Expires after 7 days by default,
// can be set via system.auth_cookie_lifetime // can be set via system.auth_cookie_lifetime
$authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7); $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
new_cookie($authcookiedays*24*60*60, $r[0]); new_cookie($authcookiedays * 24 * 60 * 60, $user);
// Do the authentification if not done by now // Do the authentification if not done by now
if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) { if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
authenticate_success($r[0]); authenticate_success($user);
if (Config::get('system','paranoia')) if (Config::get('system', 'paranoia')) {
$_SESSION['addr'] = $data->ip; $_SESSION['addr'] = $data->ip;
}
} }
} }
} }
@ -44,18 +54,16 @@ if (isset($_COOKIE["Friendica"])) {
// login/logout // login/logout
if (isset($_SESSION) && x($_SESSION,'authenticated') && (!x($_POST,'auth-params') || ($_POST['auth-params'] !== 'login'))) { if (isset($_SESSION) && x($_SESSION, 'authenticated') && (!x($_POST, 'auth-params') || ($_POST['auth-params'] !== 'login'))) {
if ((x($_POST, 'auth-params') && ($_POST['auth-params'] === 'logout')) || ($a->module === 'logout')) {
if ((x($_POST,'auth-params') && ($_POST['auth-params'] === 'logout')) || ($a->module === 'logout')) {
// process logout request // process logout request
call_hooks("logging_out"); call_hooks("logging_out");
nuke_session(); nuke_session();
info(t('Logged out.').EOL); info(t('Logged out.') . EOL);
goaway(System::baseUrl()); goaway(System::baseUrl());
} }
if (x($_SESSION,'visitor_id') && !x($_SESSION,'uid')) { if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
$r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
intval($_SESSION['visitor_id']) intval($_SESSION['visitor_id'])
); );
@ -64,25 +72,29 @@ if (isset($_SESSION) && x($_SESSION,'authenticated') && (!x($_POST,'auth-params'
} }
} }
if (x($_SESSION,'uid')) { if (x($_SESSION, 'uid')) {
// already logged in user returning // already logged in user returning
$check = Config::get('system', 'paranoia');
$check = Config::get('system','paranoia');
// extra paranoia - if the IP changed, log them out // extra paranoia - if the IP changed, log them out
if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) { if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
logger('Session address changed. Paranoid setting in effect, blocking session. '. logger('Session address changed. Paranoid setting in effect, blocking session. ' .
$_SESSION['addr'].' != '.$_SERVER['REMOTE_ADDR']); $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
nuke_session(); nuke_session();
goaway(System::baseUrl()); goaway(System::baseUrl());
} }
$r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey` $user = dba::select('user',
FROM `user` WHERE `uid` = %d AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1", [],
intval($_SESSION['uid']) [
'uid' => $_SESSION['uid'],
'blocked' => false,
'account_expired' => false,
'account_removed' => false,
'verified' => true,
],
['limit' => 1]
); );
if (!DBM::is_result($user)) {
if (!DBM::is_result($r)) {
nuke_session(); nuke_session();
goaway(System::baseUrl()); goaway(System::baseUrl());
} }
@ -91,61 +103,57 @@ if (isset($_SESSION) && x($_SESSION,'authenticated') && (!x($_POST,'auth-params'
// stays logged in for a long time, e.g. with "Remember Me" // stays logged in for a long time, e.g. with "Remember Me"
$login_refresh = false; $login_refresh = false;
if (!x($_SESSION['last_login_date'])) { if (!x($_SESSION['last_login_date'])) {
$_SESSION['last_login_date'] = datetime_convert('UTC','UTC'); $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
} }
if (strcmp(datetime_convert('UTC','UTC','now - 12 hours'), $_SESSION['last_login_date']) > 0) { if (strcmp(datetime_convert('UTC', 'UTC', 'now - 12 hours'), $_SESSION['last_login_date']) > 0) {
$_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
$_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
$login_refresh = true; $login_refresh = true;
} }
authenticate_success($r[0], false, false, $login_refresh); authenticate_success($user, false, false, $login_refresh);
} }
} else { } else {
session_unset(); session_unset();
if (
!(x($_POST, 'password') && strlen($_POST['password']))
&& (
x($_POST, 'openid_url') && strlen($_POST['openid_url'])
|| x($_POST, 'username') && strlen($_POST['username'])
)
) {
$noid = Config::get('system', 'no_openid');
if (x($_POST,'password') && strlen($_POST['password'])) $openid_url = trim(strlen($_POST['openid_url']) ? $_POST['openid_url'] : $_POST['username']);
$encrypted = hash('whirlpool',trim($_POST['password']));
else {
if ((x($_POST,'openid_url')) && strlen($_POST['openid_url']) ||
(x($_POST,'username')) && strlen($_POST['username'])) {
$noid = Config::get('system','no_openid'); // validate_url alters the calling parameter
$openid_url = trim((strlen($_POST['openid_url'])?$_POST['openid_url']:$_POST['username'])); $temp_string = $openid_url;
// validate_url alters the calling parameter // if it's an email address or doesn't resolve to a URL, fail.
$temp_string = $openid_url; if ($noid || strpos($temp_string, '@') || !validate_url($temp_string)) {
$a = get_app();
// if it's an email address or doesn't resolve to a URL, fail. notice(t('Login failed.') . EOL);
goaway(System::baseUrl());
if ($noid || strpos($temp_string,'@') || !validate_url($temp_string)) {
$a = get_app();
notice(t('Login failed.').EOL);
goaway(System::baseUrl());
// NOTREACHED
}
// Otherwise it's probably an openid.
try {
require_once('library/openid.php');
$openid = new LightOpenID;
$openid->identity = $openid_url;
$_SESSION['openid'] = $openid_url;
$_SESSION['remember'] = $_POST['remember'];
$openid->returnUrl = System::baseUrl(true).'/openid';
goaway($openid->authUrl());
} catch (Exception $e) {
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());
}
// NOTREACHED // NOTREACHED
} }
// Otherwise it's probably an openid.
try {
require_once('library/openid.php');
$openid = new LightOpenID;
$openid->identity = $openid_url;
$_SESSION['openid'] = $openid_url;
$_SESSION['remember'] = $_POST['remember'];
$openid->returnUrl = System::baseUrl(true) . '/openid';
goaway($openid->authUrl());
} catch (Exception $e) {
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());
}
// NOTREACHED
} }
if (x($_POST,'auth-params') && $_POST['auth-params'] === 'login') { if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') {
$record = null; $record = null;
$addon_auth = array( $addon_auth = array(
@ -162,39 +170,30 @@ if (isset($_SESSION) && x($_SESSION,'authenticated') && (!x($_POST,'auth-params'
* and later plugins should not interfere with an earlier one that succeeded. * and later plugins should not interfere with an earlier one that succeeded.
* *
*/ */
call_hooks('authenticate', $addon_auth); call_hooks('authenticate', $addon_auth);
if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
$record = $addon_auth['user_record']; $record = $addon_auth['user_record'];
else { } else {
$user_id = User::authenticate(trim($_POST['username']), trim($_POST['password']));
// process normal login request if ($user_id) {
$record = dba::select('user', [], ['uid' => $user_id], ['limit' => 1]);
$r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey` }
FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
dbesc(trim($_POST['username'])),
dbesc(trim($_POST['username'])),
dbesc($encrypted)
);
if (DBM::is_result($r))
$record = $r[0];
} }
if (!$record || !count($record)) { if (!$record || !count($record)) {
logger('authenticate: failed login attempt: '.notags(trim($_POST['username'])).' from IP '.$_SERVER['REMOTE_ADDR']); logger('authenticate: failed login attempt: ' . notags(trim($_POST['username'])) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
notice(t('Login failed.').EOL); notice(t('Login failed.') . EOL);
goaway(System::baseUrl()); goaway(System::baseUrl());
} }
if (! $_POST['remember']) { if (!$_POST['remember']) {
new_cookie(0); // 0 means delete on browser exit new_cookie(0); // 0 means delete on browser exit
} }
// if we haven't failed up this point, log them in. // if we haven't failed up this point, log them in.
$_SESSION['remember'] = $_POST['remember']; $_SESSION['remember'] = $_POST['remember'];
$_SESSION['last_login_date'] = datetime_convert('UTC','UTC'); $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC');
authenticate_success($record, true, true); authenticate_success($record, true, true);
} }
} }
@ -202,8 +201,8 @@ if (isset($_SESSION) && x($_SESSION,'authenticated') && (!x($_POST,'auth-params'
/** /**
* @brief Kills the "Friendica" cookie and all session data * @brief Kills the "Friendica" cookie and all session data
*/ */
function nuke_session() { function nuke_session()
{
new_cookie(-3600); // make sure cookie is deleted on browser close, as a security measure new_cookie(-3600); // make sure cookie is deleted on browser close, as a security measure
session_unset(); session_unset();
session_destroy(); session_destroy();

View File

@ -182,93 +182,3 @@ class FKOAuth1 extends OAuthServer {
} }
} }
/*
class FKOAuth2 extends OAuth2 {
private function db_secret($client_secret){
return hash('whirlpool',$client_secret);
}
public function addClient($client_id, $client_secret, $redirect_uri) {
$client_secret = $this->db_secret($client_secret);
$r = q("INSERT INTO clients (client_id, pw, redirect_uri) VALUES ('%s', '%s', '%s')",
dbesc($client_id),
dbesc($client_secret),
dbesc($redirect_uri)
);
return $r;
}
protected function checkClientCredentials($client_id, $client_secret = NULL) {
$client_secret = $this->db_secret($client_secret);
$r = q("SELECT pw FROM clients WHERE client_id = '%s'",
dbesc($client_id));
if ($client_secret === NULL)
return $result !== FALSE;
return $result["client_secret"] == $client_secret;
}
protected function getRedirectUri($client_id) {
$r = q("SELECT redirect_uri FROM clients WHERE client_id = '%s'",
dbesc($client_id));
if ($r === FALSE)
return FALSE;
return isset($r[0]["redirect_uri"]) && $r[0]["redirect_uri"] ? $r[0]["redirect_uri"] : NULL;
}
protected function getAccessToken($oauth_token) {
$r = q("SELECT client_id, expires, scope FROM tokens WHERE id = '%s'",
dbesc($oauth_token));
if (DBM::is_result($r))
return $r[0];
return null;
}
protected function setAccessToken($oauth_token, $client_id, $expires, $scope = NULL) {
$r = q("INSERT INTO tokens (id, client_id, expires, scope) VALUES ('%s', '%s', %d, '%s')",
dbesc($oauth_token),
dbesc($client_id),
intval($expires),
dbesc($scope));
return $r;
}
protected function getSupportedGrantTypes() {
return array(
OAUTH2_GRANT_TYPE_AUTH_CODE,
);
}
protected function getAuthCode($code) {
$r = q("SELECT id, client_id, redirect_uri, expires, scope FROM auth_codes WHERE id = '%s'",
dbesc($code));
if (DBM::is_result($r))
return $r[0];
return null;
}
protected function setAuthCode($code, $client_id, $redirect_uri, $expires, $scope = NULL) {
$r = q("INSERT INTO auth_codes
(id, client_id, redirect_uri, expires, scope) VALUES
('%s', '%s', '%s', %d, '%s')",
dbesc($code),
dbesc($client_id),
dbesc($redirect_uri),
intval($expires),
dbesc($scope));
return $r;
}
}
*/

View File

@ -15,7 +15,7 @@ use Friendica\Database\DBM;
*/ */
function cookie_hash($user) { function cookie_hash($user) {
return(hash("sha256", Config::get("system", "site_prvkey"). return(hash("sha256", Config::get("system", "site_prvkey").
$user["uprvkey"]. $user["prvkey"].
$user["password"])); $user["password"]));
} }

View File

@ -4,13 +4,12 @@ use Friendica\Core\Config;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBM; use Friendica\Database\DBM;
require_once('include/network.php'); require_once 'include/network.php';
require_once('include/plugin.php'); require_once 'include/plugin.php';
require_once('include/text.php'); require_once 'include/text.php';
require_once('include/pgettext.php'); require_once 'include/pgettext.php';
require_once('include/datetime.php'); require_once 'include/datetime.php';
require_once('include/enotify.php'); require_once 'include/enotify.php';
function create_user($arr) { function create_user($arr) {
@ -388,7 +387,7 @@ function user_create_self_contact($uid) {
* @param string $email * @param string $email
* @param string $sitename * @param string $sitename
* @param string $username * @param string $username
* @return NULL|boolean from notification() and email() inherited * @return NULL|boolean from notification() and email() inherited
*/ */
function send_register_pending_eml($email, $sitename, $username) { function send_register_pending_eml($email, $sitename, $username) {
$body = deindent(t(' $body = deindent(t('

View File

@ -33,7 +33,8 @@ function openid_content(App $a) {
// mod/settings.php in 8367cad so it might have left mixed // mod/settings.php in 8367cad so it might have left mixed
// records in the user table // records in the user table
// //
$r = q("SELECT *, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey` FROM `user` $r = q("SELECT *
FROM `user`
WHERE ( `openid` = '%s' OR `openid` = '%s' ) WHERE ( `openid` = '%s' OR `openid` = '%s' )
AND `blocked` = 0 AND `account_expired` = 0 AND `blocked` = 0 AND `account_expired` = 0
AND `account_removed` = 0 AND `verified` = 1 AND `account_removed` = 0 AND `verified` = 1

View File

@ -4,21 +4,21 @@ use Friendica\App;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Model\User; use Friendica\Model\User;
function removeme_post(App $a) { function removeme_post(App $a)
{
if (! local_user()) { if (!local_user()) {
return; return;
} }
if (x($_SESSION,'submanage') && intval($_SESSION['submanage'])) { if (x($_SESSION, 'submanage') && intval($_SESSION['submanage'])) {
return; return;
} }
if ((! x($_POST,'qxz_password')) || (! strlen(trim($_POST['qxz_password'])))) { if ((!x($_POST, 'qxz_password')) || (!strlen(trim($_POST['qxz_password'])))) {
return; return;
} }
if ((! x($_POST,'verify')) || (! strlen(trim($_POST['verify'])))) { if ((!x($_POST, 'verify')) || (!strlen(trim($_POST['verify'])))) {
return; return;
} }
@ -26,18 +26,15 @@ function removeme_post(App $a) {
return; return;
} }
$encrypted = hash('whirlpool',trim($_POST['qxz_password'])); if (User::authenticate($a->user['uid'], trim($_POST['qxz_password']))) {
if ((strlen($a->user['password'])) && ($encrypted === $a->user['password'])) {
User::remove($a->user['uid']); User::remove($a->user['uid']);
// NOTREACHED // NOTREACHED
} }
} }
function removeme_content(App $a) { function removeme_content(App $a)
{
if (! local_user()) { if (!local_user()) {
goaway(System::baseUrl()); goaway(System::baseUrl());
} }
@ -59,5 +56,4 @@ function removeme_content(App $a) {
)); ));
return $o; return $o;
} }

View File

@ -9,6 +9,7 @@ use Friendica\Core\Config;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Database\DBM; use Friendica\Database\DBM;
use Friendica\Model\GlobalContact; use Friendica\Model\GlobalContact;
use Friendica\Model\User;
require_once 'include/group.php'; require_once 'include/group.php';
@ -371,7 +372,6 @@ function settings_post(App $a) {
$newpass = $_POST['password']; $newpass = $_POST['password'];
$confirm = $_POST['confirm']; $confirm = $_POST['confirm'];
$oldpass = hash('whirlpool', $_POST['opassword']);
$err = false; $err = false;
if ($newpass != $confirm) { if ($newpass != $confirm) {
@ -386,8 +386,7 @@ function settings_post(App $a) {
// check if the old password was supplied correctly before // check if the old password was supplied correctly before
// changing it to the new value // changing it to the new value
$r = q("SELECT `password` FROM `user`WHERE `uid` = %d LIMIT 1", intval(local_user())); if (User::authenticate(intval(local_user()), $_POST['opassword'])) {
if ($oldpass != $r[0]['password']) {
notice(t('Wrong password.') . EOL); notice(t('Wrong password.') . EOL);
$err = true; $err = true;
} }
@ -501,22 +500,20 @@ function settings_post(App $a) {
if ($email != $a->user['email']) { if ($email != $a->user['email']) {
$email_changed = true; $email_changed = true;
// check for the correct password // check for the correct password
$r = q("SELECT `password` FROM `user`WHERE `uid` = %d LIMIT 1", intval(local_user())); if (!User::authenticate(intval(local_user()), $_POST['mpassword'])) {
$password = hash('whirlpool', $_POST['mpassword']);
if ($password != $r[0]['password']) {
$err .= t('Wrong Password') . EOL; $err .= t('Wrong Password') . EOL;
$email = $a->user['email']; $email = $a->user['email'];
} }
// check the email is valid // check the email is valid
if (!valid_email($email)) { if (!valid_email($email)) {
$err .= t(' Not valid email.'); $err .= t('Invalid email.');
} }
// ensure new email is not the admin mail // ensure new email is not the admin mail
//if ((x($a->config, 'admin_email')) && (strcasecmp($email, $a->config['admin_email']) == 0)) { //if ((x($a->config, 'admin_email')) && (strcasecmp($email, $a->config['admin_email']) == 0)) {
if (x($a->config, 'admin_email')) { if (x($a->config, 'admin_email')) {
$adminlist = explode(",", str_replace(" ", "", strtolower($a->config['admin_email']))); $adminlist = explode(",", str_replace(" ", "", strtolower($a->config['admin_email'])));
if (in_array(strtolower($email), $adminlist)) { if (in_array(strtolower($email), $adminlist)) {
$err .= t(' Cannot change to that email.'); $err .= t('Cannot change to that email.');
$email = $a->user['email']; $email = $a->user['email'];
} }
} }

View File

@ -1,22 +1,71 @@
<?php <?php
/** /**
* @file src/Model/User.php * @file src/Model/User.php
* @brief This file includes the User class with user related database functions * @brief This file includes the User class with user related database functions
*/ */
namespace Friendica\Model; namespace Friendica\Model;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBM;
use dba; use dba;
require_once 'boot.php'; require_once 'boot.php';
require_once 'plugin.php'; require_once 'include/plugin.php';
/** /**
* @brief This class handles User related functions * @brief This class handles User related functions
*/ */
class User class User
{ {
public static function authenticate($user_info, $password)
{
if (is_object($user_info)) {
$user = (array) $user_info;
} elseif (is_int($user_info)) {
$user = dba::select('user',
['uid', 'password'],
[
'uid' => $user_info,
'blocked' => 0,
'account_expired' => 0,
'account_removed' => 0,
'verified' => 1
],
['limit' => 1]
);
} elseif (is_string($user_info)) {
$user = dba::fetch_first('SELECT `uid`, `password`
FROM `user`
WHERE (`email` = ? OR `username` = ? OR `nickname` = ?)
AND `blocked` = 0
AND `account_expired` = 0
AND `account_removed` = 0
AND `verified` = 1
LIMIT 1',
$user_info,
$user_info,
$user_info
);
} else {
$user = $user_info;
}
if (!DBM::is_result($user) || !isset($user['uid']) || !isset($user['password'])) {
return false;
}
$password_hashed = hash('whirlpool', $password);
if ($password_hashed !== $user['password']) {
return false;
}
return $user['uid'];
}
/** /**
* @param object $uid user to remove * @param object $uid user to remove
* @return void * @return void
@ -29,21 +78,20 @@ class User
logger('Removing user: ' . $uid); logger('Removing user: ' . $uid);
$r = dba::select('user', array(), array('uid' => $uid), array("limit" => 1)); $user = dba::select('user', [], ['uid' => $uid], ['limit' => 1]);
call_hooks('remove_user', $r); call_hooks('remove_user', $user);
// save username (actually the nickname as it is guaranteed // save username (actually the nickname as it is guaranteed
// unique), so it cannot be re-registered in the future. // unique), so it cannot be re-registered in the future.
dba::insert('userd', ['username' => $user['nickname']]);
dba::insert('userd', array('username' => $r['nickname']));
// The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php) // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
q("UPDATE `user` SET `account_removed` = 1, `account_expires_on` = UTC_TIMESTAMP() WHERE `uid` = %d", intval($uid)); dba::update('user', ['account_removed' => true, 'account_expires_on' => datetime_convert()], ['uid' => $uid]);
Worker::add(PRIORITY_HIGH, "Notifier", "removeme", $uid); Worker::add(PRIORITY_HIGH, "Notifier", "removeme", $uid);
// Send an update to the directory // Send an update to the directory
Worker::add(PRIORITY_LOW, "Directory", $r['url']); Worker::add(PRIORITY_LOW, "Directory", $user['url']);
if ($uid == local_user()) { if ($uid == local_user()) {
unset($_SESSION['authenticated']); unset($_SESSION['authenticated']);

View File

@ -37,6 +37,7 @@ namespace Friendica\Util;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Database\DBM; use Friendica\Database\DBM;
use Friendica\Model\User;
use dba; use dba;
require_once 'include/dba.php'; require_once 'include/dba.php';
@ -217,8 +218,8 @@ class ExAuth
$aUser = dba::select('user', ['uid', 'password'], ['nickname' => $sUser], ['limit' => 1]); $aUser = dba::select('user', ['uid', 'password'], ['nickname' => $sUser], ['limit' => 1]);
if (DBM::is_result($aUser)) { if (DBM::is_result($aUser)) {
$uid = $aUser['uid']; $uid = User::authenticate($aUser, $aCommand[3]);
$Error = $aUser['password'] != hash('whirlpool', $aCommand[3]); $Error = $uid === false;
} else { } else {
$this->writeLog(LOG_WARNING, 'user not found: ' . $sUser); $this->writeLog(LOG_WARNING, 'user not found: ' . $sUser);
$Error = true; $Error = true;

View File

@ -140,7 +140,7 @@ class Delivery {
} }
} }
$r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`, $r = q("SELECT `contact`.*, `user`.`prvkey` AS `uprvkey`,
`user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
`user`.`page-flags`, `user`.`account-type`, `user`.`prvnets` `user`.`page-flags`, `user`.`account-type`, `user`.`prvnets`
FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid` FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`

View File

@ -108,7 +108,7 @@ class Notifier {
$recipients[] = $suggest[0]['cid']; $recipients[] = $suggest[0]['cid'];
$item = $suggest[0]; $item = $suggest[0];
} elseif ($cmd === 'removeme') { } elseif ($cmd === 'removeme') {
$r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`, $r = q("SELECT `contact`.*, `user`.`prvkey` AS `uprvkey`,
`user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
`user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid` `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid` FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
@ -173,7 +173,7 @@ class Notifier {
} }
$r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`, $r = q("SELECT `contact`.*, `user`.`prvkey` AS `uprvkey`,
`user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
`user`.`page-flags`, `user`.`prvnets`, `user`.`account-type` `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`
FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid` FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* @file src/Worker/Queue.php * @file src/Worker/Queue.php
*/ */
@ -19,7 +20,8 @@ require_once 'include/items.php';
require_once 'include/bbcode.php'; require_once 'include/bbcode.php';
require_once 'include/salmon.php'; require_once 'include/salmon.php';
class Queue { class Queue
{
public static function execute($queue_id = 0) public static function execute($queue_id = 0)
{ {
global $a; global $a;
@ -57,8 +59,8 @@ class Queue {
if (DBM::is_result($r)) { if (DBM::is_result($r)) {
foreach ($r as $q_item) { foreach ($r as $q_item) {
logger('Call queue for id '.$q_item['id']); logger('Call queue for id ' . $q_item['id']);
Worker::add(array('priority' => PRIORITY_LOW, 'dont_fork' => true), "Queue", (int)$q_item['id']); Worker::add(array('priority' => PRIORITY_LOW, 'dont_fork' => true), "Queue", (int) $q_item['id']);
} }
} }
return; return;
@ -78,80 +80,71 @@ class Queue {
$q_item = $r[0]; $q_item = $r[0];
$c = q( $contact = dba::select('contact', [], ['id' => $q_item['cid']], ['limit' => 1]);
"SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", if (!DBM::is_result($contact)) {
intval($q_item['cid'])
);
if (!DBM::is_result($c)) {
remove_queue_item($q_item['id']); remove_queue_item($q_item['id']);
return; return;
} }
$dead = Cache::get($cachekey_deadguy.$c[0]['notify']); $dead = Cache::get($cachekey_deadguy . $contact['notify']);
if (!is_null($dead) && $dead) { if (!is_null($dead) && $dead) {
logger('queue: skipping known dead url: '.$c[0]['notify']); logger('queue: skipping known dead url: ' . $contact['notify']);
update_queue_time($q_item['id']); update_queue_time($q_item['id']);
return; return;
} }
$server = PortableContact::detectServer($c[0]['url']); $server = PortableContact::detectServer($contact['url']);
if ($server != "") { if ($server != "") {
$vital = Cache::get($cachekey_server.$server); $vital = Cache::get($cachekey_server . $server);
if (is_null($vital)) { if (is_null($vital)) {
logger("Check server ".$server." (".$c[0]["network"].")"); logger("Check server " . $server . " (" . $contact["network"] . ")");
$vital = PortableContact::checkServer($server, $c[0]["network"], true); $vital = PortableContact::checkServer($server, $contact["network"], true);
Cache::set($cachekey_server.$server, $vital, CACHE_QUARTER_HOUR); Cache::set($cachekey_server . $server, $vital, CACHE_QUARTER_HOUR);
} }
if (!is_null($vital) && !$vital) { if (!is_null($vital) && !$vital) {
logger('queue: skipping dead server: '.$server); logger('queue: skipping dead server: ' . $server);
update_queue_time($q_item['id']); update_queue_time($q_item['id']);
return; return;
} }
} }
$u = q( $user = dba::select('user', [], ['uid' => $contact['uid']], ['limit' => 1]);
"SELECT `user`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey` if (!DBM::is_result($user)) {
FROM `user` WHERE `uid` = %d LIMIT 1",
intval($c[0]['uid'])
);
if (!DBM::is_result($u)) {
remove_queue_item($q_item['id']); remove_queue_item($q_item['id']);
return; return;
} }
$data = $q_item['content']; $data = $q_item['content'];
$public = $q_item['batch']; $public = $q_item['batch'];
$contact = $c[0]; $owner = $user;
$owner = $u[0];
$deliver_status = 0; $deliver_status = 0;
switch ($contact['network']) { switch ($contact['network']) {
case NETWORK_DFRN: case NETWORK_DFRN:
logger('queue: dfrndelivery: item '.$q_item['id'].' for '.$contact['name'].' <'.$contact['url'].'>'); logger('queue: dfrndelivery: item ' . $q_item['id'] . ' for ' . $contact['name'] . ' <' . $contact['url'] . '>');
$deliver_status = DFRN::deliver($owner, $contact, $data); $deliver_status = DFRN::deliver($owner, $contact, $data);
if ($deliver_status == (-1)) { if ($deliver_status == (-1)) {
update_queue_time($q_item['id']); update_queue_time($q_item['id']);
Cache::set($cachekey_deadguy.$contact['notify'], true, CACHE_QUARTER_HOUR); Cache::set($cachekey_deadguy . $contact['notify'], true, CACHE_QUARTER_HOUR);
} else { } else {
remove_queue_item($q_item['id']); remove_queue_item($q_item['id']);
} }
break; break;
case NETWORK_OSTATUS: case NETWORK_OSTATUS:
if ($contact['notify']) { if ($contact['notify']) {
logger('queue: slapdelivery: item '.$q_item['id'].' for '.$contact['name'].' <'.$contact['url'].'>'); logger('queue: slapdelivery: item ' . $q_item['id'] . ' for ' . $contact['name'] . ' <' . $contact['url'] . '>');
$deliver_status = slapper($owner, $contact['notify'], $data); $deliver_status = slapper($owner, $contact['notify'], $data);
if ($deliver_status == (-1)) { if ($deliver_status == (-1)) {
update_queue_time($q_item['id']); update_queue_time($q_item['id']);
Cache::set($cachekey_deadguy.$contact['notify'], true, CACHE_QUARTER_HOUR); Cache::set($cachekey_deadguy . $contact['notify'], true, CACHE_QUARTER_HOUR);
} else { } else {
remove_queue_item($q_item['id']); remove_queue_item($q_item['id']);
} }
@ -159,12 +152,12 @@ class Queue {
break; break;
case NETWORK_DIASPORA: case NETWORK_DIASPORA:
if ($contact['notify']) { if ($contact['notify']) {
logger('queue: diaspora_delivery: item '.$q_item['id'].' for '.$contact['name'].' <'.$contact['url'].'>'); logger('queue: diaspora_delivery: item ' . $q_item['id'] . ' for ' . $contact['name'] . ' <' . $contact['url'] . '>');
$deliver_status = Diaspora::transmit($owner, $contact, $data, $public, true); $deliver_status = Diaspora::transmit($owner, $contact, $data, $public, true);
if ($deliver_status == (-1)) { if ($deliver_status == (-1)) {
update_queue_time($q_item['id']); update_queue_time($q_item['id']);
Cache::set($cachekey_deadguy.$contact['notify'], true, CACHE_QUARTER_HOUR); Cache::set($cachekey_deadguy . $contact['notify'], true, CACHE_QUARTER_HOUR);
} else { } else {
remove_queue_item($q_item['id']); remove_queue_item($q_item['id']);
} }
@ -182,7 +175,7 @@ class Queue {
} }
break; break;
} }
logger('Deliver status '.(int)$deliver_status.' for item '.$q_item['id'].' to '.$contact['name'].' <'.$contact['url'].'>'); logger('Deliver status ' . (int) $deliver_status . ' for item ' . $q_item['id'] . ' to ' . $contact['name'] . ' <' . $contact['url'] . '>');
return; return;
} }