Last active
August 12, 2021 13:01
-
-
Save wactbprot/8f2d797eabb4d53d8bf710298273d0b2 to your computer and use it in GitHub Desktop.
Generates a db user and adds it to `--db` as member. (CouchDB, Python3, `os.environ.get()`)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python3 | |
import os | |
import json | |
import requests | |
import argparse | |
from requests.auth import HTTPBasicAuth | |
parser = argparse.ArgumentParser() | |
parser.add_argument("--srv", type=str, nargs=1, | |
help="name of the server (default is localhost)") | |
parser.add_argument("--port", type=str, nargs=1, | |
help="port of the server (default is 5984)") | |
parser.add_argument("--db", type=str, nargs=1, | |
help="name of the database (default is test_db)") | |
args = parser.parse_args() | |
if args.srv: | |
srv = args.srv[0] | |
else: | |
srv = "localhost" | |
if args.port: | |
port = args.port[0] | |
else: | |
port = 5984 | |
if args.db: | |
db_name = args.db[0] | |
else: | |
db_name = "test_db" | |
## read from env | |
db_usr_name = os.environ.get('cal_usr') | |
db_usr_pwd = os.environ.get('cal_pwd') | |
db_admin_name = os.environ.get('admin_usr') | |
db_pwd = os.environ.get('admin_pwd') | |
## build data and url | |
db = "http://{}:{}".format(srv, port) | |
usr_id = "org.couchdb.user:{usr}".format(usr=db_usr_name) | |
d_url = "{db}/_users/{id}".format(db=db, id=usr_id) | |
d_data = {"name": db_usr_name, | |
"password": db_usr_pwd, | |
"roles": [], | |
"type": "user" | |
} | |
s_url = "{db}/{db_name}/_security".format(db=db, db_name=db_name) | |
s_data = {"members": | |
{"names":[db_usr_name], | |
"roles":[]}} | |
## go | |
print("generate usr {}".format(db_usr_name)) | |
req = requests.get(d_url, auth=HTTPBasicAuth(db_admin_name, db_pwd)) | |
rev = req.json().get("_rev") | |
if rev is not None: | |
d_data["_rev"] = rev | |
req = requests.put(d_url, data=json.dumps(d_data), auth=HTTPBasicAuth(db_admin_name, db_pwd)) | |
print(req.json()) | |
req = requests.put(s_url, data=json.dumps(s_data), auth=HTTPBasicAuth(db_admin_name, db_pwd)) | |
print(req.json()) |
Author
wactbprot
commented
Jun 2, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment