changeset 33:6b7774cff458

Implement validation for duplicate usernames.
author Daniele Nicolodi <daniele@grinta.net>
date Mon, 27 Jun 2011 19:31:25 +0200
parents d0d44e440598
children d87ede392d48
files src/ltpdarepo/tests/manage-users.txt src/ltpdarepo/user.py
diffstat 2 files changed, 34 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/src/ltpdarepo/tests/manage-users.txt	Mon Jun 27 19:19:23 2011 +0200
+++ b/src/ltpdarepo/tests/manage-users.txt	Mon Jun 27 19:31:25 2011 +0200
@@ -112,3 +112,24 @@
     >>> browser.open('/manage/users/foo/drop')
     Traceback (most recent call last):
     HTTPError: HTTP Error 404: NOT FOUND
+
+It is not possible to create an user with a duplicate username::
+
+    >>> browser.open('/manage/users/create')
+    >>> browser.getControl(name='username').value = 'u1'
+    >>> browser.getControl(name='email').value = 'u1@example.org'
+    >>> browser.getControl(name='submit').click()
+    >>> browser.url
+    'http://localhost/manage/users/create'
+    >>> browser.contents
+    '...<li>MySQL already contains an user with this username.</li>...'
+
+or with a system username::
+
+    >>> browser.getControl(name='username').value = 'root'
+    >>> browser.getControl(name='email').value = 'root@example.org'
+    >>> browser.getControl(name='submit').click()
+    >>> browser.url
+    'http://localhost/manage/users/create'
+    >>> browser.contents
+    '...<li>MySQL already contains an user with this username.</li>...'
--- a/src/ltpdarepo/user.py	Mon Jun 27 19:19:23 2011 +0200
+++ b/src/ltpdarepo/user.py	Mon Jun 27 19:31:25 2011 +0200
@@ -1,8 +1,12 @@
+from flask import g
+from wtforms import validators
+from wtforms.fields import TextField, PasswordField, BooleanField
+from wtforms.validators import ValidationError
+
 from MySQLdb.cursors import DictCursor
+
 from ltpdarepo import connection
 from ltpdarepo.form import Form
-from wtforms.fields import TextField, PasswordField, BooleanField
-from wtforms import validators
 
 
 def _generate_password():
@@ -24,6 +28,13 @@
     institution = TextField("Institution")
     admin = BooleanField("Admin")
 
+    def validate_username(form, field):
+        curs = g.db.cursor()
+        curs.execute("SELECT DISTINCT user FROM mysql.user WHERE user <> ''")
+        users = [r[0] for r in curs.fetchall()]
+        if field.data in users:
+            raise ValidationError(u"MySQL already contains an user with this username.")
+
 
 class IPassword(Form):
     password = PasswordField()