Opens the dao's connection. Dn and credentials are used for authentication. Throws an {@link LdapDaoException} in
case of IO error or invalid dn.
11529
public void connect(String dn, String credentials) {
        BindRequest bindRequest = new BindRequestImpl();
        bindRequest.setCredentials(credentials);
        try {
            bindRequest.setDn(new Dn(dn));
            connection.connect();
            connection.bind(bindRequest);
            ((LdapNetworkConnection) connection).loadSchema(new DefaultSchemaLoader(connection));
        } catch (Exception e) {
            throw new LdapDaoException(e);
        }
    }
1204439
public Credentials userSignIn(Credentials credentials) throws DAOException {
            Credentials dbCreds = getUserByEmail(dao,credentials.getEmailAddress());
            if (dbCreds == null){
                throw new DAOException(HttpStatus.SC_UNAUTHORIZED,"User Doesnt exist");
            }
            else {
                //check if we are resetting the password
                if(dbCreds.getValidation()!=null && dbCreds.getValidation().equals(credentials.getValidation())){
                    credentials.decryptPassword(keyManager.getPrivateKey()); //decrypt the password
                    dbCreds.setPassword(BCrypt.hashpw(credentials.getPassword(), BCrypt.gensalt(10))); //set the new password
                }
                //else check password
                else {
                    String en = credentials.getPassword();
                    credentials.decryptPassword(keyManager.getPrivateKey()); //decrypt the password
                    String de = credentials.getPassword();
                    String ha = BCrypt.hashpw(de, BCrypt.gensalt(10));
                    System.out.println("Comparing passwords.\n" +
                            "Encrypted: " + en + "\n" +
                            "Decrypted: " + de + "\n" +
                            "Hashed:    " + ha + "\n" +
                            "Stored:    " + dbCreds.getPassword());
                    if (!BCrypt.checkpw(de, dbCreds.getPassword())){
                        throw new DAOException(HttpStatus.SC_UNAUTHORIZED,"User Already Exists");
                    }
                }

//              check if token is expired, if so return/set new
                AuthTokenUtils.AuthToken token;
                try {
                    token = new AuthTokenUtils.AuthToken(keyManager.getSymmetricKey(),dbCreds.getAuthToken());
                } catch (AuthenticationException e) {
                    throw new DAOException(HttpStatus.SC_INTERNAL_SERVER_ERROR,"internal error");
                }
                if (c.getTime().getTime() > token.expirationDate) {
                    dbCreds.setAuthToken(AuthTokenUtils.getNewToken(keyManager.getSymmetricKey(), dbCreds));
                    dao.save(dbCreds);
                }

                return dbCreds;
            }
    }
68302
public Rdn getRdn(final LDAPNode node) throws FrameworkException, LdapInvalidDnException {

		String name = node.getUserProvidedName();
		if (name == null) {

			name = node.getRdn();
		}

		return new Rdn(schemaManager, name);
	}
916331
def auth(self, username, password):
        """"""

        binddn = self._get_user(self._byte_p2(username), NO_ATTR)
        if binddn is not None:
            ldap_client = self._connect()
            try:
                ldap_client.simple_bind_s(
                        self._byte_p2(binddn),
                        self._byte_p2(password)
                        )
            except ldap.INVALID_CREDENTIALS:
                ldap_client.unbind_s()
                return False
            ldap_client.unbind_s()
            return True
        else:
            return False
430195
def _get_connection(self):
        
        if self._connection is None:
            uri = self.settings.SERVER_URI
            if callable(uri):
                if func_supports_parameter(uri, "request"):
                    uri = uri(self._request)
                else:
                    warnings.warn(
                        "Update AUTH_LDAP_SERVER_URI callable %s.%s to accept "
                        "a positional `request` argument. Support for callables "
                        "accepting no arguments will be removed in a future "
                        "version." % (uri.__module__, uri.__name__),
                        DeprecationWarning,
                    )
                    uri = uri()

            self._connection = self.backend.ldap.initialize(uri, bytes_mode=False)

            for opt, value in self.settings.CONNECTION_OPTIONS.items():
                self._connection.set_option(opt, value)

            if self.settings.START_TLS:
                logger.debug("Initiating TLS")
                self._connection.start_tls_s()

        return self._connection
584315
protected void openConnection() throws SQLException {
        if (connection == null) {
            try {
                Class.forName(configuration.getJdbcDriver());
            } catch (NullPointerException npe) {
                throw new RuntimeException("error while lookup jdbc driver class. jdbc driver is not configured.", npe);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("jdbc driver not found", e);
            }

            connection = DriverManager.getConnection(configuration.getJdbcUrl(), configuration.getJdbcUser(),
                    configuration.getJdbcPassword());
            connection.setAutoCommit(false);
        }
    }
