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 committed Dec 29, 2023
1 parent e2339eb commit 4da71e1
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):

Check warning on line 23 in api/admin.py

View workflow job for this annotation

GitHub Actions / Lint

Argument name "db" doesn't conform to snake_case naming style
"""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):

Check warning on line 49 in api/admin.py

View workflow job for this annotation

GitHub Actions / Lint

Missing function or method docstring

Check warning on line 49 in api/admin.py

View workflow job for this annotation

GitHub Actions / Lint

Redefining name 'args' from outer scope (line 67)
db = Database(args.mongo, args.database)

Check warning on line 50 in api/admin.py

View workflow job for this annotation

GitHub Actions / Lint

Variable name "db" doesn't conform to snake_case naming style
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 4da71e1

Please sign in to comment.