← flask-blog

password hash

0c13b8c873a9049869336fc9c6442ecf4fffac8e · ovidiucs · May 15, 2015 21:41

+25 −1 · 1 file changed

  • flask-blog.py +25 −1
diff --git a/flask-blog.py b/flask-blog.py
index 9cadf5a..50cae2d 100644
--- a/flask-blog.py
+++ b/flask-blog.py
@@ -11,6 +11,10 @@ from flask.ext.sqlalchemy import SQLAlchemy
 
 
 app = Flask(__name__)
+
+# The SECRET_KEY field in the app config is used by WTForms to create CSRF tokens.
+# It is also used by itsdangerous (included in Flask) to sign cookies and other data.
+
 app.config['SECRET_KEY'] = 'top secret!'
 # where the db is
 app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.sqlite3'
@@ -39,13 +43,33 @@ class UploadForm(Form):
 # Define a class that represents our users in the database
 # This class inherits from  a base model classes
 # Models > Classes > Associated with entities within a database.
-
+# The hardest part was finding the right SQLAlchemy data types and picking a
+# length for our String fields in the database. Using our models is also extremely
+# simple, thanks to the SQLAlchemy query syntax
 
 class User(db.Model):
     __tablename__ = 'users'
     id = db.Column(db.Integer, primary_key=True)
     name = db.Column(db.String(16), index=True, unique=True)
 
+    username = db.Column(db.String(16), index=True, unique=True)
+    password_hash = db.Column(db.String(64))
+
+    def set_password(self, password):
+        self.password_hash = generate_password_hash(password)
+
+    def verify_password(self, password):
+        return check_password_hash(self.password_hash, password)
+
+    @staticmethod
+    def register(username, password):
+        user = User(username=username)
+        user.set_password(password)
+        db.session.add(user)
+        db.session.commit()
+        return user
+
+
     def __repr__(self):
         return '<User {0}>'.format(self.name)