257708
@Override
    public synchronized void authenticate() throws PortalSecurityException {
        this.isauth = false;
        ILdapServer ldapConn;

        ldapConn = LdapServices.getDefaultLdapServer();

        String creds = new String(this.myOpaqueCredentials.credentialstring);
        if (this.myPrincipal.UID != null
                && !this.myPrincipal.UID.trim().equals("")
                && this.myOpaqueCredentials.credentialstring != null
                && !creds.trim().equals("")) {
            DirContext conn = null;
            NamingEnumeration results = null;
            StringBuffer user = new StringBuffer("(");
            String first_name = null;
            String last_name = null;

            user.append(ldapConn.getUidAttribute()).append("=");
            user.append(this.myPrincipal.UID).append(")");
            log.debug("SimpleLdapSecurityContext: Looking for {}", user.toString());

            try {
                conn = ldapConn.getConnection();

                // set up search controls
                SearchControls searchCtls = new SearchControls();
                searchCtls.setReturningAttributes(attributes);
                searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

                // do lookup
                if (conn != null) {
                    try {
                        results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls);
                        if (results != null) {
                            if (!results.hasMore()) {
                                log.error(
                                        "SimpleLdapSecurityContext: user not found: {}",
                                        this.myPrincipal.UID);
                            }
                            while (results != null && results.hasMore()) {
                                SearchResult entry = (SearchResult) results.next();
                                StringBuffer dnBuffer = new StringBuffer();
                                dnBuffer.append(entry.getName()).append(", ");
                                dnBuffer.append(ldapConn.getBaseDN());
                                Attributes attrs = entry.getAttributes();
                                first_name = getAttributeValue(attrs, ATTR_FIRSTNAME);
                                last_name = getAttributeValue(attrs, ATTR_LASTNAME);
                                // re-bind as user
                                conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL);
                                conn.removeFromEnvironment(
                                        javax.naming.Context.SECURITY_CREDENTIALS);
                                conn.addToEnvironment(
                                        javax.naming.Context.SECURITY_PRINCIPAL,
                                        dnBuffer.toString());
                                conn.addToEnvironment(
                                        javax.naming.Context.SECURITY_CREDENTIALS,
                                        this.myOpaqueCredentials.credentialstring);
                                searchCtls = new SearchControls();
                                searchCtls.setReturningAttributes(new String[0]);
                                searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

                                String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)";
                                log.debug(
                                        "SimpleLdapSecurityContext: Looking in {} for {}",
                                        dnBuffer.toString(),
                                        attrSearch);
                                conn.search(dnBuffer.toString(), attrSearch, searchCtls);

                                this.isauth = true;
                                this.myPrincipal.FullName = first_name + " " + last_name;
                                log.debug(
                                        "SimpleLdapSecurityContext: User {} ({}) is authenticated",
                                        this.myPrincipal.UID,
                                        this.myPrincipal.FullName);

                                // Since LDAP is case-insensitive with respect to uid, force
                                // user name to lower case for use by the portal
                                this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase();
                            } // while (results != null && results.hasMore())
                        } else {
                            log.error(
                                    "SimpleLdapSecurityContext: No such user: {}",
                                    this.myPrincipal.UID);
                        }
                    } catch (AuthenticationException ae) {
                        log.info(
                                "SimpleLdapSecurityContext: Password invalid for user: "
                                        + this.myPrincipal.UID);
                    } catch (Exception e) {
                        log.error(
                                "SimpleLdapSecurityContext: LDAP Error with user: "
                                        + this.myPrincipal.UID
                                        + "; ",
                                e);
                        throw new PortalSecurityException(
                                "SimpleLdapSecurityContext: LDAP Error"
                                        + e
                                        + " with user: "
                                        + this.myPrincipal.UID);
                    } finally {
                        ldapConn.releaseConnection(conn);
                    }
                } else {
                    log.error("LDAP Server Connection unavailable");
                }
            } catch (final NamingException ne) {
                log.error("Error getting connection to LDAP server.", ne);
            }
        } else {
            // If the principal and/or credential are missing, the context authentication
            // simply fails. It should not be construed that this is an error. It happens for guest
            // access.
            log.info("Principal or OpaqueCredentials not initialized prior to authenticate");
        }
        // Ok...we are now ready to authenticate all of our subcontexts.
        super.authenticate();
        return;
    }
289819
@FFDCIgnore(InvalidNameException.class)
    public static String getCNFromDN(String dn) {
        String cn = null;
        try {
            LdapName ldapDN = new LdapName(dn);
            for (int i = ldapDN.size() - 1; i > -1; i--) {
                //for (int i = 0; i < ldapDN.size(); i++) {
                if (ldapDN.get(i).toLowerCase().startsWith("cn=")) {
                    cn = ldapDN.get(i).substring(START_CN_OFFSET);
                    break;
                }
            }
        } catch (InvalidNameException e) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Unable to getCNFromDN: " + e.getMessage(), e);
            }
        }
        return cn;
    }
