关于python:Flask-Admin基于角色的访问 – 根据角色修改访问权限

Flask-Admin Role Based Access - Modify access based on role

我从这里取了flask admin auth示例,并对其进行了轻微的更改。

我在下面的视图中添加了以下块,但它没有显示导出按钮。我期望它将导出选项添加到管理视图中。它确实将---superuser打印到控制台。

1
2
3
        if current_user.has_role('superuser'):
            can_export = True
            print ' ---- superuser '

我以前用过很多次导出功能。如果我将语句can_export = True放在class MyModelView(sqla.ModelView):的正下方,它将起作用。我将此作为控制基于用户角色创建/编辑等访问的示例。例如,我希望有一个只读角色,其中可以创建=false、编辑=false等。

有人能帮忙吗?有人能告诉我我做错了什么吗?

==

这是整个视图。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Create customized model view class
class MyModelView(sqla.ModelView):

    def is_accessible(self):
        if not current_user.is_active or not current_user.is_authenticated:
            return False

        if current_user.has_role('superuser'):
            return True

        return False

    def _handle_view(self, name, **kwargs):
       """
        Override builtin _handle_view in order to redirect users when a view is not accessible.
       """

        if current_user.has_role('superuser'):
            can_export = True
            print ' ---- superuser '

        if not self.is_accessible():
            if current_user.is_authenticated:
                # permission denied
                abort(403)
            else:
                # login
                return redirect(url_for('security.login', next=request.url))

==

作为参考:我把所有代码放在这里。


为了进一步扩展,我从上面继续使用auth示例作为基础,并添加了一些简单的基于角色的访问控制。我希望这能对某人有所帮助。

完整代码在这里。如果你在这里看到一些不好的RBAC实践,我想听听。

app.py的主要文件是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import os
from flask import Flask, url_for, redirect, render_template, request, abort
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, \
    UserMixin, RoleMixin, login_required, current_user
from flask_security.utils import encrypt_password
import flask_admin
from flask_admin.contrib import sqla
from flask_admin import helpers as admin_helpers

# Create Flask application
app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Define models directly without reflection...
class Customer(db.Model):
    CustomerId = db.Column(db.Integer(), primary_key=True)
    FirstName = db.Column(db.Unicode(40), nullable=False)
    LastName = db.Column(db.String(20), nullable=False)
    City = db.Column(db.Unicode(40))
    Email = db.Column(db.Unicode(60), unique = True)

    def __str__(self):
        return self.CustomerID

class City(db.Model):
    Id = db.Column(db.Integer(), primary_key=True)
    City = db.Column(db.Unicode(40), unique = True)

    def __str__(self):
        return self.ID

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# Define models
roles_users = db.Table(
    'roles_users',
    db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
    db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
)

class Role(db.Model, RoleMixin):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

    def __str__(self):
        return self.name

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(255))
    last_name = db.Column(db.String(255))
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime())
    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

    def __str__(self):
        return self.email

# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)

# Flask views
@app.route('/')
def index():
    return render_template('index.html')


# Create customized model view class
class dgBaseView(sqla.ModelView):

    column_display_pk = True
    page_size = 20
    can_view_details = True
    #can_export = False
    can_export = True

    def _handle_view(self, name, **kwargs):
       """
        Override builtin _handle_view in order to redirect users when a view is not accessible.
       """

        if not self.is_accessible():
            if current_user.is_authenticated:
                # permission denied
                abort(403)
            else:
                # login
                return redirect(url_for('security.login', next=request.url))

class regularRbacView(dgBaseView):

    def is_accessible(self):

        # set accessibility...
        if not current_user.is_active or not current_user.is_authenticated:
            return False

        # roles not tied to ascending permissions...
        if  not current_user.has_role('export'):
            self.can_export = False

        # roles with ascending permissions...
        if current_user.has_role('adminrole'):
            self.can_create = True
            self.can_edit = True
            self.can_delete = True
            self.can_export = True
            return True
        if current_user.has_role('supervisor'):
            self.can_create = True
            self.can_edit = True
            self.can_delete = False
            return True
        if current_user.has_role('user'):
            self.can_create = True
            self.can_edit = True
            self.can_delete = False
            return True
        if current_user.has_role('create'):
            self.can_create = True
            self.can_edit = False
            self.can_delete = False
            return True
        if current_user.has_role('read'):
            self.can_create = False
            self.can_edit = False
            self.can_delete = False
            return True
        return False

class lookupRbacView(dgBaseView):

    def is_accessible(self):
        # set accessibility...
        if not current_user.is_active or not current_user.is_authenticated:
            return False

        # roles not tied to ascending permissions...
        if  not current_user.has_role('export'):
            self.can_export = False

        # roles with ascending permissions...
        if current_user.has_role('adminrole'):
            self.can_create = True
            self.can_edit = True
            self.can_delete = True
            self.can_export = True
            return True
        if current_user.has_role('supervisor'):
            self.can_create = True
            self.can_edit = True
            self.can_delete = False
            return True
        if current_user.has_role('user'):
            self.can_create = False
            self.can_edit = False
            self.can_delete = False
            return True
        if current_user.has_role('create'):
            self.can_create = False
            self.can_edit = False
            self.can_delete = False
            return True
        if current_user.has_role('read'):
            self.can_create = False
            self.can_edit = False
            self.can_delete = False
            return True
        return False

