Handles LDAP auth (but not LDAP_HTTP) which uses a HTML form.
183814
private Optional<String> tryGerritHttpFormAuth(HttpClientBuilder client, HttpContext httpContext) throws IOException, HttpStatusException {
        if (!authData.isLoginAndPasswordAvailable()) {
            return Optional.absent();
        }
        String loginUrl = authData.getHost() + "/login/";
        HttpPost method = new HttpPost(loginUrl);
        List<BasicNameValuePair> parameters = Lists.newArrayList(
            new BasicNameValuePair("username", authData.getLogin()),
            new BasicNameValuePair("password", authData.getPassword())
        );
        method.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8));
        HttpResponse loginResponse = httpRequestExecutor.execute(client, method, httpContext);
        return extractGerritAuth(loginResponse);
    }
823661
public function formAction($name = null)
    {
        $tmpServer = $this->ldap->get($name);
        $tmpPassword = (isset($tmpServer['password'])) ? $tmpServer['password'] : null;
        $form = $this->formFactory->create(LdapType::class, $tmpServer);
        if ('POST' === $this->request->getMethod() && $form->handleRequest($this->request) && $form->isValid()) {
            $data = $form->getData();

            if ($this->ldap->exists($name, $data)) {
                $form->addError(new FormError($this->translator->trans('ldap_already_exists', [], 'ldap')));
            } else {
                $user = isset($data['user']) ? $data['user'] : null;
                $data['password'] = (isset($data['password']) && null !== $data['password']) ?
                    $data['password'] :
                    $tmpPassword;
                $password = $data['password'];
                if (!$this->ldap->connect($data, $user, $password)) {
                    $form->addError(new FormError($this->translator->trans('ldap_cant_connect', [], 'ldap')));
                } else {
                    $this->ldap->saveConfig($data);
                    $this->ldap->deleteIfReplace($name, $data);

                    return new Response('true');
                }
            }
        }

        return ['form' => $form->createView(), 'name' => $name];
    }
325983
def main():
    """"""
    server_configs = ServerConfig.get('sat1'), ServerConfig.get('sat2')
    for server_config in server_configs:
        org = Organization(server_config).search(
            query={'search': 'name="Default_Organization"'}
        )[0]
        # The LDAP authentication source with an ID of 1 is internal. It is
        # nearly guaranteed to exist and be functioning.
        user = User(
            server_config,
            auth_source=1,  # or: AuthSourceLDAP(server_config, id=1),
            login='Alice',
            mail='alice@example.com',
            organization=[org],
            password='hackme',
        ).create()
        pprint(user.get_values())
324814
def simple_password(request):
    
    if request.method == "POST":
        form = PasswordForm(data=request.POST)
        if form.is_valid():
            # TODO: set session with better param
            request.session["simple_auth"] = True
            return redirect(form.cleaned_data["url"] or "/")
    else:
        form = PasswordForm()
    return render(request, "simple_auth/password_form.html",
                  {"form": form})
1006387
def _authenticate(self, request):
        

        def ensure_user_obj():
            """ Make sure that request object has user property.

            If `request.user` is not present or is `None`, it is
            created and initialized with `AnonymousUser`.
            """

            try:
                if request.user:
                    return
            except AttributeError:
                pass

            request.user = AnonymousUser()

        def anonymous_access(exc_obj):
            """ Determine what to do with unauthenticated requests.

            If the request has already been authenticated, does
            nothing.

            :param exc_obj: exception object to be thrown if anonymous
            access is not permitted.
            """

            if request.user and request.user.is_authenticated():
                # request is already authenticated
                pass
            elif self.allow_anonymous:
                request.user = AnonymousUser()
            else:
                raise exc_obj

        # first, make sure that the request carries `user` attribute
        ensure_user_obj()
        if self.authentication:
            # authentication handler is configured
            try:
                self.authentication.authenticate(request)
            except errors.Unauthorized, exc:
                # http request doesn't carry any authentication information
                anonymous_access(exc)
        else:
            # no authentication configured
            anonymous_access(errors.Forbidden())