1340784
public static Credentials getUserByEmail(DAO serverDao, String email) throws DAO.DAOException {
        Query query = new QueryBuilder()
                .select()
                .from(Credentials.class)
                .where(Credentials.EMAIL_KEY, OPERAND.EQ,email)
                .build();

        TransientObject to = (TransientObject) ObjectUtils.get1stOrNull(serverDao.query(query));
        if(to==null){
            return null;
        } else {
            return to(Credentials.class, to);
        }
    }
244508
public void open() throws SQLException, ClassNotFoundException {
        logger.info("Using database driver: " + jdbcDriver);
        Class.forName(jdbcDriver);
        logger.info("Using database.url: " + jdbcURL);
        // connect login/pass
        con = DriverManager.getConnection(jdbcURL, user, password);
        // Exception will be thrown if something went wrong
        connected = true;
    }
135027
@Override
    public void connectionOpen() {
        lock.lock();
        try {
            connectionOpen = true;

            StoredPaymentChannelClientStates channels = (StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID);
            if (channels != null)
                storedChannel = channels.getUsableChannelForServerID(serverId);

            step = InitStep.WAITING_FOR_VERSION_NEGOTIATION;

            Protos.ClientVersion.Builder versionNegotiationBuilder = Protos.ClientVersion.newBuilder()
                    .setMajor(versionSelector.getRequestedMajorVersion())
                    .setMinor(versionSelector.getRequestedMinorVersion())
                    .setTimeWindowSecs(timeWindow);

            if (storedChannel != null) {
                versionNegotiationBuilder.setPreviousChannelContractHash(ByteString.copyFrom(storedChannel.contract.getTxId().getBytes()));
                log.info("Begun version handshake, attempting to reopen channel with contract hash {}", storedChannel.contract.getTxId());
            } else
                log.info("Begun version handshake creating new channel");

            conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder()
                    .setType(Protos.TwoWayChannelMessage.MessageType.CLIENT_VERSION)
                    .setClientVersion(versionNegotiationBuilder)
                    .build());
        } finally {
            lock.unlock();
        }
    }
1133871
@Override
	protected void openConnectionInternal() throws ConnectionException, AuthenticationException {
		if (checkoutDirectory == null) {
			checkoutDirectory = createCheckoutDirectory();
		}

		if (checkoutDirectory.exists() && safeCheckout) {
			removeCheckoutDirectory();
		}

		checkoutDirectory.mkdirs();
	}
674012
private ContentsDao getContentsDao() throws SQLException {
		if (contentsDao == null) {
			contentsDao = DaoManager
					.createDao(connectionSource, Contents.class);
		}
		return contentsDao;
	}
768298
def bind
            conn = Net::LDAP.new :host => @config[:server],
                                 :port => @config[:port],
                                 :base => @config[:base]
            if @config[:encryption]
               conn.encryption @config[:encryption]
            end
            
            raise "Anonymous Bind is disabled" if @config[:password] == "" && !(@config[:anonymous_bind])
            
            conn.auth "#{@config[:username]}@#{@config[:domain]}", @config[:password]
            
            begin
                Timeout::timeout(10){
                    if conn.bind
                        return conn
                    else
                        raise 'Query User Rejected'
                    end
                }
            rescue Timeout::Error
                raise 'Unable to connect to LDAP Server'
            rescue Errno::ECONNRESET
              if @config[:allow_fallback]
                @config[:port] = @config[:allow_fallback]
                @config[:encryption] = false
                return Adauth::Connection.new(@config).bind
              end
            end
        end
1316055
public void authenticate(String username, String password) {
        ldapTemplate.authenticate(query().where("objectClass").is("simpleSecurityObject").and("cn").is(username), password);
        LOGGER.info("Successfully authenticated " + username);
    }
569403
public Principal authenicate(String uid, char[] password)
   throws  SecurityException
   {

      String rootDN = Config.getProperty(ROOT_DN_PROP);
      
      int timeout = Config.getPropertyInteger(TIMEOUT_SECS_PROP).intValue();
      Debugger.println(LDAP.class,"timeout="+timeout);
      
      String uidAttributeName = Config.getProperty(UID_ATTRIB_NM_PROP);
      String groupAttributeName = Config.getProperty(GROUP_ATTRIB_NM_PROP,"");
      String memberOfAttributeName = Config.getProperty(MEMBEROF_ATTRIB_NM_PROP,"");
      
      return authenicate(uid,  password,rootDN,uidAttributeName,memberOfAttributeName,groupAttributeName,timeout);
   }
1345421
def convert_user_to_ldap(self, ID, DN):
        """"""
        # http://teampasswordmanager.com/docs/api-users/#convert_to_ldap
        data = {'login_dn': DN}
        log.info('Convert User %s to LDAP DN %s' % (ID, DN))
        self.put('users/%s/convert_to_ldap.json' % ID, data)