Problem as follows:
I'm in charge of a creating a web services interface to a system with a huge database (hundreds of tables). The top level table in the database is "Accounts", with primary key Account_Id. Each row in any table can ultimately be traced back to a single account.
Each account should have access to their own account via the web services.
Let's say I create a web services function
DeleteProduct(string privateAccountKey, int productId);
How can I make sure - in a general an automatic manner - that the product they are trying to delete (who's primary key is productId) actually belongs to the account in question?
Update:
Thanks for your quick answers, but I need a more general solution:
Let's say we have 10 nested tables A,B,C,D,E,F,G,H,I,J. A is the top-level table, B has a foreign key into A, C has a foreign key into B, D has a foreign key into C, etc.
Given only a primary key of A and a primary key of J, we want to delete row in J. But we want to make sure that the row we delete "belongs to" the row in A identified by the supplied primary key of A. That is, we need to "join back" or "trace back" via the foreign keys from J back to A, find out which primary key in A the primary key from J is related to and compare it to the supplied primary key from A which we must make sure it is related to.
Can this be done in a general matter by using the system tables or something? No hardcoded joins and checks. It should work on any number of nested tables given only primary key of top-level table in tandem with primary key of bottom-level table (or any table in between).
Old:
I'm concernced that they could potentially send along product IDs which belongs to other accounts and those products would get deleted. The same problems exists with any other deletion or change of data.
What I need is a stored procedure which takes as input
a) A table name and the name of the primary key of this table
b) the primary key itself of a row in this table
c) the ID of the top-level primary key
and performs:
d) find out which account the primary key of b) belongs to
e) return true if the account from d) matches the ID (and account) from c)
E.g.:
PKBelongsToAccount(string table, string primaryKeyName, int ID, int accountId)
Pseudo:
DeleteProduct(string privateAccountKey, int productId)
{
int accountId = FindAccountWhosPrivateKeyIs(privateAccountKey);
if (!PKBelongsToAccount("Products", "Product_Id", productId, accountId))
{
return;
}
else
{
// Product can safely be deleted
}
}
Solve PKBelongsToAccount (as an SQL function/procedure). It needs to trace up the database relationships via the FK's until it gets to the Account table, find out which account it actually belongs to and compare this to the account ID of what we want it to belong to.
Perhaps there are better ways of doing it.
Sorry for the mess.