I.T. Security and Linux Administration

Sep 30 2013   2:59PM GMT

Create Your Own Two-Factor Authentication System: Creating the Database



Posted by: Eric Hansen
Tags:
security

Lets figure out what we need to make this magical wonderland happen.  We need a user’s phone number, a field to state if the phone is usable or not (if we should concern ourselves with requests from it) and storage for the active token.  If we want to make it more advanced than we will but for now this is good.  So we will use two tables: phone and tokens.  The token will be based on the phone number and current timestamp as sort of a salt (not the safest but again, template for the future ;) ).

Phone Table

id – primary key

digits – small integer (15-digit number)

Tokens Table

id – primary key

token – variable char (length 0f 10)

phone_id – foreign key to phone->id

Simple, eh?  Now lets create it in Python!

from peewee import *

database = SqliteDatabase(“2fa.db”)

We import everything of the Peewee library to make things easier on us. We also specify we want a SQLite database.

class ABC(Model):
class Meta:
database = database

We create an abstract base class (ABC) so everything can share the database instance. This is mostly done to save typing.

class Phone(ABC):
id = PrimaryKeyField()
digits = IntegerField()

class Tokens(ABC):
id = PrimaryKeyField()
token = CharField(max_length=10)
phone = ForeignKeyField(Phone)

Specify the table structure of the phone and tokens tables, subclassing the mentioned ABC class.

phone = Phone
tokens = Tokens

Easy references for the tables (which will be needed quite a bit).

database.connect()

Connect/load the SQLite database.

try:
phone.create_table()
tokens.create_table()
except:
pass

Create the tables in the SQLite file.

Save the above code fragments to a file called “db.py” (otherwise make the adjustments in later parts). Now we have the database laid out properly and easy to work with!

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: