flask-security登录用户名而不是电子邮件

时间:2015-06-14 09:13:09

标签: python flask flask-security

我想让User模型中的字段通过它以用户username而不是email

登录

我定义了:
app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = 'username'

但我还是得到了:

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'

似乎电子邮件被硬编码到烧瓶安全......

我可以更改吗?

修改: 用户模型(根据评论中的要求):

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'))

3 个答案:

答案 0 :(得分:12)

使用用户名而非电子邮件地址登录(使用Flask-Security 1.7.0或更高版本),您可以将email字段替换为username字段在User模型中

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))
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime())
    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

并更新app配置。

app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = 'username'

接下来,为了允许用户使用用户名而不是电子邮件进行登录,我们将使用LoginForm validation method假定用户身份属性位于email表单字段中的事实。

from flask_security.forms import LoginForm
from wtforms import StringField
from wtforms.validators import InputRequired

class ExtendedLoginForm(LoginForm):
    email = StringField('Username', [InputRequired()])

# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore,
                    login_form=ExtendedLoginForm)

这样,我们可以使用用户名登录而无需重写验证方法或登录模板。当然,这是一个hack,更正确的方法是添加一个自定义validate方法,它检查username表单字段,ExtendedLoginForm类并更新登录模板相应

但是,上述方法可以轻松使用用户名或电子邮件地址登录。为此,请使用用户名和电子邮件字段定义用户模型。

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

并更新app配置。

app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = ('username','email')

最后,创建自定义登录表单。

from flask_security.forms import LoginForm
from wtforms import StringField
from wtforms.validators import InputRequired

class ExtendedLoginForm(LoginForm):
    email = StringField('Username or Email Address', [InputRequired()])

# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore,
                    login_form=ExtendedLoginForm)

现在,登录时,Flask-Security将在电子邮件表单字段中接受电子邮件或用户名。

答案 1 :(得分:1)

来自https://pythonhosted.org/Flask-Security/models.html

字段id, email, password, active是必不可少的。添加

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

只需在此处添加自定义username字段。

答案 2 :(得分:1)

我设法通过覆盖登录表单来使用用户名或密码来实现登录:

class ExtendedLoginForm(LoginForm):
    email = StringField('Username or Email Address')
    username = StringField("Username")

    def validate(self):
    from flask_security.utils import (
        _datastore,
        get_message,
        hash_password,
    )
    from flask_security.confirmable import requires_confirmation
    if not super(LoginForm, self).validate():
        return False

    # try login using email
    self.user = _datastore.get_user(self.email.data)

    if self.user is None:
        self.user = _datastore.get_user(self.username.data)

    if self.user is None:
        self.email.errors.append(get_message("USER_DOES_NOT_EXIST")[0])
        # Reduce timing variation between existing and non-existing users
        hash_password(self.password.data)
        return False
    if not self.user.password:
        self.password.errors.append(get_message("PASSWORD_NOT_SET")[0])
        # Reduce timing variation between existing and non-existing users
        hash_password(self.password.data)
        return False
    if not self.user.verify_and_update_password(self.password.data):
        self.password.errors.append(get_message("INVALID_PASSWORD")[0])
        return False
    if requires_confirmation(self.user):
        self.email.errors.append(get_message("CONFIRMATION_REQUIRED")[0])
        return False
    if not self.user.is_active:
        self.email.errors.append(get_message("DISABLED_ACCOUNT")[0])
        return False
    return True

并按照其他帖子中的说明进行注册:

# Setup Flask-Security
app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = ('username','email')
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore,
                login_form=ExtendedLoginForm)

由于电子邮件和用户名是可选的,现在可以使用其中之一登录。但是请确保在数据库模型中两个字段都设置为唯一。