How to prevent users from accessing Admin Page?

1.3k views Asked by At

I want to prevent the users from accessing the admin url, i already secured the views but /admin/ is still accessible .

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))

By this way, all my other views are hidden but i still accessing the admin page , please how to prevent unauthenticated user from even accessing the admin .

1

There are 1 answers

2
MrLeeh On

Handle your check for authentication in your index function and make a redirect if not authenticated.

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