2013-08-12 2 views
7

저는 Flask Login 및 Principal을 사용하여 ID 및 역할 관리를하고 있습니다. 내 요구는 문서에서 바로 설명됩니다. 내 코드는 여기에 있습니다 : 내 로그인 코드에서플라스크 로그인 및 프린시 펄 - 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 문서 예는 a code excerpt이며 Flask-Principal은 으로 등록되어 있습니다. 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을 제출했습니다.

관련 문제