1217873
def _get_anon_bind(self):
        
        r = self._search(
            'cn=config',
            '(objectClass=*)',
            ['nsslapd-allow-anonymous-access'],
            scope=ldap.SCOPE_BASE
        )
        dn, attrs = r[0]
        state = attrs.get('nsslapd-allow-anonymous-access')[0].decode('utf-8', 'ignore')
        if state in ['on', 'off', 'rootdse']:
            r = state
        else:
            r = None
        self._anon_bind = r
28217
def _handle_login(self, event):
        """"""

        # TODO: Refactor to simplify

        self.log("Auth request for ", event.username, 'client:',
                 event.clientuuid)

        # TODO: Define the requirements for secure passwords etc.
        # They're also required in the Enrol module..!

        if (len(event.username) < 1) or (len(event.password) < 5):
            self.log("Illegal username or password received, login cancelled", lvl=warn)
            self._fail(event, 'Password or username too short')
            return

        client_config = None

        try:
            user_account = objectmodels['user'].find_one({
                'name': event.username
            })
            # self.log("Account: %s" % user_account._fields, lvl=debug)
            if user_account is None:
                raise AuthenticationError
        except Exception as e:
            self.log("No userobject due to error: ", e, type(e),
                     lvl=error)
            self._fail(event)
            return

        self.log("User found.", lvl=debug)

        if user_account.active is False:
            self.log("Account deactivated.")
            self._fail(event, 'Account deactivated.')
            return

        if not std_hash(event.password, self.salt) == user_account.passhash:
            self.log("Password was wrong!", lvl=warn)
            self._fail(event)
            return

        self.log("Passhash matches, checking client and profile.",
                 lvl=debug)

        requested_client_uuid = event.requestedclientuuid
        if requested_client_uuid is not None:
            client_config = objectmodels['client'].find_one({
                'uuid': requested_client_uuid
            })

        if client_config:
            self.log("Checking client configuration permissions",
                     lvl=debug)
            # TODO: Shareable client configurations?
            if client_config.owner != user_account.uuid:
                client_config = None
                self.log("Unauthorized client configuration "
                         "requested",
                         lvl=warn)
        else:
            self.log("Unknown client configuration requested: ",
                     requested_client_uuid, event.__dict__,
                     lvl=warn)

        if not client_config:
            self.log("Creating new default client configuration")
            # Either no configuration was found or not requested
            # -> Create a new client configuration
            uuid = event.clientuuid if event.clientuuid is not None else str(uuid4())

            client_config = objectmodels['client']({'uuid': uuid})

            client_config.name = std_human_uid(kind='place')

            client_config.description = "New client configuration from " + user_account.name
            client_config.owner = user_account.uuid

            # TODO: Get client configuration storage done right, this one is too simple
            client_config.save()

        user_profile = self._get_profile(user_account)

        self._login(event, user_account, user_profile, client_config)
        self.log("Done with Login request", lvl=debug)
1064930
def _ensure_html_response(url, session):
    # type: (str, PipSession) -> None
    
    scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url)
    if scheme not in {'http', 'https'}:
        raise _NotHTTP()

    resp = session.head(url, allow_redirects=True)
    resp.raise_for_status()

    _ensure_html_header(resp)
814127
def process_auth(self):
        
        r = self._reader
        w = self._writer
        pdu_size = r.get_smallint()
        if not self.authentication:
            raise tds_base.Error('Got unexpected token')
        packet = self.authentication.handle_next(readall(r, pdu_size))
        if packet:
            w.write(packet)
            w.flush()
