In this post, I am going to start teasing apart Finance from CS50 problem set 7. Now, this is going to be another one that is too long for a single post. So, I will be separating it out into parts. This week we will tackle part 1, where we will implement register. This function will allow a user to register by setting a username and password. Let’s get started.
To start, I am going to cover how we implement register.html. You will notice that we are using the Jinja template language so that the page will look the same across the site. Get used to using the extends, block title, and block main, as you will use these for every html page we write in this problem set. Now, we want to create a form for the user to register. The form below is submitted using the post method. Next, we create three inputs for the user to input their name, a password, and a password confirmation. The last item is a button that will submit the form, which will call our register function in our Python document.
Below is the implementation of the register function that will execute when the submit button is clicked on our form. The first thing we want to do is make sure that the user landed on the page via post method. If not, we will redirect them to the register.html page. The next three if statements are for input validation. The first makes sure that the user has entered something into the username field. The second makes sure that a user has typed in their password twice. And the third makes sure that both passwords match.
Now that we have validated that the user has typed something in all the fields, the next step is to hash the password. This will make sure that no one, including us, will know the users password. The next statement enters the username and password into our database of registered users. Remember that we want to use the :username and :hash notation to avoid a SQL injection attack. Since the username field in the database in UNIQUE, if the username already exists nothing will be stored in result. If, however, the username doesn’t exist, the primary key (or id) will be stored in the result. Thus, we can set the current user_id to the result, and redirect the user to the home page (index).
And that is all there is to registering a user. Please comment below with any questions, and feel free to click the buttons below to share on your favorite social media site. As always…Happy Programming!!