如何阻止用户访问管理页面?

时间:2016-12-18 23:51:37

标签: flask flask-admin

我想阻止用户访问管理网址,我已经保护了视图,但仍然可以访问 / admin /

admin.py

import os

from flask import request, redirect, url_for
from werkzeug import secure_filename

from flask_admin import Admin, AdminIndexView
from flask_admin import BaseView, expose
from flask_admin.contrib.sqla import ModelView
from flask_admin.contrib.fileadmin import FileAdmin

from flask_login import current_user,login_required

from develop.extentions import admin_permission

from wtforms import FileField

class AdminIndex(AdminIndexView):
    @expose('/admin/')
    def index(self):
        if not current_user.is_authenticated:
            return redirect(url_for('main.index'))
        return self.render('admin/home.html')

    def is_accessible(self):
        return current_user.roles('admin')

class CustomModelView(ModelView):
    def is_accessible(self):
        return current_user.is_authenticated and admin_permission.can
    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for('main.index', next=request.url))

class CustomFileView(FileAdmin):

    allowed_extensions = (
        'txt',
        'md',
        'js',
        'css',
        'html',
        'jpg',
        'gif',
        'png'
    )

    editable_extensions = ('md','html','js','css','txt')

    def is_accessible(self):
        return current_user.is_authenticated and admin_permission.can

class UserView(CustomModelView):
    column_list = ('username', 'confirmed','joined')

    column_searchable_list = ('username', 'id')
    column_filters = ('joined', 'email', 'username')

    path = os.path.abspath(
        os.path.join(
            os.path.dirname(__file__),
            os.pardir
        )
    )

    form_extra_fields = {
        "image": FileField('Image')
    }

    def on_model_change(self, form, model, is_created):
        path = os.path.abspath(
            os.path.join(
                os.path.dirname(__file__),
                os.pardir
            )
        )

        image_path = os.path.join(path, 'static', 'images')
        photo_data = request.files.get(form.image.name)

        if photo_data:
            name = secure_filename(photo_data.filename)
            model.image = '/static/images/' + name
            photo_data.save(os.path.join(image_path, name))

通过这种方式,我隐藏了所有其他视图,但我仍然访问管理页面,请如何防止未经身份验证的用户访问管理员

1 个答案:

答案 0 :(得分:0)

index功能中处理您的身份验证检查,如果未经过身份验证,请进行重定向。

@expose('/')
def index(self):
    if not current_user.is_authenticated:
        return redirect(url_for('main.index'))
    return self.render('admin/home.html')