776642
private void doFormLogin(FormAuthInfo authInfo) {
        logger.info("FORM authentication for: {}", authInfo.getLoginTarget());
        String fullUri =
                authInfo.getProtocol() + "://" + authInfo.getHost() + ":" + authInfo.getPort() +
                        authInfo.getLoginTarget();
        HttpPost httpPost = new HttpPost(fullUri);
        List<NameValuePair> formParams = new ArrayList<>();
        formParams.add(
                new BasicNameValuePair(authInfo.getUsernameFormStr(), authInfo.getUsername()));
        formParams.add(
                new BasicNameValuePair(authInfo.getPasswordFormStr(), authInfo.getPassword()));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8);
        httpPost.setEntity(entity);

        try {
            httpClient.execute(httpPost);
            logger.debug("Successfully request to login in with user: {} to: {}", authInfo.getUsername(),
                    authInfo.getHost());
        } catch (ClientProtocolException e) {
            logger.error("While trying to login to: {} - Client protocol not supported",
                    authInfo.getHost(), e);
        } catch (IOException e) {
            logger.error("While trying to login to: {} - Error making request", authInfo.getHost(),
                    e);
        }
    }
38065
public static function fromDefaults() {
		$handler = new HandlerLDAP(
			config('ldap.host'),
			config('ldap.basedn'),
			config('ldap.dn'),
			config('ldap.password'),
			config('ldap.search_user_id'),
			config('ldap.search_username'),
			config('ldap.search_user_mail'),
			config('ldap.search_user_mail_array')
		);
		$handler->setVersion(config('ldap.version'));
		$handler->setOverlayDN(config('ldap.overlay_dn'));

		// configuration for add operations
		$handler->setAddBaseDN(config('ldap.add_base_dn'));
		$handler->setAddDN(config('ldap.add_dn'));
		$handler->setAddPassword(config('ldap.add_pw'));

		// configuration for modify operations
		$handler->setModifyMethod(config('ldap.modify_method'));
		$handler->setModifyBaseDN(config('ldap.modify_base_dn'));
		$handler->setModifyDN(config('ldap.modify_dn'));
		$handler->setModifyPassword(config('ldap.modify_pw'));

		return $handler;
	}
760710
private AuthenticationResult handleFormLogin(HttpServletRequest req, HttpServletResponse res, WebRequest webRequest) {
        AuthenticationResult authResult = null;
        authResult = ssoAuthenticator.authenticate(webRequest);

        if (authResult != null) {
            authResult.setAuditCredType(AuditEvent.CRED_TYPE_FORM);
        }

        if (authResult != null && authResult.getStatus() != AuthResult.FAILURE) {
            postParameterHelper.restore(req, res);
            return authResult;
        }

        try {
            authResult = providerAuthenticatorProxy.authenticate(req, res, null);
        } catch (Exception e) {
            return new AuthenticationResult(AuthResult.FAILURE, e.getLocalizedMessage());
        }

        if (authResult.getStatus() == AuthResult.CONTINUE) {
            authResult = null;
            if (webRequest.isFormLoginRedirectEnabled()) {
                authResult = handleRedirect(req, res, webRequest);
                if (authResult != null) {
                    authResult.setAuditCredType(AuditEvent.CRED_TYPE_FORM);
                    authResult.setAuditOutcome(AuditEvent.OUTCOME_REDIRECT);
                }

            }
        }
        return authResult;
    }
1024391
def _handle_401(self, data):
        """"""

        ex = ConnectionError(
            "Can't login to a protected room without a proper password", data
        )
        self.conn.reraise(ex)
246291
def isAuth(self):
        '''
        
        '''
        if isinstance(self.__conn, ldap.ldapobject.LDAPObject) or self.__conn:
            return True
        return False
