ldapReader.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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, const std::string& _base):
  6. uri(_uri), attribute(_attribute), baseDn(_base)
  7. {}
  8. LDAPReader::~LDAPReader()
  9. {}
  10. void* LDAPReader::InitConnection()
  11. {
  12. LDAP* ldapHandler;
  13. int protoVersion = LDAP_VERSION3;
  14. int err = ldap_initialize(&ldapHandler, uri.c_str());
  15. if (err != LDAP_SUCCESS)
  16. {
  17. std::cerr << "LDAP Initialize error: (" << err << ") " << ldap_err2string(err) << std::endl;
  18. return nullptr;
  19. }
  20. err = ldap_set_option(ldapHandler, LDAP_OPT_PROTOCOL_VERSION, &protoVersion);
  21. if (err != LDAP_SUCCESS)
  22. {
  23. std::cerr << "LDAP Protocol error: (" << err << ") " << ldap_err2string(err) << std::endl;
  24. return nullptr;
  25. }
  26. return ldapHandler;
  27. }
  28. bool LDAPReader::Authenticate(const std::string& username, const std::string& password)
  29. {
  30. LDAP* ldapHandler = reinterpret_cast<LDAP*>(InitConnection());
  31. if (!ldapHandler)
  32. return false;
  33. std::stringstream bindDn;
  34. bindDn << attribute << "=" << username << "," << baseDn;
  35. struct berval bindPw;
  36. char passwordCstr[password.length()];
  37. strcpy(passwordCstr, password.c_str());
  38. bindPw.bv_len = password.length();
  39. bindPw.bv_val = passwordCstr;
  40. int err = ldap_sasl_bind_s(ldapHandler, bindDn.str().c_str(), LDAP_SASL_SIMPLE, &bindPw, nullptr, nullptr, nullptr);
  41. if (err != LDAP_SUCCESS)
  42. std::cerr << "LDAP Bind Error: (" << err << ") " << ldap_err2string(err) << std::endl;
  43. ldap_unbind_ext(ldapHandler, nullptr, nullptr);
  44. return err == LDAP_SUCCESS;
  45. }