I am working with Flask and MongoDB, trying to implement username / password verification with passlib.
The class from models.py :
from passlib.hash import sha256_crypt
class Users(object):
def __init__(self, username='', password='', collection=db.users, articles=''):
self.collection = collection
self.username = username
self.password = password
self.articles = []
def addUser(self):
self.collection.insert({'username': self.username, 'password': sha256_crypt.encrypt('self.password'), 'articles': self.articles})
From the python shell, I create the user alice with the password 'secret' :
>>> import models
>>> alice = models.Users()
>>> alice.username = 'alice'
>>> alice.password = 'secret'
>>> alice.addUser()
From the mongo shell, I check that the document has been well created with a hash instead of the clear password :
> db.users.find()
{ "_id" : ObjectId("57f15d9f815a0b6c1533427f"), "username" : "alice", "articles" : [ ], "password" : "$5$rounds=535000$Oq1hy1INzO59nu0q$FzMz1DtBWDwM.sw0AhrlVA8esgE30n8rr/NjOltB8.7" }
From now on, we should be able to verify the password from the python shell using the hash stored in the document, isn't it ?
>>> sha256_crypt.verify('secret','$5$rounds=535000$Oq1hy1INzO59nu0q$FzMz1DtBWDwM.sw0AhrlVA8esgE30n8rr/NjOltB8.7')
False
But it doesn't, someone can explain to me why ?
That is happening because you're encrypting not self.password
but 'self.password'
So you need to change your addUser
method to the following:
def addUser(self):
self.collection.insert({'username': self.username, 'password': sha256_crypt.encrypt(self.password), 'articles': self.articles})