533886
function bind($userdn = NULL, $pass = NULL, $anon_bind = FALSE) {

    // Ensure that we have an active server connection.
    if (!$this->connection) {
      watchdog('ldap', "LDAP bind failure for user %user. Not connected to LDAP server.", array('%user' => $userdn));
      return LDAP_CONNECT_ERROR;
    }

    if ($anon_bind !== FALSE && $userdn === NULL && $pass === NULL && $this->bind_method == LDAP_SERVERS_BIND_METHOD_ANON) {
      $anon_bind = TRUE;
    }
    if ($anon_bind === TRUE) {
      if (@!ldap_bind($this->connection)) {
        if ($this->detailedWatchdogLog) {
          watchdog('ldap', "LDAP anonymous bind error. Error %errno: %error", array('%errno' => ldap_errno($this->connection), '%error' => ldap_error($this->connection)));
        }
        return ldap_errno($this->connection);
      }
    }
    else {
      $userdn = ($userdn != NULL) ? $userdn : $this->binddn;
      $pass = ($pass != NULL) ? $pass : $this->bindpw;

      if ($this->followrefs) {
        $rebHandler = new LdapServersRebindHandler($userdn, $pass);
        ldap_set_rebind_proc($this->connection, array($rebHandler, 'rebind_callback'));
      }

      if (drupal_strlen($pass) == 0 || drupal_strlen($userdn) == 0) {
        watchdog('ldap', "LDAP bind failure for user userdn=%userdn, pass=%pass.", array('%userdn' => $userdn, '%pass' => $pass));
        return LDAP_LOCAL_ERROR;
      }
      if (@!ldap_bind($this->connection, $userdn, $pass)) {
        if ($this->detailedWatchdogLog) {
          watchdog('ldap', "LDAP bind failure for user %user. Error %errno: %error", array('%user' => $userdn, '%errno' => ldap_errno($this->connection), '%error' => ldap_error($this->connection)));
        }
        return ldap_errno($this->connection);
      }
    }

    return LDAP_SUCCESS;
  }
903460
protected function initializeLdapAuthenticationHandler() {
        $ldapSettings = $this->_passwordAuthenticationPlatformSettings;
        $ldapAuthenticationHandler = new MultiotpWrapper();
        
        $ldapAuthenticationHandler->SetLdapServerPassword($this->getCurrentPassword());
        $ldapAuthenticationHandler->SetLdapBindDn($this->getCurrentUsername());
        $ldapAuthenticationHandler->SetLdapAccountSuffix($ldapSettings['ldap_account_suffix']);
        $ldapAuthenticationHandler->SetLdapBaseDn($ldapSettings['base_dn']);
        $ldapAuthenticationHandler->SetLdapCnIdentifier($ldapSettings['cn_identifier']);
        $ldapAuthenticationHandler->SetLdapDomainControllers($ldapSettings['domain_controllers']);
        $ldapAuthenticationHandler->SetLdapGroupAttribute($ldapSettings['group_attribute']);
        $ldapAuthenticationHandler->SetLdapGroupCnIdentifier($ldapSettings['group_cn_identifier']);
        $ldapAuthenticationHandler->SetLdapServerType($ldapSettings['ldap_server_type']);
        $ldapAuthenticationHandler->SetLdapNetworkTimeout($ldapSettings['network_timeout']);
        $ldapAuthenticationHandler->SetLdapPort($ldapSettings['port']);
        $ldapAuthenticationHandler->SetLdapRecursiveGroups($ldapSettings['recursive_groups']);
        $ldapAuthenticationHandler->SetLdapTimeLimit($ldapSettings['time_limit']);
        $ldapAuthenticationHandler->SetLdapSsl($ldapSettings['use_ssl']);
        $ldapAuthenticationHandler->SetLdapCacheOn($ldapSettings['cache_support']);
        $ldapAuthenticationHandler->SetLdapCacheFolder($ldapSettings['cache_folder']);
        $ldapAuthenticationHandler->SetLdapExpiredPasswordValid($ldapSettings['expired_password_valid']);
        
        $this->ldapAuthenticationHandler = $ldapAuthenticationHandler;
    }
687790
def validate_ldap(self):
        ''
        ldap_mgr = current_app.ldap_login_manager
        username = self.username.data
        password = self.password.data
        try:
            userdata = ldap_mgr.ldap_login(username, password)
        except ldap.INVALID_CREDENTIALS:
            flash("Invalid LDAP credentials", 'danger')
            return False
        except ldap.LDAPError as err:
            if isinstance(err.message, dict):
                message = err.message.get('desc', str(err))
            else:
                message = str(err.message)
            flash(message, 'danger')
            return False

        if userdata is None:
            flash("Invalid LDAP credentials", 'danger')
            return False

        self.user = ldap_mgr._save_user(username, userdata)
        return True