Tries to login with supported auth methods.

        Some servers advertise authentication methods they don't really
        support, so if authentication fails, we continue until we've tried
        all methods.
331923
async def login(
        self, username: str, password: str, timeout: DefaultNumType = _default
    ) -> SMTPResponse:
        
        await self._ehlo_or_helo_if_needed()

        if not self.supports_extension("auth"):
            raise SMTPException("SMTP AUTH extension not supported by server.")

        response = None  # type: Optional[SMTPResponse]
        exception = None  # type: Optional[SMTPAuthenticationError]
        for auth_name in self.supported_auth_methods:
            method_name = "auth_{}".format(auth_name.replace("-", ""))
            try:
                auth_method = getattr(self, method_name)
            except AttributeError:
                raise RuntimeError(
                    "Missing handler for auth method {}".format(auth_name)
                )
            try:
                response = await auth_method(username, password, timeout=timeout)
            except SMTPAuthenticationError as exc:
                exception = exc
            else:
                # No exception means we're good
                break

        if response is None:
            raise exception or SMTPException("No suitable authentication method found.")

        return response
463049
def authenticated(function):
    """"""
    def wrapped(*args):
        """Wrap function."""
        try:
            return function(*args)
        except USPSError:
            _LOGGER.info("attempted to access page before login")
            _login(args[0])
            return function(*args)
    return wrapped
1228611
@Override
    void doLogin(String authUrl, final Callback<TokenInfo, Throwable> callback) {
        if (window != null && window.isOpen()) {
            callback.onFailure(new IllegalStateException("Authentication in progress"));
        } else {
            window = openWindow(authUrl, height, width);
            if (window == null) {
                callback.onFailure(new RuntimeException(
                        "The authentication popup window appears to have been blocked"));
            }
            // Workaround to check if the user has closed the auth window,
            // since neither the onclose and onunload events work the expected way in this scenario
            window.setFinished(false);
            new Timer() {
                @Override
                public void run() {
                    if (window.hasFinished())
                        cancel();
                    if (!window.isOpen()) {
                        window.setFinished(true);
                        callback.onFailure(new RuntimeException("User has closed the authentication window."));
                        cancel();
                    }
                }
            }.scheduleRepeating(300);
        }
    }
188330
def check_basic_auth(self, username, password):
        
        valid = self.users.check_password(
            username, password
        )
        if not valid:
            log.warning('Invalid login from %s', username)
            valid = False
        return (
            valid,
            username
        )
881096
function authenticateLiveConnections(self, args, cb) {
    // Get the current viable connections
    var connections = self.allConnections();
    // Allow nothing else to use the connections while we authenticate them
    self.availableConnections = [];
    self.inUseConnections = [];
    self.connectingConnections = [];

    var connectionsCount = connections.length;
    var error = null;
    // No connections available, return
    if (connectionsCount === 0) {
      self.authenticating = false;
      return callback(null);
    }

    // Authenticate the connections
    for (var i = 0; i < connections.length; i++) {
      authenticate(self, args, connections[i], function(err, result) {
        connectionsCount = connectionsCount - 1;

        // Store the error
        if (err) error = err;

        // Processed all connections
        if (connectionsCount === 0) {
          // Auth finished
          self.authenticating = false;
          // Add the connections back to available connections
          self.availableConnections = self.availableConnections.concat(connections);
          // We had an error, return it
          if (error) {
            // Log the error
            if (self.logger.isError()) {
              self.logger.error(
                f(
                  '[%s] failed to authenticate against server %s:%s',
                  self.id,
                  self.options.host,
                  self.options.port
                )
              );
            }

            return cb(error, result);
          }
          cb(null, result);
        }
      });
    }
  }
470706
def authenticate(cls, request, route, server_config):
        
        if not server_config.getboolean("auth", False):
            return

        user = server_config.get("user", "").strip()
        password = server_config.get("password", "").strip()

        if len(user) == 0:
            return

        if "AUTHORIZATION" in request.headers:
            if request.headers["AUTHORIZATION"] == aiohttp.helpers.BasicAuth(user, password, "utf-8").encode():
                return

        log.error("Invalid auth. Username should %s", user)

        response = Response(request=request, route=route)
        response.set_status(401)
        response.headers["WWW-Authenticate"] = 'Basic realm="GNS3 server"'
        # Force close the keep alive. Work around a Qt issue where Qt timeout instead of handling the 401
        # this happen only for the first query send by the client.
        response.force_close()
        return response
