try { //put in a try so that we can have a finally block which resets namespaces
Key key = KeyFactory.createKey("AuthKey", "master");
DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService();
// look for the auth key in the datastore
Entity authEntity = (Entity) memcacheService.get(KeyFactory.keyToString(key));
if (authEntity == null) {
try {
authEntity = datastoreService.get(key);
memcacheService.put(KeyFactory.keyToString(key), authEntity);
} catch (EntityNotFoundException e) {
_logger.info("Authentication entity not found in memcache or datastore");
authEntity = null;
}
}
if (null != updateAuth) {
//if we're updating the auth
if (null == authEntity || !authEntity.getProperty("secret").equals(updateAuth)) {
//if there is no auth key, or the auth key doesn't match the one provided
try {
URLFetchService fetchService = URLFetchServiceFactory.getURLFetchService();
String host = URLEncoder.encode(req.getHeader("Host"), "UTF-8");
HTTPResponse response = fetchService.fetch(new URL(SECURE_HOST + "/auth/?site=" + host + "&auth=" + updateAuth));
if (response.getResponseCode() == 200) {
//if successfully received a response, save the new auth key
String content = new String(response.getContent());
if (content.equals(new String("OK"))) {
authEntity = new Entity(key);
authEntity.setProperty("secret", updateAuth);
datastoreService.put(authEntity);
memcacheService.put(KeyFactory.keyToString(key), authEntity);
}
}
} catch (Exception e) {
_logger.severe("Exception while updating key: " + e);
return null;