Search code examples
pythonflask-admin

Flask-Admin with Custom Security


I'm new to Flask-Admin and I was able to implement it to my app. Everything is working fine. Admin views are set and they can display and create/delete data.

When I look for the security options I see that I can roll my own. But it shows a class based view example (mine is function based) and requires to use Flask-Login. I don't want to use that. I already have authorization check for the necessary paths like the following;

def login_required(something):
    @wraps(something)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return test(*args, **kwargs)
        else:
            return redirect(url_for('main.login'))

    return wrap


@main_blueprint.route('/')
@login_required
def index():
    form = MessageForm(request.form)
    return render_template('index.html', form=form)


@main_blueprint.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    form = LoginForm(request.form)

    if request.method == 'POST':
        if form.validate_on_submit():
            user = User.query.filter_by(name=request.form['name']).first()
            if user is not None and bcrypt.check_password_hash(user.password, request.form['password']):
                session['logged_in'] = True
                session['user_id'] = user.id
                session['role'] = user.role
                session['user'] = user.name
                flash('Welcome')

                return redirect(url_for('main.index'))
            else:
                error = 'Invalid Username or Password.'
                flash('Invalid Username/Password Combination')
    return render_template('login.html', form=form, error=error)

I've tried to do to do the following

@main_blueprint.route('/admin')
@login_required
def admin():
    return render_template('admin/master.html')

But obviously that's not working.

How can I implement my own security to the Flask-Admin paths without using Flask-Login or Flask-Security or any other additional modules??


Solution

  • I think I found my answer. With the help of https://danidee10.github.io/2016/11/14/flask-by-example-7.html I was able to implement it to my app.

    class AdminView(sqla.ModelView):
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.static_folder = 'static'
    
        def is_accessible(self):
            return session.get('role') == 'admin'
    
        def inaccessible_callback(self, name, **kwargs):
            if not self.is_accessible():
                return redirect(url_for('main.login', next=request.url))
    

    and changed admin = Admin(app) to:

    admin = Admin(app, name='Dashboard', index_view=AdminView(User, db.session, url='/admin', endpoint='admin'))