2

现在我正在一个使用 SQLAlchemyAuthenticatorPlugin 的网站上工作。您需要用户名和密码才能登录。我想添加一个带有电子邮件和密码的登录名。所以最后应该可以使用电子邮件/密码或用户名/密码登录。现在它看起来像这样:

sqlauth = SQLAlchemyAuthenticatorPlugin(model.User, model.meta.Session)
sqlauth.translations['user_name'] = 'email'
sql_user_md = SQLAlchemyUserMDPlugin(model.User, model.meta.Session)
sql_user_md.translations['user_name'] = 'email'

使用 sqlauth.translations,我现在可以使用电子邮件/密码成功登录。但是当然用户名/密码不再起作用了。关于如何使这两个选项同时起作用的任何想法?

谢谢!

4

1 回答 1

1

SQLAlchemy插件相当简单;您可以对其进行猴子补丁或实现您自己的插件版本,例如

from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
import repoze.who.plugins.sa
class _EmailBaseSQLAlchemyPlugin(object)
    default_translations = {'user_name': "user_name", 'email': 'email',
                            'validate_password': 'validate_password'}

    def get_user(self, login):
        login_type = 'email' if '@' in login else 'user_name'
        login_attr = getattr(self.user_class, self.translations[login_type])
        query = self.dbsession.query(self.user_class)
        query = query.filter(login_attr == login)

        try:
            return query.one()
        except (NoResultFound, MultipleResultsFound):
            # As recommended in the docs for repoze.who, it's important to
            # verify that there's only _one_ matching userid.
            return None

class EmailSQLAlchemyAuthenticatorPlugin(_EmailBaseSQLAlchemyPlugin,
          repoze.who.plugins.sa.SQLAlchemyAuthenticatorPlugin):
    pass
class EmailSQLAlchemyUserMDPlugin(_EmailBaseSQLAlchemyPlugin,
          repoze.who.plugins.sa.SQLAlchemyUserMDPlugin):
    pass

sqlauth = EmailSQLAlchemyAuthenticatorPlugin(model.User, model.meta.Session)
sql_user_md = SQLAlchemyUserMDPlugin(model.User, model.meta.Session)
于 2012-10-29T15:03:52.383 回答