safer check for existing user in tutorial
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Angeline · committed by David Lord · parent 50b7dcb · Browse files · 2 files·+45 added−41 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: David Lord <davidism@gmail.com>
Diff stats
2 files+45 added−41 removed
- other:+45 added−41 removed
Provenance
- Commit
5119657- Tree
ebbdd4b- Author
Angeline <36949679+awijaya22@users.noreply.github.com>- Committer
David Lord <davidism@gmail.com>- Parent
50b7dcb
2 files changed+45 added−41 removed
modified:docs/tutorial/views.rst+32 added-28 removed
89 unmodified lines90 if not username:91 error = 'Username is required.'92 elif not password:93 error = 'Password is required.'94- elif db.execute(95- 'SELECT id FROM user WHERE username = ?', (username,)96- ).fetchone() is not None:97- error = f"User {username} is already registered."94 95 if error is None:96+ try:100- db.execute(101- 'INSERT INTO user (username, password) VALUES (?, ?)',102- (username, generate_password_hash(password))103- )104- db.commit()105- return redirect(url_for('auth.login'))97+ db.execute(98+ "INSERT INTO user (username, password) VALUES (?, ?)",99+ (username, generate_password_hash(password)),100+ )101+ db.commit()102+ except db.IntegrityError:103+ error = f"User {username} is already registered."104+ else:105+ return redirect(url_for("auth.login"))106 107 flash(error)108 109 return render_template('auth/register.html')14 unmodified lines124 input their ``username`` and ``password``.125 126 #. Validate that ``username`` and ``password`` are not empty.127 128-#. Validate that ``username`` is not already registered by querying the129- database and checking if a result is returned.130- :meth:`db.execute <sqlite3.Connection.execute>` takes a SQL query131- with ``?`` placeholders for any user input, and a tuple of values132- to replace the placeholders with. The database library will take133- care of escaping the values so you are not vulnerable to a134- *SQL injection attack*.128+#. If validation succeeds, insert the new user data into the database.129 136- :meth:`~sqlite3.Cursor.fetchone` returns one row from the query.137- If the query returned no results, it returns ``None``. Later,138- :meth:`~sqlite3.Cursor.fetchall` is used, which returns a list of139- all results.130+ - :meth:`db.execute <sqlite3.Connection.execute>` takes a SQL131+ query with ``?`` placeholders for any user input, and a tuple of132+ values to replace the placeholders with. The database library133+ will take care of escaping the values so you are not vulnerable134+ to a *SQL injection attack*.135 141-#. If validation succeeds, insert the new user data into the database.142- For security, passwords should never be stored in the database143- directly. Instead,144- :func:`~werkzeug.security.generate_password_hash` is used to145- securely hash the password, and that hash is stored. Since this146- query modifies data, :meth:`db.commit() <sqlite3.Connection.commit>`147- needs to be called afterwards to save the changes.136+ - For security, passwords should never be stored in the database137+ directly. Instead,138+ :func:`~werkzeug.security.generate_password_hash` is used to139+ securely hash the password, and that hash is stored. Since this140+ query modifies data,141+ :meth:`db.commit() <sqlite3.Connection.commit>` needs to be142+ called afterwards to save the changes.143 144+ - An :exc:`sqlite3.IntegrityError` will occur if the username145+ already exists, which should be shown to the user as another146+ validation error.147+148 #. After storing the user, they are redirected to the login page.149 :func:`url_for` generates the URL for the login view based on its150 name. This is preferable to writing the URL directly as it allows151 you to change the URL later without changing all code that links to46 unmodified lines198 There are a few differences from the ``register`` view:199 200 #. The user is queried first and stored in a variable for later use.201 202+ :meth:`~sqlite3.Cursor.fetchone` returns one row from the query.203+ If the query returned no results, it returns ``None``. Later,204+ :meth:`~sqlite3.Cursor.fetchall` will be used, which returns a list205+ of all results.206+207 #. :func:`~werkzeug.security.check_password_hash` hashes the submitted208 password in the same way as the stored hash and securely compares209 them. If they match, the password is valid.210 95 unmodified linesmodified:examples/tutorial/flaskr/auth.py+13 added-13 removed
58 unmodified lines59 if not username:60 error = "Username is required."61 elif not password:62 error = "Password is required."63- elif (64- db.execute("SELECT id FROM user WHERE username = ?", (username,)).fetchone()65- is not None66- ):67- error = f"User {username} is already registered."63 64 if error is None:70- # the name is available, store it in the database and go to71- # the login page72- db.execute(73- "INSERT INTO user (username, password) VALUES (?, ?)",74- (username, generate_password_hash(password)),75- )76- db.commit()77- return redirect(url_for("auth.login"))65+ try:66+ db.execute(67+ "INSERT INTO user (username, password) VALUES (?, ?)",68+ (username, generate_password_hash(password)),69+ )70+ db.commit()71+ except db.IntegrityError:72+ # The username was already taken, which caused the73+ # commit to fail. Show a validation error.74+ error = f"User {username} is already registered."75+ else:76+ # Success, go to the login page.77+ return redirect(url_for("auth.login"))78 79 flash(error)80 81 return render_template("auth/register.html")35 unmodified lines