def init(endpoint, email):
    """Request a token.

    EMAIL: Your email address registered with your mongogrant administrator.
    """
    if endpoint is None:
        print("You have no saved endpoints. Provide an endpoint argument.")
        return

    rv = requests.get("{}/gettoken/{}".format(endpoint, email))
    print(rv.json())
    client = Client()
    client.set_remote(endpoint, "")
    print("Copy the fetch token from the link and run `mgrant settoken`.")
Ejemplo n.º 2
0
def settoken(endpoint, token):
    """Set token for a remote

    TOKEN: Your fetch token
    """
    if endpoint is None:
        print("You have no saved endpoints. Provide an endpoint argument.")
        return

    client = Client()
    client.set_remote(endpoint, token)
    print("Remember that tokens expire. Run `mgrant init` to request "
          "a fresh token for an endpoint.")
    print("Run `mgrant db` to get credentials for a database.")
Ejemplo n.º 3
0
def settoken(endpoint, token):
    """Set token for a remote

    TOKEN: Your fetch token
    """
    if endpoint is None:
        print("You have no saved endpoints. Provide an endpoint argument.")
        return

    client = Client()
    client.set_remote(endpoint, token)
    print("Remember that tokens expire. Run `mgrant init` to request "
          "a fresh token for an endpoint.")
    print("Run `mgrant db` to get credentials for a database "
          "(note that the server you are requesting credentials from "
          "may require you to be connected through a VPN.)")
Ejemplo n.º 4
0
def allow(endpoint, email, spec):
    """
    [Admins only] Set allow rules for users.

    \b
    EMAIL: Email address of user to update.
    SPEC: mongogrant spec, e.g. "ro:host/dbname", "rw:host/dbname"
    """
    client = Client()
    remote = next(r for r in client.remotes() if r["endpoint"] == endpoint)
    token = remote["token"]
    if not token:
        print(
            "You do not have a token set for your default endpoint. See `mgrant init --help`."
        )
        return
    role, host_db = spec.split(":")
    host, db = host_db.split("/")
    roles = {"ro", "rw", "read", "readWrite"}
    if role not in roles:
        print("Role not recognized. Must be one of {}".format(roles))
        return

    if role == "ro":
        role = "read"
    elif role == "rw":
        role = "readWrite"
    rv = requests.post("{}/setrule/{}".format(endpoint, token),
                       data=dict(
                           email=email,
                           host=host,
                           db=db,
                           role=role,
                           which="allow",
                       ))
    if rv.json()["success"]:
        print("{} is now authorized to obtain {} credentials for {}/{} "
              "via mongogrant (from remote \"{}\").".format(
                  email,
                  "read" if role == "read" else "read and readWrite",
                  host,
                  db,
                  endpoint,
              ))
    else:
        print("Rule setting failed: {}".format(rv.text))
Ejemplo n.º 5
0
def db(db, role, host, atomate_starters):
    """
    Get credentials for a database.

    \b
    HOST: Database host. Ask your mongogrant administrator
    DB: Database name. Ask your mongogrant administrator
    """
    if atomate_starters and role == 'read':
        print("Need '--role readWrite' for atomate credentials.")
        return
    client = Client()
    if atomate_starters:
        db_rw = client.db("{}:{}/{}".format(role, host, db))
        admin = client.get_auth(host, db, role)
        db_ro = client.db("{}:{}/{}".format("read", host, db))
        readonly = client.get_auth(host, db, "read")
        db_json = dict(host=host,
                       database=db,
                       collection="tasks",
                       admin_user=admin['username'],
                       admin_password=admin['password'],
                       readonly_user=readonly['username'],
                       readonly_password=readonly['password'],
                       aliases={})
        print(json.dumps(db_json, indent=2))
        my_launchpad = my_launchpad_template.format(host, db,
                                                    admin['username'],
                                                    admin['password'])
        print(my_launchpad)
    else:
        db_we = client.db("{}:{}/{}".format(role, host, db))
        print("Wrote credentials to ~/.mongogrant.json")
Ejemplo n.º 6
0
def calcdb_from_mgrant(spec_or_dbfile):
    if os.path.exists(spec_or_dbfile):
        return VaspCalcDb.from_db_file(spec_or_dbfile)

    client = Client()
    role = "rw"  # NOTE need write access to source to ensure indexes
    host, dbname_or_alias = spec_or_dbfile.split("/", 1)
    auth = client.get_auth(host, dbname_or_alias, role)
    if auth is None:
        raise Exception("No valid auth credentials available!")
    return VaspCalcDb(
        auth["host"],
        27017,
        auth["db"],
        "tasks",
        auth["username"],
        auth["password"],
        authSource=auth["db"],
    )
Ejemplo n.º 7
0
def init(endpoint, email):
    """Request a token.

    EMAIL: Your email address registered with your mongogrant administrator.
    """
    if endpoint is None:
        print("You have no saved endpoints. Provide an endpoint argument.")
        return

    rv = requests.get("{}/gettoken/{}".format(endpoint, email))
    if rv.status_code == 403:
        print(rv.reason, ":", rv.text)
        print("Ensure you have been given access to at least one database.")
    elif rv.status_code != 200:
        print(rv.reason, ":", rv.text)
    else:
        print(rv.json())
        print("Copy the fetch token from the link and run `mgrant settoken`.")

    client = Client()
    client.set_remote(endpoint, "")
