|
| 1 | +from flask import redirect, Response |
1 | 2 | from flask_sqlalchemy import SQLAlchemy
|
2 |
| -from flask_admin.contrib.sqla import ModelView |
| 3 | +from flask_admin.contrib import sqla |
| 4 | +from flask_basicauth import BasicAuth |
| 5 | + |
| 6 | +from werkzeug.exceptions import HTTPException |
| 7 | + |
| 8 | +class AuthException(HTTPException): |
| 9 | + def __init__(self, message): |
| 10 | + super(AuthException, self).__init__(message, Response( |
| 11 | + "You could not be authenticated. Please refresh the page.", 401, |
| 12 | + {'WWW-Authenticate': 'Basic realm="Login Required"'} |
| 13 | + )) |
| 14 | + |
| 15 | + |
| 16 | +class ModelView(sqla.ModelView): |
| 17 | + @classmethod |
| 18 | + def setup_basic_auth(cls, basic_auth): |
| 19 | + cls.basic_auth = basic_auth |
| 20 | + def is_accessible(self): |
| 21 | + if not self.basic_auth.authenticate(): |
| 22 | + raise AuthException('Not authenticated.') |
| 23 | + else: |
| 24 | + return True |
| 25 | + |
| 26 | + def inaccessible_callback(self, name, **kwargs): |
| 27 | + return redirect(self.basic_auth.challenge()) |
3 | 28 |
|
4 | 29 | db = SQLAlchemy()
|
5 | 30 |
|
6 |
| -def register_admin(admin): |
7 |
| - from .models import Intent |
| 31 | +def register_admin(admin, app): |
| 32 | + from .models import Intent, BibleVerse |
| 33 | + basic_auth = BasicAuth(app) |
| 34 | + ModelView.setup_basic_auth(basic_auth) |
8 | 35 | admin.add_view(ModelView(Intent, db.session))
|
| 36 | + admin.add_view(ModelView(BibleVerse, db.session)) |
| 37 | + |
0 commit comments