You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kibble.apache.org by tu...@apache.org on 2020/11/27 13:20:28 UTC

[kibble] branch main updated: Refactor make_account as cli command (#94)

This is an automated email from the ASF dual-hosted git repository.

turbaszek pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/kibble.git


The following commit(s) were added to refs/heads/main by this push:
     new 393635e  Refactor make_account as cli command (#94)
393635e is described below

commit 393635e18fcabe75e0cea72005b1f168c0769230
Author: Tomek Urbaszek <tu...@gmail.com>
AuthorDate: Fri Nov 27 13:18:01 2020 +0000

    Refactor make_account as cli command (#94)
---
 kibble.ini                               |   2 +-
 kibble/__main__.py                       |  30 +++++++--
 kibble/cli/make_account_command.py       |  79 +++++++++++++++++++++++
 kibble/cli/setup_command.py              |  17 +++--
 kibble/{setup => mappings}/mappings.json |   0
 kibble/settings.py                       |   3 +
 kibble/setup/kibble.yaml.sample          |  19 ------
 kibble/setup/makeaccount.py              | 104 -------------------------------
 8 files changed, 114 insertions(+), 140 deletions(-)

diff --git a/kibble.ini b/kibble.ini
index 0089f4d..527d574 100644
--- a/kibble.ini
+++ b/kibble.ini
@@ -12,7 +12,7 @@ version = 0.1.0
 # Elasticsearch database name
 dbname = kibble
 # Connection uri used to determine host and port of elasticsearch instance
-conn_uri = elasticsearch:9200
+conn_uri = http://elasticsearch:9200
 # Number of shards in es cluster
 shards = 5
 # Number of replicase in es cluster
diff --git a/kibble/__main__.py b/kibble/__main__.py
index 2807c35..4b1c6b5 100644
--- a/kibble/__main__.py
+++ b/kibble/__main__.py
@@ -18,6 +18,7 @@
 import click
 
 from kibble.cli import setup_command
+from kibble.cli.make_account_command import make_account_cmd
 from kibble.configuration import conf
 from kibble.version import version as kibble_version
 
@@ -29,7 +30,7 @@ def cli():
 
 @cli.command("version", short_help="displays the current kibble version")
 def version():
-    click.echo(kibble_version)
+    print(kibble_version)
 
 
 @cli.command("setup", short_help="starts the setup process for kibble")
@@ -57,9 +58,6 @@ def version():
     default=conf.get("elasticsearch", "replicas"),
     help="number of replicas for ES",
 )
-@click.option(
-    "-m", "--mailhost", default=conf.get("mail", "mailhost"), help="mail server host"
-)
 @click.option("-a", "--autoadmin", default=False, help="generate generic admin account")
 @click.option("-k", "--skiponexist", default=True, help="skip DB creation if DBs exist")
 def setup(
@@ -67,7 +65,6 @@ def setup(
     dbname: str,
     shards: str,
     replicas: str,
-    mailhost: str,
     autoadmin: bool,
     skiponexist: bool,
 ):
@@ -76,12 +73,33 @@ def setup(
         dbname=dbname,
         shards=shards,
         replicas=replicas,
-        mailhost=mailhost,
         autoadmin=autoadmin,
         skiponexist=skiponexist,
     )
 
 
+@cli.command("make_account", short_help="creates new kibble user account")
+@click.option(
+    "-u", "--username", help="username (email) of account to create", required=True
+)
+@click.option("-p", "--password", help="password to set for account", required=True)
+@click.option("-A", "--admin", default=False, help="make account global admin")
+@click.option(
+    "-a", "--orgadmin", default=False, help="make account owner of orgs invited to"
+)
+@click.option("-o", "--org", default=None, help="invite to this organisation")
+def make_account(
+    username: str,
+    password: str,
+    admin: bool = False,
+    orgadmin: bool = False,
+    org: str = None,
+):
+    make_account_cmd(
+        username=username, password=password, admin=admin, adminorg=orgadmin, org=org
+    )
+
+
 def main():
     cli()
 
diff --git a/kibble/cli/make_account_command.py b/kibble/cli/make_account_command.py
new file mode 100644
index 0000000..e0a59f6
--- /dev/null
+++ b/kibble/cli/make_account_command.py
@@ -0,0 +1,79 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from urllib.parse import urlparse
+
+import bcrypt
+import elasticsearch
+
+from kibble.configuration import conf
+
+
+class ESDatabase:
+    def __init__(self):
+        self.dbname = conf.get("elasticsearch", "dbname")
+        parsed = urlparse(conf.get("elasticsearch", "conn_uri"))
+        es_host = {
+            "host": parsed.hostname,
+            "port": parsed.port,
+            "use_ssl": conf.getboolean("elasticsearch", "ssl"),
+            "verify_certs": False,
+            "url_prefix": conf.get("elasticsearch", "uri"),
+            "http_auth": conf.get("elasticsearch", "auth") or None,
+        }
+        self.es = elasticsearch.Elasticsearch(
+            hosts=[es_host], max_retries=5, retry_on_timeout=True
+        )
+
+    def create_index(self, doc_type: str, id_: str, body: dict):
+        self.es.index(index=self.dbname, doc_type=doc_type, id=id_, body=body)
+
+
+def make_account_cmd(
+    username: str,
+    password: str,
+    admin: bool = False,
+    adminorg: bool = False,
+    org: str = None,
+) -> None:
+    """
+    Create user kibble account.
+
+    :param username: username for login for example email
+    :param password: password used for login
+    :param admin: set to true if created user should has admin access level
+    :param adminorg: organization user owns
+    :param org: organisation user belongs to
+    """
+    orgs = [org] or []
+    aorgs = [adminorg] if adminorg else []
+
+    salt = bcrypt.gensalt()
+    pwd = bcrypt.hashpw(password.encode("utf-8"), salt).decode("ascii")
+    doc = {
+        "email": username,
+        "password": pwd,
+        "displayName": username,
+        "organisations": orgs,
+        "ownerships": aorgs,
+        "defaultOrganisation": None,  # Default org for user
+        "verified": True,  # Account verified via email?
+        "userlevel": "admin" if admin else "user",
+    }
+    db = ESDatabase()
+    db.create_index(doc_type="useraccount", id_=username, body=doc)
+    print("Account created!")
diff --git a/kibble/cli/setup_command.py b/kibble/cli/setup_command.py
index a88b7ab..264e7ea 100644
--- a/kibble/cli/setup_command.py
+++ b/kibble/cli/setup_command.py
@@ -22,11 +22,11 @@ import sys
 from getpass import getpass
 
 import bcrypt
-import click
 import tenacity
 from elasticsearch import Elasticsearch
 
 from kibble.configuration import conf
+from kibble.settings import MAPPING_DIRECTORY
 
 KIBBLE_VERSION = conf.get("api", "version")
 KIBBLE_DB_VERSION = conf.get("api", "database")
@@ -53,9 +53,7 @@ def create_es_index(
     # elasticsearch logs lots of warnings on retries/connection failure
     logging.getLogger("elasticsearch").setLevel(logging.ERROR)
 
-    mappings_json = os.path.join(
-        os.path.dirname(os.path.realpath(__file__)), "../setup/mappings.json"
-    )
+    mappings_json = os.path.join(MAPPING_DIRECTORY, "mappings.json")
     with open(mappings_json, "r") as f:
         mappings = json.load(f)
 
@@ -170,11 +168,10 @@ def do_setup(
     dbname: str,
     shards: str,
     replicas: str,
-    mailhost: str,
     autoadmin: bool,
     skiponexist: bool,
 ):
-    click.echo("Welcome to the Apache Kibble setup script!")
+    print("Welcome to the Apache Kibble setup script!")
 
     admin_name = "admin@kibble"
     admin_pass = "kibbleAdmin"
@@ -188,7 +185,7 @@ def do_setup(
 
     # Create Elasticsearch index
     # Retry in case ES is not yet up
-    click.echo(f"Elasticsearch: {uri}")
+    print(f"Elasticsearch: {uri}")
     for attempt in tenacity.Retrying(
         retry=tenacity.retry_if_exception_type(exception_types=Exception),
         wait=tenacity.wait_fixed(10),
@@ -196,7 +193,7 @@ def do_setup(
         reraise=True,
     ):
         with attempt:
-            click.echo("Trying to create ES index...")
+            print("Trying to create ES index...")
             create_es_index(
                 conn_uri=uri,
                 dbname=dbname,
@@ -206,5 +203,5 @@ def do_setup(
                 admin_pass=admin_pass,
                 skiponexist=skiponexist,
             )
-    click.echo()
-    click.echo("All done, Kibble should...work now :)")
+    print()
+    print("All done, Kibble should...work now :)")
diff --git a/kibble/setup/mappings.json b/kibble/mappings/mappings.json
similarity index 100%
rename from kibble/setup/mappings.json
rename to kibble/mappings/mappings.json
diff --git a/kibble/settings.py b/kibble/settings.py
index 243c301..d165bb2 100644
--- a/kibble/settings.py
+++ b/kibble/settings.py
@@ -21,3 +21,6 @@ YAML_DIRECTORY = os.path.join(
     os.path.dirname(os.path.realpath(__file__)), "api", "yaml"
 )
 KIBBLE_YAML = os.path.join(YAML_DIRECTORY, "kibble.yaml")
+MAPPING_DIRECTORY = os.path.join(
+    os.path.dirname(os.path.realpath(__file__)), "mappings"
+)
diff --git a/kibble/setup/kibble.yaml.sample b/kibble/setup/kibble.yaml.sample
deleted file mode 100644
index c414b5e..0000000
--- a/kibble/setup/kibble.yaml.sample
+++ /dev/null
@@ -1,19 +0,0 @@
-elasticsearch:
-    host:       localhost
-    port:       9200
-    ssl:        false
-    dbname:     kibble
-
-mail:
-    mailhost:   localhost
-    mailport:   25
-    sender:     Kibble <no...@kibble.live>
-
-accounts:
-    allowSignup:    true
-    verifyEmail:    false
-    # Example auto-invite setup:
-    autoInvite:
-        -
-            domain: apache.org
-            organisation: apache
diff --git a/kibble/setup/makeaccount.py b/kibble/setup/makeaccount.py
deleted file mode 100644
index 2b4e954..0000000
--- a/kibble/setup/makeaccount.py
+++ /dev/null
@@ -1,104 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#   http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-
-import argparse
-import os
-import os.path
-import sys
-
-import bcrypt
-import elasticsearch
-import yaml
-
-from kibble.settings import KIBBLE_YAML, YAML_DIRECTORY
-
-
-class KibbleDatabase(object):
-    def __init__(self, config):
-        self.config = config
-        self.dbname = config["elasticsearch"]["dbname"]
-        self.ES = elasticsearch.Elasticsearch(
-            [
-                {
-                    "host": config["elasticsearch"]["host"],
-                    "port": int(config["elasticsearch"]["port"]),
-                    "use_ssl": config["elasticsearch"]["ssl"],
-                    "verify_certs": False,
-                    "url_prefix": config["elasticsearch"]["uri"]
-                    if "uri" in config["elasticsearch"]
-                    else "",
-                    "http_auth": config["elasticsearch"]["auth"]
-                    if "auth" in config["elasticsearch"]
-                    else None,
-                }
-            ],
-            max_retries=5,
-            retry_on_timeout=True,
-        )
-
-
-arg_parser = argparse.ArgumentParser()
-arg_parser.add_argument(
-    "-u", "--username", required=True, help="Username (email) of accoun to create"
-)
-arg_parser.add_argument(
-    "-p", "--password", required=True, help="Password to set for account"
-)
-arg_parser.add_argument(
-    "-n", "--name", help="Real name (displayname) of account (optional)"
-)
-arg_parser.add_argument(
-    "-A", "--admin", action="store_true", help="Make account global admin"
-)
-arg_parser.add_argument(
-    "-a",
-    "--orgadmin",
-    action="store_true",
-    help="Make account owner of orgs invited to",
-)
-arg_parser.add_argument("-o", "--org", help="Invite to this organisation")
-
-args = arg_parser.parse_args()
-
-# Load Kibble master configuration
-with open(KIBBLE_YAML) as f:
-    config = yaml.safe_load(f)
-
-DB = KibbleDatabase(config)
-
-username = args.username
-password = args.password
-name = args.name if args.name else args.username
-admin = True if args.admin else False
-adminorg = True if args.orgadmin else False
-orgs = [args.org] if args.org else []
-aorgs = orgs if adminorg else []
-
-salt = bcrypt.gensalt()
-pwd = bcrypt.hashpw(password.encode("utf-8"), salt).decode("ascii")
-doc = {
-    "email": username,  # Username (email)
-    "password": pwd,  # Hashed password
-    "displayName": username,  # Display Name
-    "organisations": orgs,  # Orgs user belongs to (default is none)
-    "ownerships": aorgs,  # Orgs user owns (default is none)
-    "defaultOrganisation": None,  # Default org for user
-    "verified": True,  # Account verified via email?
-    "userlevel": "admin" if admin else "user",  # User level (user/admin)
-}
-DB.ES.index(index=DB.dbname, doc_type="useraccount", id=username, body=doc)
-print("Account created!")