Example #1
0
    def authenticate(self,
                     name=None,
                     password=None,
                     source=None,
                     mechanism='DEFAULT',
                     **kwargs):
        """Authenticate to use this database.

        Authentication lasts for the life of the underlying client
        instance, or until :meth:`logout` is called.

        Raises :class:`TypeError` if (required) `name`, (optional) `password`,
        or (optional) `source` is not an instance of :class:`basestring`
        (:class:`str` in python 3).

        .. note::
          - This method authenticates the current connection, and
            will also cause all new :class:`~socket.socket` connections
            in the underlying client instance to be authenticated automatically.

          - Authenticating more than once on the same database with different
            credentials is not supported. You must call :meth:`logout` before
            authenticating with new credentials.

          - When sharing a client instance between multiple threads, all
            threads will share the authentication. If you need different
            authentication profiles for different purposes you must use
            distinct client instances.

        :Parameters:
          - `name`: the name of the user to authenticate. Optional when
            `mechanism` is MONGODB-X509 and the MongoDB server version is
            >= 3.4.
          - `password` (optional): the password of the user to authenticate.
            Not used with GSSAPI or MONGODB-X509 authentication.
          - `source` (optional): the database to authenticate on. If not
            specified the current database is used.
          - `mechanism` (optional): See
            :data:`~pymongo.auth.MECHANISMS` for options.
            By default, use SCRAM-SHA-1 with MongoDB 3.0 and later,
            MONGODB-CR (MongoDB Challenge Response protocol) for older servers.
          - `authMechanismProperties` (optional): Used to specify
            authentication mechanism specific options. To specify the service
            name for GSSAPI authentication pass
            authMechanismProperties='SERVICE_NAME:<service name>'

        .. versionadded:: 2.8
           Use SCRAM-SHA-1 with MongoDB 3.0 and later.

        .. versionchanged:: 2.5
           Added the `source` and `mechanism` parameters. :meth:`authenticate`
           now raises a subclass of :class:`~pymongo.errors.PyMongoError` if
           authentication fails due to invalid credentials or configuration
           issues.

        .. mongodoc:: authenticate
        """
        if name is not None and not isinstance(name, string_type):
            raise TypeError("name must be an "
                            "instance of %s" % (string_type.__name__, ))
        if password is not None and not isinstance(password, string_type):
            raise TypeError("password must be an "
                            "instance of %s" % (string_type.__name__, ))
        if source is not None and not isinstance(source, string_type):
            raise TypeError("source must be an "
                            "instance of %s" % (string_type.__name__, ))
        common.validate_auth_mechanism('mechanism', mechanism)

        validated_options = {}
        for option, value in iteritems(kwargs):
            normalized, val = common.validate_auth_option(option, value)
            validated_options[normalized] = val

        credentials = auth._build_credentials_tuple(mechanism, source
                                                    or self.name, name,
                                                    password,
                                                    validated_options)

        self.client._cache_credentials(self.name, credentials, connect=True)

        return True
