Send an authentication command for this database.
        mostly stolen from pymongo
352352
def authenticate(self, name, password, mechanism="DEFAULT"):
        
        if not isinstance(name, (bytes, unicode)):
            raise TypeError("TxMongo: name must be an instance of basestring.")
        if not isinstance(password, (bytes, unicode)):
            raise TypeError("TxMongo: password must be an instance of basestring.")

        """
        Authenticating
        """
        return self.connection.authenticate(self, name, password, mechanism)
635852
def connect(self, host=None, port=None, connect=False, **kwargs):
        
        try:
            self.__connection = MongoClient(host=host, port=port, connect=connect, **kwargs)
        except (AutoReconnect, ConnectionFailure, ServerSelectionTimeoutError):
            raise DatabaseIsDownError("No mongod process is running.")
756931
function db(self, callback) {

  if (self.db) {
    return callback(undefined, self.code ? self.db.collection(self.code) : self.db);
  }

  mongo.connect(self.domain, self.user, self.pass, function (err, db) {
    if (err) {
      log.error(err);
    }

    self.db = db;
    callback(err, self.code ? db.collection(self.code) : db);
  });
}
557311
def _set_client(self):
        """"""
        if self._client is None:
            if mongo_proxy:
                self._client = mongo_proxy.MongoProxy(
                    pymongo.MongoClient(self.connection_string),
                    logger=LOG)
            else:
                LOG.warning("MongoDBProxy not imported. AutoReconnect "
                            "is not enabled.")
                self._client = mongo_proxy.MongoProxy(
                    pymongo.MongoClient(self.connection_string),
                    logger=LOG)
            LOG.debug("Created new connection to MongoDB: %s",
                      self.safe_connection_string)
1340178
def user_remove(name, user=None, password=None, host=None, port=None,
                database='admin', authdb=None):
    '''
    
    '''
    conn = _connect(user, password, host, port)
    if not conn:
        return 'Failed to connect to mongo database'

    try:
        log.info('Removing user %s', name)
        mdb = pymongo.database.Database(conn, database)
        mdb.remove_user(name)
    except pymongo.errors.PyMongoError as err:
        log.error('Creating database %s failed with error: %s', name, err)
        return six.text_type(err)

    return True
822838
def connect(self):
        
        mongodb_args = {
            'host': self.host,
            'port': self.port,
            'username': self._username,
            'password': self._password,
            'authSource': self._auth_source,
            'serverSelectionTimeoutMS': self._connect_timeout
        }

        if self._auth_mechanism is not None:
            mongodb_args['authMechanism'] = self._auth_mechanism

        self._client = MongoClient(**mongodb_args)

        if self._handle_reconnect:
            self._client = MongoClientProxy(self._client)
692433
def _get_connection(self, ssl):
        """"""

        # Use SSL/TLS if requested and available.
        connect_string = self.connect_string
        if ssl and self.ssl_connect_string:
            connect_string = self.ssl_connect_string

        return pymongo.MongoClient(connect_string)
745162
def patch_pymongo(config):
    

    # Nothing to change!
    if not config["print_mongodb"] and not config["trace_io"]:
        return

    from termcolor import cprint

    # Print because we are very early and log() may not be ready yet.
    cprint("Monkey-patching MongoDB methods...", "white")

    def gen_monkey_patch(base_object, method):
        base_method = getattr(base_object, method)

        def mrq_monkey_patched(self, *args, **kwargs):

            if config["trace_io"]:
                comment = "mrq"

                worker = get_current_worker()
                job = get_current_job()
                if job:
                    job.set_current_io({
                        "type": "mongodb.%s" % method,
                        "data": {
                            "collection": self.full_name
                        }
                        # Perf issue? All MongoDB data will get jsonified!
                        # "data": json.dumps(args)[0:300]
                    })
                    comment = {"job": job.id}
                elif worker:
                    comment = {"worker": worker.id}

                # Tag potentially expensive queries with their job id for easier debugging
                if method in ["find", "find_and_modify", "count", "update_many", "update", "delete_many"]:
                    if len(args) > 0 and isinstance(args[0], dict) and "$comment" not in args[0]:
                        query = copy.copy(args[0])
                        query["$comment"] = comment
                        args = (query, ) + args[1:]

            if config["print_mongodb"]:
                if self.full_name in config.get("print_mongodb_hidden_collections", []):
                    cprint("[MONGO] %s.%s%s %s" % (
                        self.full_name, method, "-hidden-", kwargs
                    ), "magenta")
                else:
                    cprint("[MONGO] %s.%s%s %s" % (
                        self.full_name, method, args, kwargs
                    ), "magenta")

            if config.get("mongodb_pre_hook"):
                config.get("mongodb_pre_hook")({
                    "collection": self.full_name,
                    "method": method,
                    "args": args,
                    "kwargs": kwargs,
                    "client": self.database.client,
                    "job": job
                })

            start_time = time.time()
            ret = False
            try:
                ret = base_method(self, *args, **kwargs)
            finally:
                stop_time = time.time()

                job = None

                if config["trace_io"]:
                    job = get_current_job()
                    if job:
                        job.set_current_io(None)

                if config.get("mongodb_post_hook"):
                    config.get("mongodb_post_hook")({
                        "collection": self.full_name,
                        "method": method,
                        "args": args,
                        "kwargs": kwargs,
                        "client": self.database.client,
                        "job": job,
                        "result": ret,
                        "time": stop_time - start_time
                    })

            return ret

        # Needed to avoid breaking mongokit
        mrq_monkey_patched.__doc__ = method.__doc__

        return mrq_monkey_patched

    from pymongo.collection import Collection
    pymongo_method_whitelist = (
        "bulk_write",
        "find", "find_one_and_delete", "find_one_and_replace", "find_one_and_update",
        "update", "update_one", "update_many",
        "drop",
        "count",
        "save",
        "insert", "insert_one", "insert_many",
        "replace_one",
        "remove", "delete_one", "delete_many",
        "find_and_modify",
        "parallel_scan",
        "options",
        "aggregate",
        "group", "distinct",
        "rename",
        "map_reduce", "inline_map_reduce",
        "create_indexes", "create_index", "ensure_index", "drop_index", "reindex", "list_indexes"
    )
    for method in pymongo_method_whitelist:
        if hasattr(Collection, method) and getattr(Collection, method).__name__ != "mrq_monkey_patched":
            setattr(Collection, method, gen_monkey_patch(Collection, method))