117691
def authenticate(self, password):
        
        user = None

        try:
            self._authenticate_user_dn(password)
            self._check_requirements()
            self._get_or_create_user()

            user = self._user
        except self.AuthenticationFailed as e:
            logger.debug(u"Authentication failed for %s: %s" % (self._username, e))
        except ldap.LDAPError as e:
            results = ldap_error.send(self.backend.__class__,
                                      context='authenticate', exception=e)
            if len(results) == 0:
                logger.warning(u"Caught LDAPError while authenticating %s: %s",
                               self._username, pprint.pformat(e))
        except Exception:
            logger.exception(u"Caught Exception while authenticating %s",
                             self._username)
            raise

        return user
60747
def do_authentication(environ, start_response, authn_context, key,
                      redirect_uri):
    
    logger.debug("Do authentication")
    auth_info = AUTHN_BROKER.pick(authn_context)

    if len(auth_info):
        method, reference = auth_info[0]
        logger.debug("Authn chosen: %s (ref=%s)", method, reference)
        return method(environ, start_response, reference, key, redirect_uri)
    else:
        resp = Unauthorized("No usable authentication method")
        return resp(environ, start_response)
320775
def authenticate(username = nil, password = nil, options = {}, &block)
      if username.is_a?(Hash) or password.is_a?(Hash)
        options = username.is_a?(Hash) ? username : password
      end
      options["username"] = username if username and !username.is_a?Hash
      options["password"] = password if password and !password.is_a?Hash

      options = set_options(options, &block)

      #TODO: Raise error if doesn't find username and password key in options
      @response = post('auth', options)
      if @response.has_key?("success") and @response['success']
        add_header("X-Auth-Token", @response['token'])
      end
      @response
    end
1029455
def authenticate!(options = {}, connection = self.connection)
      creds = options.to_json
      connection.post('/auth', {}, :body => creds)
      @creds = creds
      true
    rescue Docker::Error::ServerError, Docker::Error::UnauthorizedError
      raise Docker::Error::AuthenticationError
    end
415768
def _authenticate(self):
        
        for authenticator in self.authenticators:
            try:
                user_auth_tuple = authenticator.authenticate(self)
            except exceptions.APIException:
                self._not_authenticated()
                raise

            if user_auth_tuple is not None:
                self._authenticator = authenticator
                self.user, self.auth = user_auth_tuple
                return

        self._not_authenticated()
84632
function applyAuth(authContexts, server, callback) {
    if (authContexts.length === 0) return callback();
    // Get the first auth context
    var authContext = authContexts.shift();
    // Copy the params
    var customAuthContext = authContext.slice(0);
    // Push our callback handler
    customAuthContext.push(function(/* err */) {
      applyAuth(authContexts, server, callback);
    });

    // Attempt authentication
    server.auth.apply(server, customAuthContext);
  }
245414
def authenticate(self, user, password):
        """"""
        assert user['password_hash'] == '_'.join((password, 'hash'))
        self.logger.debug('User %s has been successfully authenticated',
                          user['uid'])
1356184
def authenticate(self, bound_route, actual_params) -> bool:
        
        if self.__auth_service is not None:
            auth_route = "{0}_{1}{2}".format(self.__method, self.__route, bound_route)
            auth_data = self.__auth_service.authenticate(self.__request, auth_route, actual_params)
            if auth_data is True:
                self.app.auth_data = self.__auth_service.auth_data
            else:
                return False

        return True
384029
def auth_required(*auth_methods):
    
    login_mechanisms = {
        'token': lambda: _check_token(),
        'basic': lambda: _check_http_auth(),
        'session': lambda: current_user.is_authenticated
    }

    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            h = {}
            mechanisms = [(method, login_mechanisms.get(method))
                          for method in auth_methods]
            for method, mechanism in mechanisms:
                if mechanism and mechanism():
                    return fn(*args, **kwargs)
                elif method == 'basic':
                    r = _security.default_http_auth_realm
                    h['WWW-Authenticate'] = 'Basic realm="%s"' % r
            if _security._unauthorized_callback:
                return _security._unauthorized_callback()
            else:
                return _get_unauthorized_response(headers=h)
        return decorated_view
    return wrapper
371070
def login_from_basic_auth
      authenticate_with_http_basic do |accountname, password|
        account = Account.authenticate(accountname, password, true)
        self.auth_type_used = :basic if not account.nil?
        self.current_account = account
        account
      end
    end
846925
def authenticate(self, dn='', password=''):
        
        try:
            self.connection.simple_bind_s(dn, password)
        except tuple(self.failed_authentication_exceptions):
            return False
        else:
            return True