Example #2
0
    def authenticate(self, name=None, password=None,
                     source=None, mechanism='DEFAULT', **kwargs):
        """**DEPRECATED**: Authenticate to use this database.

        .. warning:: Starting in MongoDB 3.6, calling :meth:`authenticate`
          invalidates all existing cursors. It may also leave logical sessions
          open on the server for up to 30 minutes until they time out.

        Authentication lasts for the life of the underlying client
        instance, or until :meth:`logout` is called.

        Raises :class:`TypeError` if (required) `name`, (optional) `password`,
        or (optional) `source` is not an instance of :class:`basestring`
        (:class:`str` in python 3).

        .. note::
          - This method authenticates the current connection, and
            will also cause all new :class:`~socket.socket` connections
            in the underlying client instance to be authenticated automatically.

          - Authenticating more than once on the same database with different
            credentials is not supported. You must call :meth:`logout` before
            authenticating with new credentials.

          - When sharing a client instance between multiple threads, all
            threads will share the authentication. If you need different
            authentication profiles for different purposes you must use
            distinct client instances.

        :Parameters:
          - `name`: the name of the user to authenticate. Optional when
            `mechanism` is MONGODB-X509 and the MongoDB server version is
            >= 3.4.
          - `password` (optional): the password of the user to authenticate.
            Not used with GSSAPI or MONGODB-X509 authentication.
          - `source` (optional): the database to authenticate on. If not
            specified the current database is used.
          - `mechanism` (optional): See :data:`~pymongo.auth.MECHANISMS` for
            options. If no mechanism is specified, PyMongo automatically uses
            MONGODB-CR when connected to a pre-3.0 version of MongoDB,
            SCRAM-SHA-1 when connected to MongoDB 3.0 through 3.6, and
            negotiates the mechanism to use (SCRAM-SHA-1 or SCRAM-SHA-256) when
            connected to MongoDB 4.0+.
          - `authMechanismProperties` (optional): Used to specify
            authentication mechanism specific options. To specify the service
            name for GSSAPI authentication pass
            ``authMechanismProperties='SERVICE_NAME:<service name>'``.
            To specify the session token for MONGODB-AWS authentication pass
            ``authMechanismProperties='AWS_SESSION_TOKEN:<session token>'``.

        .. versionchanged:: 3.7
           Added support for SCRAM-SHA-256 with MongoDB 4.0 and later.

        .. versionchanged:: 3.5
           Deprecated. Authenticating multiple users conflicts with support for
           logical sessions in MongoDB 3.6. To authenticate as multiple users,
           create multiple instances of MongoClient.

        .. versionadded:: 2.8
           Use SCRAM-SHA-1 with MongoDB 3.0 and later.

        .. versionchanged:: 2.5
           Added the `source` and `mechanism` parameters. :meth:`authenticate`
           now raises a subclass of :class:`~pymongo.errors.PyMongoError` if
           authentication fails due to invalid credentials or configuration
           issues.

        .. mongodoc:: authenticate
        """
        if name is not None and not isinstance(name, str):
            raise TypeError("name must be an instance of str")
        if password is not None and not isinstance(password, str):
            raise TypeError("password must be an instance of str")
        if source is not None and not isinstance(source, str):
            raise TypeError("source must be an instance of str")
        common.validate_auth_mechanism('mechanism', mechanism)

        validated_options = common._CaseInsensitiveDictionary()
        for option, value in kwargs.items():
            normalized, val = common.validate_auth_option(option, value)
            validated_options[normalized] = val

        credentials = auth._build_credentials_tuple(
            mechanism,
            source,
            name,
            password,
            validated_options,
            self.name)

        self.client._cache_credentials(
            self.name,
            credentials,
            connect=True)

        return True
