Table Of Contents

This Page

auth — Access secured MongoDB servers

Caution

The auth module is still being designed! Not for use.

The auth module makes connecting to MongoDB instances easier. The same Python code can decide to connect to a MongoDB server locally, or over an SSH tunnel, depending on where the code is called from. This is handled with a ~/.moastro_auth file on each client computer.

Background

Normally, connecting to a MongoDB database requires several arguments:

  1. host url,
  2. port, and
  3. database name.

If the database is secured, a

  1. username, and
  2. password

are also required. If one is always running a code locally, this is not a problem. However, in collaborative environments, the host will need to be changed programmatically from localhost to the external URL of the database server. The moastro.auth module provides a standard interface for connecting to a MongoDB database from a user’s perspective.

The moasto credentials format

Python codes can create a pymongo connection to a database by specifying a named database.

Credentials for MongoDB databases are written in ~/.moastro_auth in JSON format. For example:

{"db_key": {"db_name": the_db_name,
            "host": host_url,
            "port": port_on_host}
}

Each database that your application connects to would be an extra key-value in the .moastro_auth file.

Requesting a SSH tunnel

How to specify an SSH tunnel in ~/.moastro_auth.

Implementation Notes

Object Design

Use the Borg Pattern (Martelli 2005; 6.16) to ensure that all Credentials classes share the same state and obviate needing to re-read the auth file. Also, the Credentials class should be split from the Connector class. The Connector class would actually set up the SSH tunnels, and cache db objects, etc. Credentials would simply parse the credentials file and provide access.

API

class auth.Credentials[source]

Stores credentials for MongoDB databases and facilitates DB connections.

Credentials for MongoDB databases are written in ~/.moastro_auth in JSON format. For example:

{"localhost":
     {"my_db": {
         "user": "jsick",
         "pwd": "mypwd"},
     "my_other_db": {
         "user": "jsick",
         "pwd": "mypwd"},
     }
}

Methods

connect_db
connect_db(dbname, c=None, host='localhost', port=27017)[source]

Authorizes a MongoDB database, returning the DB instance.

There are two means of connecting to a database:

  1. Pass a pymongo.Connection instance of the host as

    the c keyword argument

  2. Pass the host URL and port using the host and port keyword

    arguments.

A Connection instance takes precedence over host and port.

Parameters:
  • dbname – (required) the name of the database
  • c – A pymongo Connection instance.
  • host – Address (IP) of the MongoDB server
  • port – Port that the MongoDB server uses
Returns:

pymongo.database instance.