2017-03-05 16 views
0

私は多くのソリューションをオンラインで見てきましたが、それらのすべてが外部ユーザーがアカウントを作成できるようにするより複雑なアプリケーションに対処しました。私の場合、唯一のユーザーは管理者になります。 Flask-Adminによって作成された/ adminルートを効率的に保護するにはどうすればよいですか?私の唯一のユーザーが管理者になる場合、Flask-Adminを保護する方法は?

答えて

1

これにはFlask-Loginを使用できます。私は通常、ユーザーがまだログインしていない場合、ログインを処理するAdminIndexViewクラスへのルートを追加します。それ以外の場合は、デフォルトの管理ページが表示されます。

from flask import Flask 
from flask_login import LoginManager 
from flask_admin import Admin 


app = Flask(__name__) 

login_manager = LoginManager(app) 
login_manager.session_protection = 'strong' 
login_manager.login_view = 'admin.login' 

admin = Admin(app, index_view=MyIndexView()) 

MyAdminViewの定義は次のようになります

from flask_admin import AdminIndexView, expose, helpers 


class FlaskyAdminIndexView(AdminIndexView): 

    @expose('/') 
    def index(self): 
     if not login.current_user.is_authenticated: 
      return redirect(url_for('.login')) 
     return super(MyAdminIndexView, self).index() 

    @expose('/login', methods=['GET', 'POST']) 
    def login(self): 
     form = LoginForm(request.form) 
     if helpers.validate_form_on_submit(form): 
      user = form.get_user() 
      if user is not None and user.verify_password(form.password.data): 
       login.login_user(user) 
      else: 
       flash('Invalid username or password.') 
     if login.current_user.is_authenticated: 
      return redirect(url_for('.index')) 
     self._template_args['form'] = form 
     return super(MyAdminIndexView, self).index() 

    @expose('/logout') 
    @login_required 
    def logout(self): 
     login.logout_user() 
     return redirect(url_for('.login')) 

これはフラスコ-管理インタフェースで控えめフラスコ-ログインを統合しています。 Flask-Login documentationに記載されているように、ユーザーとパスワードの検証を実装する必要があります。あなたの管理者ルートへの不正アクセスを防止するために

EDIT

ビューごとにModelViewクラスを作成し、次のコードで機能is_accessible()を追加します。

def is_accessible(self): 
    if (not login.current_user.is_active or not 
      login.current_user.is_authenticated): 
     return False 
    return True 
関連する問題