Example #3
0
    def authenticate(self, name, password=None,
                     source=None, mechanism='MONGODB-CR', **kwargs):
        """Authenticate to use this database.

        Authentication lasts for the life of the underlying client
        instance, or until :meth:`logout` is called.

        Raises :class:`TypeError` if (required) `name`, (optional) `password`,
        or (optional) `source` is not an instance of :class:`basestring`
        (:class:`str` in python 3).

        .. note::
          - This method authenticates the current connection, and
            will also cause all new :class:`~socket.socket` connections
            in the underlying client instance to be authenticated automatically.

          - Authenticating more than once on the same database with different
            credentials is not supported. You must call :meth:`logout` before
            authenticating with new credentials.

          - When sharing a client instance between multiple threads, all
            threads will share the authentication. If you need different
            authentication profiles for different purposes you must use
            distinct client instances.

          - To get authentication to apply immediately to all
            existing sockets you may need to reset this client instance's
            sockets using :meth:`~pymongo.mongo_client.MongoClient.disconnect`.

        :Parameters:
          - `name`: the name of the user to authenticate.
          - `password` (optional): the password of the user to authenticate.
            Not used with GSSAPI or MONGODB-X509 authentication.
          - `source` (optional): the database to authenticate on. If not
            specified the current database is used.
          - `mechanism` (optional): See
            :data:`~pymongo.auth.MECHANISMS` for options.
            Defaults to MONGODB-CR (MongoDB Challenge Response protocol)
          - `gssapiServiceName` (optional): Used with the GSSAPI mechanism
            to specify the service name portion of the service principal name.
            Defaults to 'mongodb'.

        .. versionchanged:: 2.5
           Added the `source` and `mechanism` parameters. :meth:`authenticate`
           now raises a subclass of :class:`~pymongo.errors.PyMongoError` if
           authentication fails due to invalid credentials or configuration
           issues.

        .. mongodoc:: authenticate
        """
        if not isinstance(name, str):
            raise TypeError("name must be an instance "
                            "of %s" % (str.__name__,))
        if password is not None and not isinstance(password, str):
            raise TypeError("password must be an instance "
                            "of %s" % (str.__name__,))
        if source is not None and not isinstance(source, str):
            raise TypeError("source must be an instance "
                            "of %s" % (str.__name__,))
        common.validate_auth_mechanism('mechanism', mechanism)

        validated_options = {}
        for option, value in kwargs.items():
            normalized, val = common.validate_auth_option(option, value)
            validated_options[normalized] = val

        credentials = auth._build_credentials_tuple(mechanism,
                                source or self.name, str(name),
                                password and str(password) or None,
                                validated_options)
        self.connection._cache_credentials(self.name, credentials)
        return True
    def authenticate(self, name, password=None,
                     source=None, mechanism='MONGODB-CR'):
        """Authenticate to use this database.

        Raises :class:`TypeError` if either `name` or `password` is not
        an instance of :class:`basestring` (:class:`str` in python 3).
        Authentication lasts for the life of the underlying client
        instance, or until :meth:`logout` is called.

        The "admin" database is special. Authenticating on "admin"
        gives access to *all* databases. Effectively, "admin" access
        means root access to the database.

        .. note::
          This method authenticates the current connection, and
          will also cause all new :class:`~socket.socket` connections
          in the underlying client instance to be authenticated automatically.

         - Authenticating more than once on the same database with different
           credentials is not supported. You must call :meth:`logout` before
           authenticating with new credentials.

         - When sharing a client instance between multiple threads, all
           threads will share the authentication. If you need different
           authentication profiles for different purposes you must use
           distinct client instances.

         - To get authentication to apply immediately to all
           existing sockets you may need to reset this client instance's
           sockets using :meth:`~pymongo.mongo_client.MongoClient.disconnect`.

        :Parameters:
          - `name`: the name of the user to authenticate.
          - `password` (optional): the password of the user to authenticate.
            Not used with GSSAPI authentication.
          - `source` (optional): the database to authenticate on. If not
            specified the current database is used.
          - `mechanism` (optional): See
            :data:`~pymongo.auth.MECHANISMS` for options.
            Defaults to MONGODB-CR (MongoDB Challenge Response protocol)

        .. mongodoc:: authenticate
        """
        if not isinstance(name, basestring):
            raise TypeError("name must be an instance "
                            "of %s" % (basestring.__name__,))
        if password is not None and not isinstance(password, basestring):
            raise TypeError("password must be an instance "
                            "of %s" % (basestring.__name__,))
        if source is not None and not isinstance(source, basestring):
            raise TypeError("source must be an instance "
                            "of %s" % (basestring.__name__,))
        common.validate_auth_mechanism('mechanism', mechanism)

        try:
            credentials = (source or self.name, unicode(name),
                           password and unicode(password) or None, mechanism)
            self.connection._cache_credentials(self.name, credentials)
            return True
        except OperationFailure:
            return False
