Add more create_user checks

This commit is contained in:
Tim Van Baak 2021-05-27 18:01:37 -07:00
parent 1d5023c41b
commit 63f17cfc7a
1 changed files with 19 additions and 4 deletions

View File

@ -11,6 +11,10 @@ from amanuensis.db import DbContext, User
from amanuensis.errors import ArgumentError from amanuensis.errors import ArgumentError
RE_NO_LETTERS = re.compile(r'^[0-9-_]*$')
RE_ALPHANUM_DASH_UNDER = re.compile(r'^[A-Za-z0-9-_]*$')
def create_user( def create_user(
db: DbContext, db: DbContext,
username: str, username: str,
@ -22,19 +26,30 @@ def create_user(
Create a new user. Create a new user.
""" """
# Verify username # Verify username
if not isinstance(username, str):
raise ArgumentError('Username must be a string')
if len(username) < 3 or len(username) > 32: if len(username) < 3 or len(username) > 32:
raise ArgumentError('Username must be between 3 and 32 characters') raise ArgumentError('Username must be between 3 and 32 characters')
if re.match(r'^[0-9-_]*$', username): if RE_NO_LETTERS.match(username):
raise ArgumentError('Username must contain a letter') raise ArgumentError('Username must contain a letter')
if not re.match(r'^[A-Za-z0-9-_]*$', username): if not RE_ALPHANUM_DASH_UNDER.match(username):
raise ArgumentError('Username may only contain alphanumerics, dash, and underscore') raise ArgumentError('Username may only contain alphanumerics, dash, and underscore')
# Verify password # Verify password
if not password: if not isinstance(password, str):
raise ArgumentError('Password must be provided') raise ArgumentError('Password must be a string')
# Verify display name
if display_name is not None and not isinstance(display_name, str):
raise ArgumentError('Display name must be a string')
# If display name is not provided, use the username # If display name is not provided, use the username
if not display_name or not display_name.strip(): if not display_name or not display_name.strip():
display_name = username display_name = username
# Verify email
if not isinstance(email, str):
raise ArgumentError('Email must be a string')
# Query the db to make sure the username isn't taken # Query the db to make sure the username isn't taken
if db.session.query(func.count(User.id)).filter(User.username == username).scalar() > 0: if db.session.query(func.count(User.id)).filter(User.username == username).scalar() > 0:
raise ArgumentError('Username is already taken') raise ArgumentError('Username is already taken')