172174
def authTryNextMethod(self):
        
        if not self.authOrder:
            raise DBusAuthenticationFailed()
        
        self.authMech  = self.authOrder.pop()
            
        if self.authMech == 'DBUS_COOKIE_SHA1':
            self.sendAuthMessage('AUTH ' + self.authMech + ' ' +
                                 hexlify(getpass.getuser()))
        elif self.authMech == 'ANONYMOUS':
            self.sendAuthMessage('AUTH ' + self.authMech + ' ' +
                                 hexlify("txdbus"))
        else:
            self.sendAuthMessage('AUTH ' + self.authMech)
510582
def insert(objects, collection, user=None, password=None,
           host=None, port=None, database='admin', authdb=None):
    '''
    

    '''
    conn = _connect(user, password, host, port, database, authdb)
    if not conn:
        return "Failed to connect to mongo database"

    try:
        objects = _to_dict(objects)
    except Exception as err:
        return err

    try:
        log.info("Inserting %r into %s.%s", objects, database, collection)
        mdb = pymongo.database.Database(conn, database)
        col = getattr(mdb, collection)
        ids = col.insert(objects)
        return ids
    except pymongo.errors.PyMongoError as err:
        log.error("Inserting objects %r failed with error %s", objects, err)
        return err
415945
def database(key='default', slave=False):
    
    if slave:
        key += '.slave'
        return choice(__db[key])
    return __db.get(key)
7655
def authenticate(self, request, username=None, password=None, realm=None):
        
        if isinstance(username, basestring):
            username = username.encode('utf-8')

        if isinstance(password, basestring):
            password = password.encode('utf-8')

        server = self.get_server(realm)

        if not server:
            return None

        result = self._radius_auth(server, username, password)

        if result:
            full_username = self.construct_full_username(username, realm)
            return self.get_django_user(full_username, password)

        return None
1210639
def connect_command(self):
        '''
        

        '''
        options = {
            "verbose": self.options["verbose"],
            "pedantic": self.options["pedantic"],
            "lang": __lang__,
            "version": __version__,
            "protocol": PROTOCOL
        }
        if "auth_required" in self._server_info:
            if self._server_info["auth_required"] == True:
                # In case there is no password, then consider handle
                # sending a token instead.
                if self.options["user"] is not None and self.options["password"] is not None:
                    options["user"] = self.options["user"]
                    options["pass"] = self.options["password"]
                elif self.options["token"] is not None:
                    options["auth_token"] = self.options["token"]
                elif self._current_server.uri.password is None:
                    options["auth_token"] = self._current_server.uri.username
                else:
                    options["user"] = self._current_server.uri.username
                    options["pass"] = self._current_server.uri.password
        if self.options["name"] is not None:
            options["name"] = self.options["name"]
        if self.options["no_echo"] is not None:
            options["echo"] = not self.options["no_echo"]

        args = json.dumps(options, sort_keys=True)
        return CONNECT_PROTO.format(CONNECT_OP, args, _CRLF_)
205633
def _get_conn(ret):
    '''
    
    '''
    _options = _get_options(ret)

    host = _options.get('host')
    port = _options.get('port')
    db_ = _options.get('db')
    user = _options.get('user')
    password = _options.get('password')
    indexes = _options.get('indexes', False)

    # at some point we should remove support for
    # pymongo versions < 2.3 until then there are
    # a bunch of these sections that need to be supported

    if PYMONGO_VERSION > _LooseVersion('2.3'):
        conn = pymongo.MongoClient(host, port)
    else:
        conn = pymongo.Connection(host, port)
    mdb = conn[db_]

    if user and password:
        mdb.authenticate(user, password)

    if indexes:
        if PYMONGO_VERSION > _LooseVersion('2.3'):
            mdb.saltReturns.create_index('minion')
            mdb.saltReturns.create_index('jid')

            mdb.jobs.create_index('jid')
        else:
            mdb.saltReturns.ensure_index('minion')
            mdb.saltReturns.ensure_index('jid')

            mdb.jobs.ensure_index('jid')

    return conn, mdb