Example #5
0
    def authenticate(self,
                     name,
                     password=None,
                     source=None,
                     mechanism='MONGODB-CR',
                     **kwargs):
        """Authenticate to use this database.

        Authentication lasts for the life of the underlying client
        instance, or until :meth:`logout` is called.

        Raises :class:`TypeError` if (required) `name`, (optional) `password`,
        or (optional) `source` is not an instance of :class:`basestring`
        (:class:`str` in python 3).

        .. note::
          - This method authenticates the current connection, and
            will also cause all new :class:`~socket.socket` connections
            in the underlying client instance to be authenticated automatically.

          - Authenticating more than once on the same database with different
            credentials is not supported. You must call :meth:`logout` before
            authenticating with new credentials.

          - When sharing a client instance between multiple threads, all
            threads will share the authentication. If you need different
            authentication profiles for different purposes you must use
            distinct client instances.

          - To get authentication to apply immediately to all
            existing sockets you may need to reset this client instance's
            sockets using :meth:`~pymongo.mongo_client.MongoClient.disconnect`.

        :Parameters:
          - `name`: the name of the user to authenticate.
          - `password` (optional): the password of the user to authenticate.
            Not used with GSSAPI or MONGODB-X509 authentication.
          - `source` (optional): the database to authenticate on. If not
            specified the current database is used.
          - `mechanism` (optional): See
            :data:`~pymongo.auth.MECHANISMS` for options.
            Defaults to MONGODB-CR (MongoDB Challenge Response protocol)
          - `gssapiServiceName` (optional): Used with the GSSAPI mechanism
            to specify the service name portion of the service principal name.
            Defaults to 'mongodb'.

        .. versionchanged:: 2.5
           Added the `source` and `mechanism` parameters. :meth:`authenticate`
           now raises a subclass of :class:`~pymongo.errors.PyMongoError` if
           authentication fails due to invalid credentials or configuration
           issues.

        .. mongodoc:: authenticate
        """
        if not isinstance(name, basestring):
            raise TypeError("name must be an instance "
                            "of %s" % (basestring.__name__, ))
        if password is not None and not isinstance(password, basestring):
            raise TypeError("password must be an instance "
                            "of %s" % (basestring.__name__, ))
        if source is not None and not isinstance(source, basestring):
            raise TypeError("source must be an instance "
                            "of %s" % (basestring.__name__, ))
        common.validate_auth_mechanism('mechanism', mechanism)

        validated_options = {}
        for option, value in kwargs.iteritems():
            normalized, val = common.validate_auth_option(option, value)
            validated_options[normalized] = val

        credentials = auth._build_credentials_tuple(
            mechanism, source or self.name, unicode(name),
            password and unicode(password) or None, validated_options)
        self.connection._cache_credentials(self.name, credentials)
        return True
