Last active
December 2, 2015 09:40
-
-
Save nguyenkims/96f8f37265dc213af3c1 to your computer and use it in GitHub Desktop.
flask admin authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import flask_admin as admin | |
from flask import request, make_response, redirect, g | |
from flask.ext.admin import BaseView | |
from flask.ext.admin.contrib.sqla import ModelView | |
from flask_admin import Admin, expose | |
class MyModelView(ModelView): | |
"""Only admin can see""" | |
column_filters = ['id'] | |
def is_accessible(self): | |
# Use g to receive data from admin view | |
if hasattr(g, 'ok'): | |
return g.ok | |
# if cookies['man'] = 'ok', then consider user authorized | |
return request.cookies.get('ok') == 'man' | |
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(): | |
# return self.render('login.html') | |
return redirect('/admin') | |
class UserView(MyModelView): | |
column_filters = ['id', 'email', 'name'] | |
column_exclude_list = ['password_hash'] | |
class MyAdminView(admin.AdminIndexView): | |
"""Handle admin login""" | |
@expose('/', methods=['POST', 'GET']) | |
def index(self): | |
if request.cookies.get('ok') == 'man': | |
return super(MyAdminView, self).index() | |
if (request.form | |
and request.form.get('username') == 'admin' | |
and request.form.get('password') == 'admin_password'): | |
# notify MyModelView that user is admin | |
# Cannot use cookie to notify as the cookie is not set yet when 'super(MyAdminView, self).index()' is called | |
g.ok = True | |
response = make_response(super(MyAdminView, self).index()) | |
response.set_cookie('ok', 'man') | |
return response | |
return """ | |
<form method="POST"> | |
<input type="text" name="username"> | |
<input type="password" name="password"> | |
<input type="submit" value="Login"> | |
</form> | |
""" | |
admin = Admin( | |
app, name='app name', | |
template_mode='bootstrap3', | |
index_view=MyAdminView() | |
) | |
# add different model views here | |
# admin.add_view(UserView(models.User, db.session, category="User")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment