Make registration show an error message on username or email reuse

This commit is contained in:
Gergely Polonkai 2018-07-10 15:33:57 +02:00
parent 0595a28535
commit 66659dfe51
2 changed files with 66 additions and 3 deletions

View File

@ -23,16 +23,78 @@ from flask_wtf import FlaskForm
import pytz
from wtforms import BooleanField, PasswordField, SelectField, StringField
from wtforms.ext.dateutil.fields import DateTimeField
from wtforms.validators import DataRequired, Email, ValidationError
from wtforms.validators import DataRequired, Email, StopValidation, ValidationError
from wtforms.widgets import TextArea
class UsernameAvailable(object): # pylint: disable=too-few-public-methods
"""Checks if a username is available
"""
def __init__(self, message=None):
self.message = message
def __call__(self, form, field):
from sqlalchemy.orm.exc import NoResultFound
from calsocial.models import User
# If there is no data, we dont raise an error; its not the task of this validator to
# check the validity of the username
if not field.data:
return
try:
User.query.filter(User.username == field.data).one()
except NoResultFound:
return
if self.message is None:
message = field.gettext('This username is not available')
else:
message = self.message
field.errors[:] = []
raise StopValidation(message)
class EmailAvailable(object): # pylint: disable=too-few-public-methods
"""Checks if an email address is available
"""
def __init__(self, message=None):
self.message = message
def __call__(self, form, field):
from sqlalchemy.orm.exc import NoResultFound
from calsocial.models import User
# If there is no data, we dont raise an error; its not the task of this validator to
# check the validity of the username
if not field.data:
return
try:
User.query.filter(User.email == field.data).one()
except NoResultFound:
return
if self.message is None:
message = field.gettext('This email address can not be used')
else:
message = self.message
field.errors[:] = []
raise StopValidation(message)
class RegistrationForm(FlaskForm):
"""Registration form
"""
username = StringField(_('Username'), validators=[DataRequired()])
email = StringField(_('Email address'), validators=[Email()])
username = StringField(_('Username'), validators=[DataRequired(), UsernameAvailable()])
email = StringField(_('Email address'), validators=[Email(), EmailAvailable()])
password = PasswordField(_('Password'), validators=[DataRequired()])
password_retype = PasswordField(_('Password, once more'), validators=[DataRequired()])

View File

@ -2,6 +2,7 @@
{% block content %}
<form method="post">
{{ form.errors }}
{{ form.hidden_tag() }}
{{ form.username.errors }}