Poco::SharedPtr<Poco::MongoDB::QueryRequest> Database::createCountRequest(const std::string& collectionName) const { Poco::SharedPtr<Poco::MongoDB::QueryRequest> request = createQueryRequest("$cmd"); request->setNumberToReturn(1); request->selector().add("count", collectionName); return request; }
bool MongoAuthentication::authenticateMongoCR(const std::string &user, const std::string &pwd) { bool ret = false; _user = user; _pwd = pwd; try { std::string nonce; Poco::SharedPtr<Poco::MongoDB::QueryRequest> command = _db.createCommand(); command->selector().add<Poco::Int32>("getnonce", 1); command->setNumberToReturn(1); Poco::MongoDB::ResponseMessage response; _conn.sendRequest(*command, response); if (response.documents().size() > 0) { Poco::MongoDB::Document::Ptr doc = response.documents()[0]; nonce = doc->get<std::string>("nonce", ""); std::string password = _user + ":mongo:" + _pwd; Poco::MD5Engine md5; md5.update(password); std::string hashedPassword(Poco::DigestEngine::digestToHex(md5.digest())); std::string key = nonce + _user + hashedPassword; md5.reset(); md5.update(key); std::string hashedKey(Poco::DigestEngine::digestToHex(md5.digest())); Poco::SharedPtr<Poco::MongoDB::QueryRequest> command = _db.createCommand(); command->selector() .add<Poco::Int32>("authenticate", 1) .add<std::string>("user", _user) .add<std::string>("nonce", nonce) .add<std::string>("key", hashedKey); // hex_md5( n.nonce + username + hex_md5( username + ":mongo:" + password ) ) _conn.sendRequest(*command, response); if (response.documents().size() > 0 && response.documents()[0]->get<double>("ok")) { ret = true; } } } catch (Poco::Exception &) { throw Poco::ApplicationException("auth failed."); } return ret; }
Document::Ptr Database::getLastErrorDoc(Connection& connection) const { Document::Ptr errorDoc; Poco::SharedPtr<Poco::MongoDB::QueryRequest> request = createQueryRequest("$cmd"); request->setNumberToReturn(1); request->selector().add("getLastError", 1); Poco::MongoDB::ResponseMessage response; connection.sendRequest(*request, response); if ( response.documents().size() > 0 ) { errorDoc = response.documents()[0]; } return errorDoc; }
// SELECT * FROM players LIMIT 1 void sample9(Poco::MongoDB::Connection& connection) { std::cout << "*** SAMPLE 9 ***" << std::endl; // QueryRequest can be used directly Poco::MongoDB::QueryRequest query("sample.players"); query.setNumberToReturn(1); Poco::MongoDB::ResponseMessage response; connection.sendRequest(query, response); if ( response.hasDocuments() ) { std::cout << response.documents()[0]->toString(2) << std::endl; } // QueryRequest can be created using the Database class Poco::MongoDB::Database db("sample"); Poco::SharedPtr<Poco::MongoDB::QueryRequest> queryPtr = db.createQueryRequest("players"); queryPtr->setNumberToReturn(1); connection.sendRequest(*queryPtr, response); if ( response.hasDocuments() ) { std::cout << response.documents()[0]->toString(2) << std::endl; } }