2013-08-12 4 views
7

私はFlaskログインとプリンシパルをIDとロール管理に使用しています。私のニーズは、ドキュメントから直接説明されています。私のコードはここにある:私のログインコードでFlaskのログインとプリンシパル - current_userはログインしていても匿名です

@identity_loaded.connect_via(app) 
def on_identity_loaded(sender, identity): 
    # Set the identity user object 
    identity.user = current_user 

    # Add the UserNeed to the identity 
    if hasattr(current_user, 'get_id'): 
     print 'current_user ' + str(current_user.get_id()) 
     identity.provides.add(UserNeed(current_user.get_id)) 

    # Assuming the User model has a list of roles, update the 
    # identity with the roles that the user provides 
    if hasattr(current_user, 'roles'): 
     if current_user.roles: 
      for role in current_user.roles: 
       identity.provides.add(RoleNeed(role.name)) 

私はこれを行う:予想通りのログインに

identity_changed.send(current_app._get_current_object(), 
            identity=Identity(user.user_id) 

、信号火を。それ以降の各ページの読み込み時には、current_userは匿名であり、ユーザーIDはありませんが、@login_required関数はユーザーがログインしているかのように動作します。Flaskログインはユーザーがログインしていることを認識しますが、何らかの理由でcurrent_userが矛盾します。

どこかの重要な設定点がありませんか?

+0

Flask initで 'static_url_path = '''と何かしていますか?私は同様の問題に遭遇していた参照してください:http://stackoverflow.com/questions/16627384/flask-login-with-static-user-always-yielding-401-unauthorizedそれはセッションとログインのものが大丈夫と見えて困惑していた(ユーザーログインすることができました)しかし、私はいつも匿名のユーザーがセキュリティ保護されたエンドポイントを打つ – craigb

答えて

5

同じ問題が発生しました。根本的な原因は、Flask-LoginとFlask-Principalの両方が、Flaskのアプリケーションに登録された順番で、要求の「前処理」段階でFlaskによって呼び出されることです。 Flask-Loginを登録する前にFlask-Principalを登録すると、@login_manager.user_loaderの前に@identity_loaded.connect_via(app)が呼び出されます。したがって、current_userは匿名ユーザーを返します。

Flask-Principalのドキュメント例では、Flask-Principalがの前に登録されているa code excerptが表示されます。 Flask-Loginの前にあります。テスク!ここでは、私は私のブートストラップでやってしまったものです:

login_manager = LoginManager() 
login_manager.init_app(app) 

# ... 

principals = Principal(app) # This must be initialized after login_manager. 

その後、私のusers.pyビューファイルに:

@identity_loaded.connect_via(app) 
def on_identity_loaded(sender, identity): 
    """ This function is called by Flask-Principal after a user logs in. """ 

    identity.user = current_user 

    if isinstance(current_user, User): 
     identity.provides.add(UserNeed(current_user.id)) 

    for permission in user.permissions: 
     # Do permission-y stuff here. 

これは私のために問題を解決しました。

編集:私はドキュメントのためにプロジェクトにa bug reportを提出しました。

関連する問題