Ejemplo n.º 8
0
 def test_empty_init(self):
     os.environ["HOME"] = os.path.split(self.config_path)[0]
     self.assertTrue(Client().cfg is not None)
Ejemplo n.º 9
0
 def setUp(self):
     config = Config(check=check, path=self.config_path, seed=seed())
     self.client = Client(config)
Ejemplo n.º 10
0
class TestClient(TestCase):
    @classmethod
    def setUpClass(cls):
        cls.mongod_with_auth = MongodWithAuth(port=27020)
        cls.mongod_with_auth.ensure()
        _, cls.config_path = tempfile.mkstemp()
        cls.dbname = "test_" + uuid4().hex
        cls.db = MongoClient(
            "mongodb://*****:*****@localhost:27020/admin")[
                cls.dbname]
        cls.db.command("createUser",
                       "reader",
                       pwd="readerpass",
                       roles=["read"])
        cls.db.command("createUser",
                       "writer",
                       pwd="writerpass",
                       roles=["readWrite"])

    @classmethod
    def tearDownClass(cls):
        os.remove(cls.config_path)
        cls.db.command("dropDatabase")
        cls.db.client.close()
        cls.mongod_with_auth.destroy()

    def setUp(self):
        config = Config(check=check, path=self.config_path, seed=seed())
        self.client = Client(config)

    def test_empty_init(self):
        os.environ["HOME"] = os.path.split(self.config_path)[0]
        self.assertTrue(Client().cfg is not None)

    def test_remotes(self):
        self.assertEqual(len(self.client.remotes()), 0)
        self.client.set_remote("ep1", "tk1")
        self.assertIn(dict(endpoint="ep1", token="tk1"), self.client.remotes())
        self.client.set_remote("ep1", "tk0")
        self.client.set_remote("ep2", "tk2")
        remotes = self.client.remotes()
        self.assertIn(dict(endpoint="ep1", token="tk0"), remotes)
        self.assertIn(dict(endpoint="ep2", token="tk2"), remotes)
        self.assertNotIn(dict(endpoint="ep1", token="tk1"), remotes)

    def test_aliases(self):
        self.assertEqual(len(self.client.aliases()), 0)
        h_alias = "dev"
        h_actual = "my.example.com"
        self.client.set_alias(h_alias, h_actual)
        self.assertIn(h_alias, self.client.aliases())
        self.assertTrue(h_actual, self.client.aliases()[h_alias])
        self.client.set_alias("h_alt_alias", h_actual)
        self.assertTrue(h_actual, self.client.aliases()["h_alt_alias"])
        d_alias = "core"
        d_actual = "the_best_db"
        self.client.set_alias(d_alias, d_actual, which="db")
        self.assertIn(d_alias, self.client.aliases("db"))
        self.assertTrue(d_actual, self.client.aliases("db")[d_alias])

    def test_auth(self):
        host = "my.example.com"
        db = "the_best_db"
        user_ro, user_rw = "user_ro", "user_rw"
        pass_ro, pass_rw = "pass_ro", "pass_rw"
        self.client.set_auth(host, db, "read", user_ro, pass_ro)
        self.client.set_auth(host, db, "readWrite", user_rw, pass_rw)
        self.assertTrue(self.client.get_auth(host, db, "read"))
        self.assertTrue(self.client.get_auth(host, db, "readWrite"))
        self.client.set_alias("dev", host, "host")
        auth = self.client.get_auth("dev", db, "read")
        self.assertEqual(auth["host"], host)
        self.client.set_alias("core", "the_best_db", "db")
        auth = self.client.get_auth("dev", "core", "read")
        self.assertEqual(auth["host"], host)

    def test_db(self):
        self.client.set_auth("localhost:27020",
                             self.dbname,
                             "read",
                             "reader",
                             "readerpass",
                             check=True)
        self.client.set_auth("localhost:27020",
                             self.dbname,
                             "readWrite",
                             "writer",
                             "writerpass",
                             check=True)
        self.client.set_alias("dev", "localhost:27020", "host")
        self.client.set_alias("core", self.dbname, "db")
        self.assertTrue(self.client.get_auth("dev", "core", "ro"))
        db = self.client.db("ro:dev/core")
        self.assertIsInstance(db, pymongo.database.Database)
        self.assertRaises(pymongo.errors.OperationFailure,
                          db.collection.insert_one, {"a": 1})
        db = self.client.db("rw:dev/core")
        db.collection.insert_one({"a": 1})
        self.assertTrue(db.collection.find_one({"a": 1}))
Ejemplo n.º 11
0
import json

import click
import requests

from mongogrant.client import Client

remotes = Client().remotes()
DEFAULT_ENDPOINT = remotes[0]["endpoint"] if remotes else None


@click.group()
def cli():
    """Run `mgrant init --help` to get started."""
    pass


@click.command()
@click.option('--endpoint',
              default=DEFAULT_ENDPOINT,
              help=('Mongogrant endpoint. Defaults to that of your first '
                    'remote. default: "{}"'.format(DEFAULT_ENDPOINT)))
@click.argument('email')
def init(endpoint, email):
    """Request a token.

    EMAIL: Your email address registered with your mongogrant administrator.
    """
    if endpoint is None:
        print("You have no saved endpoints. Provide an endpoint argument.")
        return