Example #6
0
    def authenticate(self, name, password=None,
                     source=None, mechanism='DEFAULT', **kwargs):
        """Authenticate to use this database.

        Authentication lasts for the life of the underlying client
        instance, or until :meth:`logout` is called.

        Raises :class:`TypeError` if (required) `name`, (optional) `password`,
        or (optional) `source` is not an instance of :class:`basestring`
        (:class:`str` in python 3).

        .. note::
          - This method authenticates the current connection, and
            will also cause all new :class:`~socket.socket` connections
            in the underlying client instance to be authenticated automatically.

          - Authenticating more than once on the same database with different
            credentials is not supported. You must call :meth:`logout` before
            authenticating with new credentials.

          - When sharing a client instance between multiple threads, all
            threads will share the authentication. If you need different
            authentication profiles for different purposes you must use
            distinct client instances.

        :Parameters:
          - `name`: the name of the user to authenticate.
          - `password` (optional): the password of the user to authenticate.
            Not used with GSSAPI or MONGODB-X509 authentication.
          - `source` (optional): the database to authenticate on. If not
            specified the current database is used.
          - `mechanism` (optional): See
            :data:`~pymongo.auth.MECHANISMS` for options.
            By default, use SCRAM-SHA-1 with MongoDB 3.0 and later,
            MONGODB-CR (MongoDB Challenge Response protocol) for older servers.
          - `authMechanismProperties` (optional): Used to specify
            authentication mechanism specific options. To specify the service
            name for GSSAPI authentication pass
            authMechanismProperties='SERVICE_NAME:<service name>'

        .. versionadded:: 2.8
           Use SCRAM-SHA-1 with MongoDB 3.0 and later.

        .. versionchanged:: 2.5
           Added the `source` and `mechanism` parameters. :meth:`authenticate`
           now raises a subclass of :class:`~pymongo.errors.PyMongoError` if
           authentication fails due to invalid credentials or configuration
           issues.

        .. mongodoc:: authenticate
        """
        if not isinstance(name, string_type):
            raise TypeError("name must be an "
                            "instance of %s" % (string_type.__name__,))
        if password is not None and not isinstance(password, string_type):
            raise TypeError("password must be an "
                            "instance of %s" % (string_type.__name__,))
        if source is not None and not isinstance(source, string_type):
            raise TypeError("source must be an "
                            "instance of %s" % (string_type.__name__,))
        common.validate_auth_mechanism('mechanism', mechanism)

        validated_options = {}
        for option, value in iteritems(kwargs):
            normalized, val = common.validate_auth_option(option, value)
            validated_options[normalized] = val

        credentials = auth._build_credentials_tuple(
            mechanism,
            source or self.name,
            name,
            password,
            validated_options)

        self.client._cache_credentials(
            self.name,
            credentials,
            connect=True)

        return True
    def authenticate(self,
                     name,
                     password=None,
                     source=None,
                     mechanism='MONGODB-CR'):
        """Authenticate to use this database.

        Raises :class:`TypeError` if either `name` or `password` is not
        an instance of :class:`basestring` (:class:`str` in python 3).
        Authentication lasts for the life of the underlying client
        instance, or until :meth:`logout` is called.

        The "admin" database is special. Authenticating on "admin"
        gives access to *all* databases. Effectively, "admin" access
        means root access to the database.

        .. note::
          This method authenticates the current connection, and
          will also cause all new :class:`~socket.socket` connections
          in the underlying client instance to be authenticated automatically.

         - Authenticating more than once on the same database with different
           credentials is not supported. You must call :meth:`logout` before
           authenticating with new credentials.

         - When sharing a client instance between multiple threads, all
           threads will share the authentication. If you need different
           authentication profiles for different purposes you must use
           distinct client instances.

         - To get authentication to apply immediately to all
           existing sockets you may need to reset this client instance's
           sockets using :meth:`~pymongo.mongo_client.MongoClient.disconnect`.

        :Parameters:
          - `name`: the name of the user to authenticate.
          - `password` (optional): the password of the user to authenticate.
            Not used with GSSAPI authentication.
          - `source` (optional): the database to authenticate on. If not
            specified the current database is used.
          - `mechanism` (optional): See
            :data:`~pymongo.auth.MECHANISMS` for options.
            Defaults to MONGODB-CR (MongoDB Challenge Response protocol)

        .. versionchanged:: 2.5
           Added the `source` and `mechanism` parameters. :meth:`authenticate`
           now raises a subclass of :class:`~pymongo.errors.PyMongoError` if
           authentication fails due to invalid credentials or configuration
           issues.

        .. mongodoc:: authenticate
        """
        if not isinstance(name, basestring):
            raise TypeError("name must be an instance "
                            "of %s" % (basestring.__name__, ))
        if password is not None and not isinstance(password, basestring):
            raise TypeError("password must be an instance "
                            "of %s" % (basestring.__name__, ))
        if source is not None and not isinstance(source, basestring):
            raise TypeError("source must be an instance "
                            "of %s" % (basestring.__name__, ))
        common.validate_auth_mechanism('mechanism', mechanism)

        credentials = (source or self.name, unicode(name),
                       password and unicode(password) or None, mechanism)
        self.connection._cache_credentials(self.name, credentials)
        return True