| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- #include <iostream>
- #include <sstream>
- #include <ldap.h>
- #include "ldapReader.h"
- LDAPReader::LDAPReader(const std::string& _uri, const std::string& _attribute,
- const std::string& _base, const std::string& _filter):
- uri(_uri), attribute(_attribute), baseDn(_base), filter(_filter)
- {}
- LDAPReader::~LDAPReader()
- {}
- LDAP* LDAPReader::InitConnection()
- {
- LDAP* ldapHandler;
- int protoVersion = LDAP_VERSION3;
- int err = ldap_initialize(&ldapHandler, uri.c_str());
- if (err != LDAP_SUCCESS)
- {
- std::cerr << "LDAP Initialize error: (" << err << ") " << ldap_err2string(err) << std::endl;
- return nullptr;
- }
- err = ldap_set_option(ldapHandler, LDAP_OPT_PROTOCOL_VERSION, &protoVersion);
- if (err != LDAP_SUCCESS)
- {
- std::cerr << "LDAP Protocol error: (" << err << ") " << ldap_err2string(err) << std::endl;
- return nullptr;
- }
- return ldapHandler;
- }
- bool LDAPReader::CheckFilter(LDAP* ldapHandler, const std::string& queryBase)
- {
- LDAPMessage* msg;
- struct timeval timeo;
- timeo.tv_sec = 5;
- timeo.tv_usec = 0;
- char attrCstr[attribute.length()];
- strcpy(attrCstr, attribute.c_str());
- char* attrs[] = { attrCstr, nullptr };
- int err = ldap_search_ext_s(ldapHandler, queryBase.c_str(), LDAP_SCOPE_BASE, filter.c_str(), attrs, false, nullptr, nullptr, &timeo, 1, &msg);
- if (err != LDAP_SUCCESS)
- {
- std::cerr << "LDAP Search Error: (" << err << ") " << ldap_err2string(err) << std::endl;
- return false;
- }
- if (!msg)
- return false;
- bool result = nullptr != ldap_first_entry(ldapHandler, msg);
- ldap_msgfree(msg);
- return result;
- }
- bool LDAPReader::Authenticate(const std::string& username, const std::string& password)
- {
- LDAP* ldapHandler = InitConnection();
- if (!ldapHandler)
- return false;
- std::stringstream bindDn;
- bindDn << attribute << "=" << username << "," << baseDn;
- struct berval bindPw;
- char passwordCstr[password.length()];
- strcpy(passwordCstr, password.c_str());
- bindPw.bv_len = password.length();
- bindPw.bv_val = passwordCstr;
- int err = ldap_sasl_bind_s(ldapHandler, bindDn.str().c_str(), LDAP_SASL_SIMPLE, &bindPw, nullptr, nullptr, nullptr);
- bool success = err == LDAP_SUCCESS;
- if (!success)
- std::cerr << "LDAP Bind Error: (" << err << ") " << ldap_err2string(err) << std::endl;
- else if (!filter.empty())
- success &= CheckFilter(ldapHandler, bindDn.str());
- ldap_unbind_ext(ldapHandler, nullptr, nullptr);
- return success;
- }
|