CSc 250: Lecture Notes: Password Rules with re

Creating a Username and Password

At some point or another, all of use have had to create a username and password. Many types of application require a username and password to be selected - from operating systems to work applications to websites. Often, these applications have rules about what constitutes a valid username and password. A user can only create an account if the rules are adhered to. A typical set of rules looks something like this:

These rules are created and enforced to keep users from using usernames and passwords that are easy to guess. This helps to improve the overall security of using a given website or application.

In this lecture, I’ll cover how to write an application that enforces such rules using regular expressions!

The Existing Application

Below are links to several files that compose an application with a basic username/password login scheme.

create-account-app.py

This component of the application gives a user the ability to create a new username and password combination. Once the username and password are selected, the pair is saved into a database so the user can be looked up when they attempt to log in.

login-app.py

This program serves as the one users will login with. It accepts a username and password, and checks the database to see if it exists. If so, the user may log in.

The application database file

This is the sqlite3 database that both of these applications connect to.

Notice that the application does absolutely zero checking for expected/valid username and password input. We will modify this program to do validation.

The Regular Expressions

Each of the rules for usernames and passwords can both be represented with a regular expression.

For the username:

For the password:

We can use each of these regular expression to ensure that the user follows the rules of account creation.

The Code

Knowing the regular expressions that must be used, let’s head to our code editor and modify these program(s) to do better validation.

The solutions are linked below, but don’t look until you’ve attempted this on your own!

create-account-re-app.py