2012-10-29 153 views
2

現在我正在使用SQLAlchemyAuthenticatorPlugin的網站上工作。您需要用戶名和密碼才能登錄。 我想添加一個電子郵件和密碼的登錄。所以最終應該可以使用電子郵件/密碼或用戶名/密碼登錄。 現在它看起來是這樣的:使用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我現在能夠與電子郵件/密碼成功登錄。但當然,用戶名/密碼不再工作。 關於如何使兩個選項同時工作的任何想法?

謝謝!

回答

1

The SQLAlchemy plugins are fairly simple;你可以猴子補丁或實現你自己的插件版本,如

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) 
相關問題