ldapReader.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <iostream>
  2. #include <sstream>
  3. #include <ldap.h>
  4. #include "ldapReader.h"
  5. LDAPReader::LDAPReader(const std::string& _uri, const std::string& _attribute,
  6. const std::string& _base, const std::string& _filter):
  7. uri(_uri), attribute(_attribute), baseDn(_base), filter(_filter)
  8. {}
  9. LDAPReader::~LDAPReader()
  10. {}
  11. LDAP* LDAPReader::InitConnection()
  12. {
  13. LDAP* ldapHandler;
  14. int protoVersion = LDAP_VERSION3;
  15. int err = ldap_initialize(&ldapHandler, uri.c_str());
  16. if (err != LDAP_SUCCESS)
  17. {
  18. std::cerr << "LDAP Initialize error: (" << err << ") " << ldap_err2string(err) << std::endl;
  19. return nullptr;
  20. }
  21. err = ldap_set_option(ldapHandler, LDAP_OPT_PROTOCOL_VERSION, &protoVersion);
  22. if (err != LDAP_SUCCESS)
  23. {
  24. std::cerr << "LDAP Protocol error: (" << err << ") " << ldap_err2string(err) << std::endl;
  25. return nullptr;
  26. }
  27. return ldapHandler;
  28. }
  29. bool LDAPReader::CheckFilter(LDAP* ldapHandler, const std::string& queryBase)
  30. {
  31. LDAPMessage* msg;
  32. struct timeval timeo;
  33. timeo.tv_sec = 5;
  34. timeo.tv_usec = 0;
  35. char attrCstr[attribute.length()];
  36. strcpy(attrCstr, attribute.c_str());
  37. char* attrs[] = { attrCstr, nullptr };
  38. int err = ldap_search_ext_s(ldapHandler, queryBase.c_str(), LDAP_SCOPE_BASE, filter.c_str(), attrs, false, nullptr, nullptr, &timeo, 1, &msg);
  39. if (err != LDAP_SUCCESS)
  40. {
  41. std::cerr << "LDAP Search Error: (" << err << ") " << ldap_err2string(err) << std::endl;
  42. return false;
  43. }
  44. if (!msg)
  45. return false;
  46. bool result = nullptr != ldap_first_entry(ldapHandler, msg);
  47. ldap_msgfree(msg);
  48. return result;
  49. }
  50. bool LDAPReader::Authenticate(const std::string& username, const std::string& password)
  51. {
  52. LDAP* ldapHandler = InitConnection();
  53. if (!ldapHandler)
  54. return false;
  55. std::stringstream bindDn;
  56. bindDn << attribute << "=" << username << "," << baseDn;
  57. struct berval bindPw;
  58. char passwordCstr[password.length()];
  59. strcpy(passwordCstr, password.c_str());
  60. bindPw.bv_len = password.length();
  61. bindPw.bv_val = passwordCstr;
  62. int err = ldap_sasl_bind_s(ldapHandler, bindDn.str().c_str(), LDAP_SASL_SIMPLE, &bindPw, nullptr, nullptr, nullptr);
  63. bool success = err == LDAP_SUCCESS;
  64. if (!success)
  65. std::cerr << "LDAP Bind Error: (" << err << ") " << ldap_err2string(err) << std::endl;
  66. else if (!filter.empty())
  67. success &= CheckFilter(ldapHandler, bindDn.str());
  68. ldap_unbind_ext(ldapHandler, nullptr, nullptr);
  69. return success;
  70. }