Registration in Python and Cockroach

Introduction

In this tutorial we will learn how to create Registration in Python and CockroachDB for most kinds of applications, including games. We see step by step how to register a user using an HTML page pulled up by Python.

Let’s begin by building a simple registration gui using HTML to be called up with Python Flask’s render_template function.

Registration GUI in Python

Below is a registration GUI created with HTML. This will render identically in most web browsers. Name this file “input_register.html” and put it in a folder called “templates” off the root of your project folder:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<html>
    <head>
        <link rel="shortcut icon" href="favicon.ico">
        <title>Zombie Feeder Game Register</title>
    </head>
<body>
<!-- The "t_dynamic_message" you see below is part of how this page is a Flask template. -->
<!-- Because this page is "dynamic", the server can fill in data at the place-holder -->
<!-- of {{t_dynamic_message}} with the value you sent from -->
<!-- render_template("input_register.html", t_dynamic_message = "String to be shown -->
<!--   in the h1 tag below") -->
<h1>{{t_dynamic_message}}</h1>
<!-- Container DIV - open/begin -->
<div>
    <!-- Add html POSTing form for user inputs. -->
    <!-- Method=post sends the data entered by the user -->
    <!-- back to Python as a post for the Flask request -->
    <!-- function to receive. -->
    <form id='formRegistration' name='formRegistration' action='' method='post' onsubmit='return true;'>
    <!-- Input field for the user to input email address. -->
    <!-- Input has a 'name' of 't_user_email_addr'. -->
    <!-- So our Flask request function in Python will use this -->
    <!--   to specify which data from this form to retrieve. -->
    <div class="form-row">
    Email Addr: <input name="t_user_email_addr" type="text">
    </div>
    <div class="form-row">
    Password: <input name="t_user_pass" type="text">
    </div>
    <!-- button for the user to submit the form. -->
    <div>
      <input name="btnSubmitRegUser" value='Register' type="submit">
    </div>
    <!-- Close the form -->
    </form>
<!-- Container DIV - close/end -->
</div>
<!-- Close the body of the HTML. -->
</body>
</html>

Next, we will look at how we call the Flask template we created above and named “input_register.html” from Python.

Flask render_template

Flask’s Render_Template calls up the user an HTML page in their default web browser. This page can be filled with dynamic content we determine by using parameters in the render template function and placed anywhere in the HTML within curly brackets like you see we did in the H1 tag of the HTML file we built above.

1
2
3
4
# Render_template requires Flask.
from flask import Flask
from flask import render_template
return render_template("/templates/input_register.html", t_dynamic_message = "Zombie Feeder")

Flask Request Syntax

1
2
value_received = request.args.get(field_in_URL, default value) # GET, which is a querystring.
value_received = request.form.get(field_on_html_form, default value) # POST, from method=post in an HTML form.

Analysis

  • field_on_html_form and field_in_URL: These both use field name, as designated in your form POST or GET (querystring). A querystring is data added to the tail of a URL, like so: “https://adomain.com?field_name_in_URL=42”.
  • default value: If no data was sent by the user, this is the value that will be returned for value_received.

Flask Request Example

Flask examples of how the syntax will be used in applications. We’ll leave out “get” (request.args.get) for now as it has no use in our current project:

1
2
t_user_email_addr = request.form.get("t_user_email_addr", "")
t_user_pass = request.form.get("t_user_pass", "")

Analysis

  • t_user_email_addr = request.form.get(): This retrieves the value the user put into the HTML field called “t_user_email_addr” and places that value in the local Python text variable also named “t_user_email_addr”.

  • t_user_pass = request.form.get(): Same concept as the above example for t_user_email_addr.

Finally, let’s look at Python code for requesting the user-submitted email address and password.

Python request from form

We’ll begin the process by making use of the render_template function we learned to use above to send the user to the dynamic HTML template page created above and then we will request the data submitted by the new user.

1
2
3
4
5
@app.route("/registration", methods=["POST","GET"])
def registration():
    return RENDER_TEMPLATE("input_register.html", t_dynamic_message = "Pyngo Skater Registration")
    t_user_email_addr = REQUEST.form.get("t_user_email_addr", "")
    t_user_pass = REQUEST.form.get("t_user_pass", "")

Hashing for increased security

Storing a plain text password in the CockroachDB database leaves us – and especially the user – vulnerable to others who have (or hack) access to the users table. So we encrypt the password with a hash so that we can never again (and no one else can) read that password. We can only compare a hashed version at login to the hashed version in the database to know if the user logging in used the correct password. This is why any time you forgot your password on most sites, instead of showing you your password, they ask you to make a new one. This is because they can’t show you your password.

1
2
t_pass_hashed = hashlib.sha3_512(t_user_pass.encode())
t_user_pass = t_pass_hashed.hexdigest()

Analysis

  • We start with the value a new user typed into “t_user_pass” on the HTML form we built above, use the hashlib() function to “encrypt” it, and store that encrypted value as a byte in a variable we named “t_pass_hashed”.
  • We then use the hexdigest() function to convert the byte value returned by hashlib() into hex formatted data.

Insert Into CockroachDB

1
2
3
4
5
6
7
8
9
10
s = ""
s += "INSERT INTO tbl_people "
s += "("
s += " t_user_email_addr"
s += ", t_user_pass"
s += ") VALUES ("
s += " '(%t_user_email_addr)'"
s += ", '(%t_user_pass)'"
s += ")"
data_cursor.execute(s, [t_user_email_addr, t_user_pass])

Analysis: We used SQL to build a parameterized query for added security, where the parameters here are t_user_email_addr and t_user_pass, both to be added into tbl_people in our CockroachDB.

Python source

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# ----------------------
# Library imports
# ----------------------
from flask import Flask
from flask import request
from flask import render_template
import psycopg2
import hashlib

# ----------------------
# Route setup
# ----------------------
app = Flask(__name__)
@app.route("/", methods=["POST","GET"])

# ----------------------
# CockroachDB Connection
# ----------------------
import psycopg2
t_dbname = "database name"
t_name_user = "database user name"
t_sslmode = "auto"
t_sslrootcert = 'certies/ca.crt'
t_sslkey = 'certies/client.maxroach.key'
t_sslcert = 'certies/client.maxroach.crt'
t_host = "localhost"
t_port = "26251"
cdb_conn = psycopg2.connect(database=t_dbname, user=t_name_user, sslmode=t_sslmode, sslrootcert=t_sslrootcert, sslkey=t_sslkey, sslcert=t_sslcert, host=t_host, port=t_port)
cdb_cursor = cdb_conn.cursor()

# ----------------------
# Primary reg function
# ----------------------
def registration():
    return render_template("input_register.html", t_dynamic_message = "Register to play Zombie Feeder Now")
    t_user_email_addr = request.form.get("t_user_email_addr", "")
    t_user_pass = request.form.get("t_user_pass", "")

    # Make sure user didn't leave email field empty.
    if t_user_email_addr == "":
        t_dynamic_message = "You left the email field empty."
        # Send the user back to the html template with the above message.
        return render_template("input_register.html", t_dynamic_message = t_dynamic_message)
    # Make sure user password is not empty.
    if t_user_pass == "":
        t_dynamic_message = "You left the password field empty."
        # Send the user back to the html template with the above message.
        return render_template("input_register.html", t_dynamic_message = t_dynamic_message)

    # Hash-encrypt the password the user submitted.
    t_value_hashed = hashlib.sha256(t_user_pass.encode())
    t_user_pass = t_value_hashed.hexdigest()

    # Build a query for new user data insertion into CockroachDB
    s = ""
    s += "INSERT INTO tbl_people "
    s += "("
    s += " t_user_email_addr"
    s += ",t_user_pass"
    s += ") VALUES ("
    s += " '(%t_user_email_addr)'"
    s += ",'(%t_user_pass)'"
    s += ")"
    # Catch possible errors with "try" and "except" commands.
    try:
        cdb_cursor.execute(s, [t_user_email_addr, t_user_pass])
        cdb_conn.commit()
    except psycopg2.Error as e:
        t_dynamic_message = "Database error: " + e + "/n SQL: " + s
        return render_template("input_register.html", t_dynamic_message = t_dynamic_message)
    cdb_cursor.close()

Conclusion

In this tutorial we learned how to create a registration form in Python and CockroachDB for most types of applications, including games. We saw step-by-step how to register a user using an HTML page pulled up by Python and place the new user’s data into a table in our database.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.