class SuperView(dgBaseView):

    can_export = True

    def is_accessible(self):
        if not current_user.is_active or not current_user.is_authenticated:
            return False
        if current_user.has_role('adminrole'):
            self.can_create = True
            self.can_edit = True
            self.can_delete = True
            #self.can_export = True
            return True
        return False


# define a context processor for merging flask-admin's template context into the
# flask-security views.
@security.context_processor
def security_context_processor():
    return dict(
        admin_base_template=admin.base_template,
        admin_view=admin.index_view,
        h=admin_helpers,
    )

# Create admin
admin = flask_admin.Admin(
    app, 'Rbac RoleBasedAccess', base_template='my_master.html', template_mode='bootstrap3',
)

class customer_view(regularRbacView):

    column_searchable_list = ['CustomerId', 'City',  'Email', 'FirstName', 'LastName',]
    # make sure the type of your filter matches your hybrid_property
    column_filters = ['FirstName', 'LastName',  'City',  'Email'   ]
    # column_default_sort = ('part_timestamp', True)
    #column_export_list = ['CustomerId', 'City',  'Email', 'FirstName', 'LastName',]

# Add model views
admin.add_view(SuperView(Role, db.session))
admin.add_view(SuperView(User, db.session))
admin.add_view(customer_view(Customer, db.session))
admin.add_view(lookupRbacView(City, db.session))


def build_sample_db():
   """
    Populate a small db with some example entries.
   """

    import string

    #db.drop_all()
    db.create_all()

    with app.app_context():
        read_role = Role(name='read')
        user_role = Role(name='user')
        super_user_role = Role(name='adminrole')
        db.session.add(user_role)
        db.session.add(super_user_role)
        db.session.add(Role(name='read'))
        db.session.add(Role(name='create'))    
        db.session.add(Role(name='supervisor'))
        db.session.add(Role(name='delete'))
        db.session.add(Role(name='export'))
        db.session.commit()

        test_user = user_datastore.create_user(
            first_name='Admin',
            email='admin',
            password=encrypt_password('admin'),
            roles=[user_role, super_user_role]
        )


        first_names = [
            'read', 'create', 'user', 'suser',  'delete',   'Charlie', 'Sophie',  'Mia',
        ]
        last_names = [
            'Brown', 'Smith',  'Patel', 'Jones', 'Williams', 'Johnson', 'Taylor', 'Thomas',
        ]
        roles1 = [
            'read',  'create',  'user', 'supervisor', 'delete', 'read', 'read', 'read',
        ]

        for i in range(len(first_names)):
            tmp_email = first_names[i].lower()
            # initialize the users with simple password...  'a'
            tmp_pass = 'a'
            user_datastore.create_user(
                first_name=first_names[i],
                last_name=last_names[i],
                email=tmp_email,
                password=encrypt_password(tmp_pass),
                roles=[read_role, ]
            )
        db.session.commit()
    return

if __name__ == '__main__':

    # Build a sample db on the fly, if one does not exist yet.
    app_dir = os.path.realpath(os.path.dirname(__file__))
    database_path = os.path.join(app_dir, app.config['DATABASE_FILE'])
    if not os.path.exists(database_path):
        build_sample_db()
    app.run(host='0.0.0.0', port=5000, debug=True)

config.py是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# http://stackoverflow.com/questions/5055042/whats-the-best-practice-using-a-settings-file-in-python
import creds

# Create dummy secret key so we can use sessions
SECRET_KEY = creds.cred['secretkey']

# Create in-memory database
DATABASE_FILE = 'fground.sqlite'
SQLALCHEMY_DATABASE_URI = creds.cred['dbspec'] + DATABASE_FILE
SQLALCHEMY_ECHO = True

# Flask-Security config
SECURITY_URL_PREFIX ="/admin"
SECURITY_PASSWORD_HASH ="pbkdf2_sha512"
SECURITY_PASSWORD_Salt=creds.cred['csalt']

# Flask-Security URLs, overridden because they don't put a / at the end
SECURITY_LOGIN_URL ="/login/"
SECURITY_LOGOUT_URL ="/logout/"
SECURITY_REGISTER_URL ="/register/"

SECURITY_POST_LOGIN_VIEW ="/admin/"
SECURITY_POST_LOGOUT_VIEW ="/admin/"
SECURITY_POST_REGISTER_VIEW ="/admin/"

# Flask-Security features
SECURITY_REGISTERABLE = True
SECURITY_SEND_REGISTER_EMAIL = False

creds.py是:

1
2
3
4
5
6
7
cred = dict(
    secretkey = '123232323238',
    dbspec    = 'sqlite:///',
    csalt     ="ATGUOHAELKiubaq3fgo8hiughaerGOJAEGj",
    dbu = 'user',
    dbp = 'pass',
)

要运行这个,我建议您从上面的flask admin auth示例开始,然后将这些文件复制到该示例中。运行它应该创建一个包含用户和角色的数据库。此外,您可以在github链接上准备好所有代码。


根据@dirn上面的评论,添加了self.修复了它。

1
        self.can_export = True

谢谢@迪恩