I'm trying to implement flask-login in my application which uses flask-mongoengine too. Here is my user proto:
class User(db.Document, UserMixin):
username = db.StringField(max_length=80)
email = db.StringField(max_length=255, unique=True)
password = db.StringField(max_length=255, required=True)
active = db.BooleanField(default=True)
def __init__(self, *args, **kwargs):
super(db.Document, self).__init__(self)
try:
self.username = kwargs['username']
self.email = kwargs['email']
self.password = kwargs['password']
except:
flash('Bad arguments for User')
@staticmethod
def salt_password(password):
return generate_password_hash(password)
@property
def is_authenticated(self):
return True
@property
def is_active(self):
return self.active
@property
def is_anonymous(self):
return False
def get_id(self):
return unicode(self._id)
def __repr__(self):
return '<User %r>' % (self.username)
def check_pwd(self, password):
return check_password_hash(self.password, password)
However, when I call the login_user(user)
function from my login view, it calls the get_id
method of the User
, but self._id
returns None
. I also tried self.id
with the same result. Then, I tried to add the _id
field explicitely :
class User(db.Document, UserMixin):
_id = db.ObjectIdField(default=bson.ObjectId())
but then, self._id
gives me 'User u'username'>
instead of the user id.
Any idea of how to retrieve the _id
of a user ?
I found a workaround for this issue. My User prototype is updated as follow, using pymongo :
def get_id(self):
user_queried = self._get_collection().find_one({'username':self.username, 'email':self.email, 'password':self.password})
if user_queried is not None:
return unicode(user_queried['_id'])
else:
return 'None'
Though I don't know if an answer to your problem is still needed - you found a solution for you and your question is old. But if someone else comes around i solved it with the following code:
from mongoengine import Document, StringField, FloatField, BooleanField
class User(Document):
name = StringField(primary_key=True, required=True, max_length=50)
mail = StringField(required=True, max_length=255)
password = StringField(required=True, max_length=80)
first_name = StringField(max_length=255)
second_name = StringField(max_length=255)
authenticated = True # BooleanField(required=True, default=True)
is_active = True # BooleanField(required=True, default=True)
meta = {'db_alias': 'users'}
@property
def is_authenticated(self):
return True
@property
def is_active(self):
return True
@property
def is_anonymous(self):
return False
def get_id(self):
return self.name
and added the following user_loader
@login_manager.user_loader
def load_user(user_id):
user = User.objects(name=user_id)[0]
return user
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.