about summary refs log tree commit diff
path: root/scripts/register_sys_admin.py
diff options
context:
space:
mode:
authorFrederick Muriuki Muriithi2023-08-07 08:40:50 +0300
committerFrederick Muriuki Muriithi2023-08-07 09:26:13 +0300
commita112c99cae0c5422a38e3a35e843a82db764316a (patch)
treef0823fd1fc4d8ec52dc0a12b8d987dd4325b043b /scripts/register_sys_admin.py
parent6d9c61dc0072b96b12153e64940b465306f25bfb (diff)
downloadgn-auth-a112c99cae0c5422a38e3a35e843a82db764316a.tar.gz
Add missing modules
Copy over missing modules and functions to completely disconnect
gn-auth from GN3.
Diffstat (limited to 'scripts/register_sys_admin.py')
-rw-r--r--scripts/register_sys_admin.py81
1 files changed, 81 insertions, 0 deletions
diff --git a/scripts/register_sys_admin.py b/scripts/register_sys_admin.py
new file mode 100644
index 0000000..7d4d667
--- /dev/null
+++ b/scripts/register_sys_admin.py
@@ -0,0 +1,81 @@
+"""Script to register and mark a user account as sysadmin."""
+import sys
+import uuid
+import getpass
+from pathlib import Path
+
+import click
+from email_validator import validate_email, EmailNotValidError
+
+from gn_auth.auth.db import sqlite3 as db
+from gn_auth.auth.authentication.users import hash_password
+
+def fetch_email() -> str:
+    """Prompt user for email."""
+    while True:
+        try:
+            user_input = input("Enter the administrator's email: ")
+            email = validate_email(user_input.strip(), check_deliverability=True)
+            return email["email"]
+        except EmailNotValidError as _enve:
+            print("You did not provide a valid email address. Try again...",
+                  file=sys.stderr)
+
+def fetch_password() -> str:
+    """Prompt user for password."""
+    while True:
+        passwd = getpass.getpass(prompt="Enter password: ").strip()
+        passwd2 = getpass.getpass(prompt="Confirm password: ").strip()
+        if passwd != "" and passwd == passwd2:
+            return passwd
+        if passwd == "":
+            print("Empty password not accepted", file=sys.stderr)
+            continue
+        if passwd != passwd2:
+            print("Passwords *MUST* match", file=sys.stderr)
+            continue
+
+def fetch_name() -> str:
+    """Prompt user for name"""
+    while True:
+        name = input("Enter the user's name: ").strip()
+        if name == "":
+            print("Invalid name.")
+            continue
+        return name
+
+def save_admin(conn: db.DbConnection, name: str, email: str, passwd: str):
+    """Save the details to the database and assign the new user as admin."""
+    admin_id = uuid.uuid4()
+    admin = {
+        "user_id": str(admin_id),
+        "email": email,
+        "name": name,
+        "hash": hash_password(passwd)
+    }
+    with db.cursor(conn) as cursor:
+        cursor.execute("INSERT INTO users VALUES (:user_id, :email, :name)",
+                       admin)
+        cursor.execute("INSERT INTO user_credentials VALUES (:user_id, :hash)",
+                       admin)
+        cursor.execute(
+            "SELECT * FROM roles WHERE role_name='system-administrator'")
+        admin_role = cursor.fetchone()
+        cursor.execute("INSERT INTO user_roles VALUES (:user_id, :role_id)",
+                       {**admin, "role_id": admin_role["role_id"]})
+        return 0
+
+def register_admin(authdbpath: Path):
+    """Register a user as a system admin."""
+    assert authdbpath.exists(), "Could not find database file."
+    with db.connection(str(authdbpath)) as conn:
+        return save_admin(conn, fetch_name(), fetch_email(), fetch_password())
+
+if __name__ == "__main__":
+    @click.command()
+    @click.argument("authdbpath")
+    def run(authdbpath):
+        """Entry-point for when script is run directly"""
+        return register_admin(Path(authdbpath).absolute())
+
+    run()# pylint: disable=[no-value-for-parameter]