[FIXED] flask-security login via username and not email

Issue

I wanted to have the field in User model that through it the user logs in as username instead of email

I defined:
app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = 'username'

But I’m still getting:

user_datastore.add_role_to_user(name, 'mgmt')
      File "/Users/boazin/sentinal/sentinel-cloud/.env/lib/python2.7/site-packages/flask_security/datastore.py", line 105, in add_role_to_user
        user, role = self._prepare_role_modify_args(user, role)
      File "/Users/boazin/sentinal/sentinel-cloud/.env/lib/python2.7/site-packages/flask_security/datastore.py", line 72, in _prepare_role_modify_args
        user = self.find_user(email=user)
      File "/Users/boazin/sentinal/sentinel-cloud/.env/lib/python2.7/site-packages/flask_security/datastore.py", line 203, in find_user
        return self.user_model.query.filter_by(**kwargs).first()
      File "/Users/boazin/sentinal/sentinel-cloud/.env/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 1333, in filter_by
        for key, value in kwargs.items()]
      File "/Users/boazin/sentinal/sentinel-cloud/.env/lib/python2.7/site-packages/sqlalchemy/orm/base.py", line 383, in _entity_descriptor
        (description, key)
    InvalidRequestError: Entity '<class 'flask_app.models.User'>' has no property 'email'

It seems that email is hardcoded into flask-security…

Can I change it?

edit:
The User Model (as requested in the comment):

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(255), unique=True, index=True)
    password = db.Column(db.String(255))
    token = db.Column(db.String(255), unique=True, index=True)
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime())
    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

Solution

From https://pythonhosted.org/Flask-Security/models.html

Fields id, email, password, active is essential.So add

email = db.Column(db.String(255), unique=True)

Just add your custom username field along this.

Answered By – itzMEonTV

Answer Checked By – Terry (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published