Skip to content

Commit

Permalink
Improve user password hashes handling
Browse files Browse the repository at this point in the history
  • Loading branch information
karec committed Oct 30, 2020
1 parent d2441a2 commit c71b8ca
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
7 changes: 6 additions & 1 deletion {{cookiecutter.project_name}}/tests/test_user.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from flask import url_for

from {{cookiecutter.app_name}}.extensions import pwd_context
from {{cookiecutter.app_name}}.models import User


Expand Down Expand Up @@ -31,7 +33,7 @@ def test_put_user(client, db, user, admin_headers):
db.session.add(user)
db.session.commit()

data = {"username": "updated"}
data = {"username": "updated", "password": "new_password"}

user_url = url_for('api.user_by_id', user_id=user.id)
# test update user
Expand All @@ -43,6 +45,9 @@ def test_put_user(client, db, user, admin_headers):
assert data["email"] == user.email
assert data["active"] == user.active

db.session.refresh(user)
assert pwd_context.verify("new_password", user.password)


def test_delete_user(client, db, user, admin_headers):
# test 404
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ class Meta:
model = User
sqla_session = db.session
load_instance = True
exclude = ("_password",)
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from sqlalchemy.ext.hybrid import hybrid_property

from {{cookiecutter.app_name}}.extensions import db, pwd_context


Expand All @@ -8,12 +10,16 @@ class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(255), nullable=False)
_password = db.Column("password", db.String(255), nullable=False)
active = db.Column(db.Boolean, default=True)

def __init__(self, **kwargs):
super(User, self).__init__(**kwargs)
self.password = pwd_context.hash(self.password)
@hybrid_property
def password(self):
return self._password

@password.setter
def password(self, value):
self._password = pwd_context.hash(value)

def __repr__(self):
return "<User %s>" % self.username

0 comments on commit c71b8ca

Please sign in to comment.