Skip to content

Commit

Permalink
api.admin: ensure unique email for admin users
Browse files Browse the repository at this point in the history
The script is allowing multiple users with the
same email address. Fix the issue by creating
unique DB index on `User.email` field.
Remove manual check for existing `username`.
Catch `DuplicateKeyError` from `pymongo` while
creating users for duplicate username or
email field.

Signed-off-by: Jeny Sadadia <[email protected]>
  • Loading branch information
Jeny Sadadia authored and JenySadadia committed Jan 9, 2024
1 parent 5bb3751 commit 8876165
Showing 1 changed file with 17 additions and 14 deletions.
31 changes: 17 additions & 14 deletions api/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
import asyncio
import argparse
import sys

import getpass
import pymongo

from .auth import Authentication
from .db import Database
Expand All @@ -22,31 +22,34 @@

async def setup_admin_user(db, username, email):
"""Create an admin user"""
user_obj = await db.find_one_by_attributes(User,
{'username': username})
if user_obj:
print(f"User {username} already exists, aborting.")
print(user_obj.json())
return None
password = getpass.getpass(f"Password for user '{username}': ")
retyped = getpass.getpass(f"Retype password for user '{username}': ")
if password != retyped:
print("Sorry, passwords do not match, aborting.")
return None
hashed_password = Authentication.get_password_hash(password)
print(f"Creating {username} user...")
return await db.create(User(
username=username,
hashed_password=hashed_password,
email=email,
is_superuser=1,
is_verified=1,
))
try:
return await db.create(User(
username=username,
hashed_password=hashed_password,
email=email,
is_superuser=1,
is_verified=1,
))
except pymongo.errors.DuplicateKeyError as exc:
err = str(exc)
if "username" in err:
print(f"User {username} already exists, aborting.")
elif "email" in err:
print(f"User with {email} already exists, aborting.")
return None


async def main(args):
db = Database(args.mongo, args.database)
await db.initialize_beanie()
await db.create_indexes()
await setup_admin_user(db, args.username, args.email)
return True

Expand Down

0 comments on commit 8876165

Please sign in to comment.