Reputation: 262
hello i have a problem with my /admin route in my flask app when anyone can see mywesite/admin page they dont have access to admin methods but they can see the page i try to do this with the code blow But i still have the problem :
from flask_admin import expose, BaseView
from flask_admin.contrib.sqla import ModelView
from flask_login import current_user
from flask import abort
class CustomView(BaseView):
@expose('/')
def index(self):
if current_user.is_authenticated and current_user.is_admin:
return self.render('admin/index.html')
else:
return abort(403)
def is_accessible(self):
return current_user.is_authenticated and current_user.is_admin
def is_visible(self):
return current_user.is_authenticated and current_user.is_admin
class CustomModelView(ModelView):
def is_accessible(self):
return current_user.is_authenticated and current_user.is_admin
class UserView(CustomModelView):
column_list = ('username', 'active', 'email')
def is_accessible(self):
return current_user.is_authenticated and current_user.is_admin
in my main app file i have this :
from flask import Flask
from .extentions import db, ckeditor, mail, migrate, bootstrap, user_login_manager,
basic_auth
from flask_admin import Admin
def create_app():
application = Flask(__name__)
application.config.from_object(Config)
db.init_app(application)
bootstrap.init_app(application)
ckeditor.init_app(application)
mail.init_app(application)
migrate.init_app(application, db)
basic_auth.init_app(application)
return application
app = create_app()
admin = Admin(app)
admin.add_view(CustomView(name='My View', menu_icon_type='glyph',
menu_icon_value='glyphicon-home'))
admin.add_view(UserView(User, db.session))
@app.route('/admin')
@admin_only
@login_required
def admin_index():
return render_template('admin/index.html')
please tell me where is my problem on how can i fix this thank you so much
Upvotes: 0
Views: 54
Reputation: 262
i find my answer and i post it here maybe help someone
i create a MyHomeView class and inherit from AdminIndexView:
from flask_admin import expose, BaseView, AdminIndexView
class MyHomeView(AdminIndexView):
@expose('/')
def index(self):
new_cafe = db.session.query(NewCafe).all()
new_users = db.session.query(NewUser).all()
new_subs = db.session.query(NewSubscriber).all()
count = db.session.query(NewCount).first()
# check current user is admin and authenticated
if current_user.is_authenticated and current_user.is_admin:
return self.render('admin/index.html',
new_cafe=new_cafe,
new_users=new_users,
new_subs=new_subs,
count=count)
else:
return abort(403)
and in the main file when i create a admin from Admin i pass the MyhomeView class as index_view like this :
from flask_admin import Admin
from app.admin_views.admin_page import MyHomeView
admin = Admin(app, index_view=MyHomeView(), template_mode='bootstrap4')
with this method not admin users when try to access my /admin view get 403 Error You can Replace this With any Error You Want
Upvotes: 0