537464
function() {
      const AUTH_TOKEN = 'AUTH_TOKEN';
      var req = {
        protocol: this.isSrvRecord ? 'mongodb+srv' : 'mongodb',
        slashes: true,
        hostname: this.hostname,
        port: this.isSrvRecord ? null : this.port,
        pathname: '/',
        query: {}
      };

      if (this.replica_set_name) {
        req.query.replicaSet = this.replica_set_name;
      }

      req.query.readPreference = this.read_preference;

      if (this.app_name) {
        req.query.appname = this.app_name;
      }

      if (this.ns) {
        req.pathname = format('/%s', this.ns);
      }

      const encodeAuthForUrlFormat = () => {
        if (this.authentication === 'MONGODB') {
          req.auth = AUTH_TOKEN;
          req.query.authSource = this.mongodb_database_name || MONGODB_DATABASE_NAME_DEFAULT;
        } else if (this.authentication === 'SCRAM-SHA-256') {
          req.auth = AUTH_TOKEN;
          req.query.authSource = this.mongodb_database_name || MONGODB_DATABASE_NAME_DEFAULT;
          req.query.authMechanism = this.driver_auth_mechanism;
        } else if (this.authentication === 'KERBEROS') {
          defaults(req.query, {
            gssapiServiceName: this.kerberos_service_name,
            authMechanism: this.driver_auth_mechanism
          });
          req.auth = AUTH_TOKEN;
        } else if (this.authentication === 'X509') {
          req.auth = this.x509_username;
          defaults(req.query, {
            authMechanism: this.driver_auth_mechanism
          });
        } else if (this.authentication === 'LDAP') {
          req.auth = AUTH_TOKEN;

          defaults(req.query, {
            authMechanism: this.driver_auth_mechanism
          });
        }
      };
      encodeAuthForUrlFormat();

      if (includes(['UNVALIDATED', 'SYSTEMCA', 'SERVER', 'ALL'], this.ssl)) {
        req.query.ssl = 'true';
      } else if (this.ssl === 'IFAVAILABLE') {
        req.query.ssl = 'prefer';
      } else if (this.ssl === 'NONE') {
        req.query.ssl = 'false';
      }
      var reqClone = clone(req);
      if (this.ssh_tunnel !== 'NONE') {
        // Populate the SSH Tunnel options correctly
        reqClone.hostname = this.ssh_tunnel_options.localAddr;
        reqClone.port = this.ssh_tunnel_options.localPort;
      }
      var result = toURL(reqClone);

      // Post url.format() workaround for
      // https://github.com/nodejs/node/issues/1802
      if (this.authentication === 'MONGODB' || this.authentication === 'SCRAM-SHA-256') {
        const authField = format(
          '%s:%s',
          encodeURIComponent(this.mongodb_username),
          encodeURIComponent(this.mongodb_password)
        );

        // The auth component comes straight after the mongodb:// so
        // a single string replace should always work
        result = result.replace(AUTH_TOKEN, authField, 1);
      }
      if (this.authentication === 'LDAP') {
        const authField = format(
          '%s:%s',
          encodeURIComponent(this.ldap_username),
          encodeURIComponent(this.ldap_password)
        );
        result = result.replace(AUTH_TOKEN, authField, 1);
        result = `${result}&authSource=$external`;
      }
      if (this.authentication === 'KERBEROS') {
        if (this.kerberos_password) {
          const authField = format(
            '%s:%s',
            encodeURIComponent(this.kerberos_principal),
            encodeURIComponent(this.kerberos_password)
          );
          result = result.replace(AUTH_TOKEN, authField, 1);
        } else {
          const authField = format(
            '%s:',
            encodeURIComponent(this.kerberos_principal)
          );
          result = result.replace(AUTH_TOKEN, authField, 1);
        }
        result = `${result}&authSource=$external`;
        if (this.kerberos_canonicalize_hostname) {
          result = `${result}&authMechanismProperties=CANONICALIZE_HOST_NAME:true`;
        }
      }
      return result;
    }
1126076
def user_create(name, passwd, user=None, password=None, host=None, port=None,
                database='admin', authdb=None, roles=None):
    '''
    
    '''
    conn = _connect(user, password, host, port, authdb=authdb)
    if not conn:
        return 'Failed to connect to mongo database'

    if not roles:
        roles = []

    try:
        log.info('Creating user %s', name)
        mdb = pymongo.database.Database(conn, database)
        mdb.add_user(name, passwd, roles=roles)
    except pymongo.errors.PyMongoError as err:
        log.error('Creating database %s failed with error: %s', name, err)
        return six.text_type(err)
    return True
1242937
def connect_mysql(host, port, user, password, database):
    """"""
    return pymysql.connect(
        host=host, port=port,
        user=user, passwd=password,
        db=database
    )