For a plugin system I am writing, I need to write a database API. But I want to restrict database access, so plugins can't see other tables than the ones they created through a specific function. How would I enable plugins to use SQL, but not give them full access at the same time?
Here is some code, it may not be working, but it shows the idea behind it:
class Api_Database {
private $pluginid;
function __construct($pluginid) {
$this->pluginid = $pluginid;
}
function query($sql, $tablename) {
$db = new Sys_Database;
$db->query(str_replace('{table}', $pluginid.$tablename, $sql));
}
}
Am I thinking in the right direction here? How would you create such a system, only more secure?
The idea is to create a table containing the list of created tables linked to the user...
Something like :
privileges
user_id
table_name
And in your query
SELECT FROM privileges WHERE user_id = '{user_id}' and table_name = '{table}';
And after check if the row exist. If yes, the user have the right to use the table!
class Api_Database {
private $pluginid;
function __construct($pluginid) {
$this->pluginid = $pluginid;
}
function query($sql, $tablename) {
$hasPrivilege = $this->checkPrivileges($tablename, $userid);
if(!$hasPrivilege) return false; //for example
$db = new Sys_Database;
$db->query(str_replace('{table}', $pluginid.$tablename, $sql));
}
function checkPrivileges($table, $user_id) {
$db = new Sys_Database;
$result = $db->query('SELECT id FROM privileges WHERE user_id = "'.$user_id.'" AND table_name = "'.$table.'"');
return ($result && $result->num_rows);
}
}
EDIT
So if I understand correctly, you are using a PHP plugin to access SQL data, but you can't or doesn't want to change it.
You cant' add SQL users too, and you wan't to restrict PHP Dev to make some queries in some table via PHP?? Hum... Impossible!
Because to be able to disallow database table access, YOU HAVE TO MANIPULATE PHP OR MYSQL USERS...
Or if I'm wrong, sorry, it's difficult to follow you!
Related
I have a snippet of code from an existing system that is pulling the users 2-digit country code from an obsolete database table. Normally I have updated the table on a regular basis but I am quite honestly sick of doing it. What I would like to do is make this more of a live pull each time a user logs in. This is the existing code
public static function geoip_country_code_by_name($ip)
{
if ($_SERVER['HTTP_CF_IPCOUNTRY']) {
return $_SERVER['HTTP_CF_IPCOUNTRY'];
}
$sql = "SELECT country FROM ip2country WHERE ip < INET_ATON('$ip') ORDER BY ip DESC LIMIT 0,1";
$res = DB::selectOneBySQL($sql);
return $res->country;
}
I am looking for suggestions on how to best accomplish this.
I decided to use this solution. It also allows me the option to grab additional information in the future if required. I might eventually move to a paid service either with this API or another but for now this solved my issue
public static function geoip_country_code_by_name($ip)
{
if ($_SERVER['HTTP_CF_IPCOUNTRY']) {
return $_SERVER['HTTP_CF_IPCOUNTRY'];
}
$iptolocation = #json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
$creatorlocation = $iptolocation->geoplugin_countryCode;
return $creatorlocation;
}
Am getting an error of prepared statement "my_query7" already exists, i call this function each time a user tries to update table leader_info in the database, i have gone through the documentation for pg_prepare and i don't understand what is meant by it should only be run once. code snippets will be of help. Thanks.
function add_leader_country($user_id,$l_country)
{
global $connection;
$query = pg_prepare($connection,"my_query7","update leader_info set l_country = $1 where user_id = $2 and status < 9");
$result = pg_execute($connection,"my_query7",array($l_country,$user_id));
if(!$result)
{
echo pg_last_error($connection);
}
else
{
echo "Records created successfully\n";
}
$row = pg_affected_rows($result);
return $row;
}
Prepare execute does not permit duplicate naming, so that is your error.
A query should only be prepared once, for example, in a cycle for the preparation state must be set out of the for and its execution in the for.
$result=$pg_prepare($connection,"my_query7",$query);
for($id=1;$id<3;$id++){
$result=pg_execute($connection,"my_query7",array($l_country,$user_id));
...
}
In your case using a functio that use the prepare and execute multiple times it's a problem.
What are you trying to accomplish with this function dispatches more code like where you are calling the function. This way I might be able to help you.
If you want to use functions I would use this method
Exemple from https://secure.php.net
<?php
function requestToDB($connection,$request){
if(!$result=pg_query($connection,$request)){
return False;
}
$combined=array();
while ($row = pg_fetch_assoc($result)) {
$combined[]=$row;
}
return $combined;
}
?>
<?php
$conn = pg_pconnect("dbname=mydatabase");
$results=requestToDB($connect,"select * from mytable");
//You can now access a "cell" of your table like this:
$rownumber=0;
$columname="mycolumn";
$mycell=$results[$rownumber][$columname];
var_dump($mycell);
If you whant to use preaper and execute functions try to create a function that creates the preparations only once in a session. Do not forget to give different names so that the same error does not occur. I tried to find something of the genre and did not find. If you find a form presented here for others to learn. If in the meantime I find a way I present it.
so this is very simple.
Essentially, I'd like to connect the following class:
class mailManager{
function add($address){
$check = $db->query("SELECT * FROM mail_list WHERE email = '$address'");
$exist = mysqli_num_rows($check);
if($exist > 0){
return "Whoops! Your email is already registered with us.";
}else{
if($insert = $db->query("INSERT INTO mail_list (email, datetime) VALUES ('$address', DATE)")){
return "Success! You've joined the CSGO Earn family.";
} else {
return "Aw snap! There was a database communication error. Please try later.";
}
}
}
}
to the database.
However, nothing 'obvious' that I try seems to work and a google search has yielded no results that I can understand. Perhaps somebody could explain it simply for me?
Note: The SQL is there, but it doesn't do anything (obviously).
Regards
Your class does not have immediate access to your $db. You can do this a few different ways.
1) Pass $db into your public function __construct($db) and assign it to a class member like private $db; (most useful)
You then access it like $check = $this->db->query("..etc..");
2) Pass it in via a parameter to the add() function like so:
public function add($address, $db) {
}
3) Bring it in as a global variable: (easiest)
function add($address){
global $db;
$check = $db->query("SELECT * FROM mail_list WHERE email = '$address'");
/*
etc....
*/
}
I'd recommend learning how to do the first one as it will come in very handy when you have a number of database calls within your class.
Two more things regarding your code in the function.
1) You should use NOW() instead of DATE.
2) Since you are using the OOP implementation of mysqli, you should change mysqli_num_rows($check); to $check->num_rows();. I'm not sure if it will work the way you have it, but even if it does it's good practice to treat your objects uniformly.
after searching for a long time got this great article its really very nice
but i am facing a bit problem here in my stuff as u have used direct mysql query in api i have used stored procedure in here and every time i have to compare two XML before and after even for a single short and sweet query so is there any alternative for this process but which is this secure
please chk this out u will get i more clearly
database testing in php using phpunit,simpletest on api haveing stored procedure
or how shall i compare to xml files before and after api function call(the function contains the stored procedure)
means i am able to get the before state with mysql-dump but the after but not getting the instant after xml state
sorry for the English but tried my best
thanks for the help friend
have to write an unit test test for the api function
public function delete($userId)
{
// this function calls a stored procedure
$sql = "CALL Delete_User_Details(:userId)";
try {
$db = parent::getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userId", $userId);
$stmt->execute();
$id = $stmt->fetchObject();
if ($id == null) {
$delete_response->createJSONArray("DATABASE_ERROR",0);
} else {
$delete_response->createJSONArray("SUCCESS",1);
}
} catch (PDOException $e) {
$delete_response->createJSONArray("DATABASE_ERROR",0);
}
return $delete_response->toJSON();
}
i have writen this unit test for it now want to write an dbunit for it
public function testDeleteUser()
{
$decodedResponse = $response->json();
$this->assertEquals($response->getStatusCode(), 200);
$this->assertEquals($decodedResponse['status']['StatusMSG'], 'SUCCESS');
$this->assertEquals($decodedResponse['status']['Code'], '1');
}
help guyss
u can just simply test it before by calling the query like
$sql = "select * from user";
and compare it with BeforeDeleteUser.xml
And the Call Ur stored procedure
$sql = "CALL Delete_User_Details(:userId)";
And for the after case just repeat the before one again
$sql = "select * from user";
and compare it with AfterDeleteUser.xml
see the logic is very simple if u have 5 Users in BeforeDeleteUser.xml and it results true and after the call of CALL Delete_User_Details(:userId) stored procedure , the AfterDeleteUser.xml should contain only 4 user (or maybe idDelete field to 0 that depends on ur implementation)
I'm just getting started on writing functions instead of writing everything inline. Is this how a reusable function is typically written?
function test_user($user) {
$conn = get_db_conn();
$res = mysql_query("SELECT * FROM users WHERE uid = $user");
$row = mysql_fetch_assoc($res);
if (count($row) == 1) {
return true;
}
else {
return false;
}
}
When someone logs in, I have their UID. I want to see if that's in the DB already. It's basic logic will be used in a
"If exists, display preferences, if !exists, display signup box" sort of flow. Obviously it's dependent on how it's used in the rest of the code, but will this work as advertised and have I fallen for any pitfalls? Thanks!
Try this:
$conn = get_db_conn(); # should reuse a connection if it exists
# Have MySQL count the rows, instead of fetching a list (also prevent injection)
$res = mysql_query(sprintf("SELECT COUNT(*) FROM users WHERE uid=%d", $user));
# if the query fails
if (!$res) return false;
# explode the result
list($count) = mysql_fetch_row($res);
return ($count === '1');
Thoughts:
You'll want better handling of a failed query, since return false means the user doesn't already exist.
Use the database to count, it'll be faster.
I'm assuming uid is an integer in the sprintf statement. This is now safe for user input.
If you have an if statement that looks like if (something) { true } else { false } you should collapse it to just return something.
HTH
That is reuseable, yes. You may want to consider moving the SQL out of the PHP code itself.
Although you weren't asking for optimization necessarily, you might want to consider querying for the user's display preferences (which I assume are stored in the DB) and if it comes back empty, display the signup box. You'll save a trip to the database and depending on your traffic, that could be huge. If you decide to keep this implementation, I would suggest only selecting one column from the database in your SELECT. As long as you don't care about the data, there's no reason to fetch every single column.
First off, you need to call
$user = mysql_real_escape_string($user);
because there's an sql injection bug in your code, see the manual. Second, you can simplify your logic by changing your query to:
SELECT COUNT(1) FROM user WHERE uid = $user;
which just lets you evaluate a single return value from $row. Last thing, once you have the basics of php down, consider looking at a php framework. They can cause you trouble and won't make you write good code, but they likely will save you a lot of work.
Indent!
Overall it looks not bad...check the comments..
function test_user($user)
{
$conn = get_db_conn(); //this should be done only once. Maybe somewhere else...?
$res = mysql_query("SELECT uid FROM users WHERE uid = $user");
$row = mysql_fetch_assoc($res);
//I can't remember...can you return count($row) and have that forced to boolean ala C? It would reduce lines of code and make it easier to read.
if (count($row) == 1) {
return true;
}
else {
return false;
}
}
Also,
if (condition) {
return true;
}
else {
return false;
}
can be rewritten as:
return condition;
which saves quite a bit of typing and reading :)