Monday, June 15, 2009

Searching For A User

Searching for a user in the datastore uses the Query interface. We get a Query by aking for one from a PerstistenceManager. There are several ways to populate a Query...I'll use the SQL like form:


Query query = pm.newQuery("select from project.server.User where identifier == " + identifier);


Note the use of the project.server.User notation to say which class you want to load. Change the project to be the name of your project.

If your first thought on seeing that wasn't, "What about SQL injection attacks?", then you should read this tutorial.

In this particular instance, the likelihood of suffering an SQL injection attack is low, since the data is coming from a request to RPX. Nobody can just load up the RPXResults servlet in a browser and inject an arbitrary identifier.

But, it never hurts to be safe, so let's use a parameter to lessen the risk:


Query query = pm.newQuery("select from project.server.User where identifier == identifierParam");
query.declareParameters("String identifierParam");


Note that parameters may lessen your risk of an SQL injection attack, but it depends on the implementation of JDO. I'd like to think Google is on top of its game with App Engine security, but we should be wary of relying on that for pages that are susceptible to SQL injection. When we get to a page that's more vulnerable, we'll look at ways to protect the page.

Now that we have a Query, we need to execute it and provide the value for the parameter:


try
{
  List results = (List) query.execute(identifier);
}
finally
{
  query.closeAll();
}


We can then use normal List methods for iterating over elements of the list of Users that has been returned. Note that since our identifier field is not a unique field, the List could theoretically have more than one element. But we'll write the code so that we only have one User per identifier, so the List will either have zero elements (for a new user) or one element.

We'll put the pieces together in the next post.

No comments:

Post a Comment