|
1 | 1 | from app import app, cli |
2 | | -from app.models import Category, Language, Resource, db |
| 2 | +from app.admin import run_flask_admin |
| 3 | +from app.models import Category, Language, Resource, db, Role, User |
| 4 | +import os |
| 5 | +from flask_security import Security, SQLAlchemyUserDatastore, utils |
| 6 | +from flask import url_for |
| 7 | +from flask_admin import helpers as admin_helpers |
3 | 8 | from werkzeug.middleware.dispatcher import DispatcherMiddleware |
4 | 9 | from prometheus_client import make_wsgi_app |
| 10 | +from sqlalchemy import event |
5 | 11 |
|
| 12 | +admin = run_flask_admin(app) |
| 13 | + |
| 14 | +user_datastore = SQLAlchemyUserDatastore(db, User, Role) |
| 15 | +security = Security(app, user_datastore) |
6 | 16 |
|
7 | 17 | if __name__ == "__main__": |
8 | 18 | app.run() |
|
15 | 25 | }) |
16 | 26 |
|
17 | 27 |
|
| 28 | +# @event.listens_for(User.password, 'set', retval=True) |
| 29 | +# def hash_user_password(target, value, oldvalue, initiator): |
| 30 | +# """Encrypts password when new admin created in User View""" |
| 31 | +# if value != oldvalue: |
| 32 | +# return utils.encrypt_password(value) |
| 33 | +# return value |
| 34 | + |
| 35 | + |
| 36 | +@security.context_processor |
| 37 | +def security_context_processor(): |
| 38 | + return dict( |
| 39 | + admin_base_template=admin.base_template, |
| 40 | + admin_view=admin.index_view, |
| 41 | + h=admin_helpers, |
| 42 | + get_url=url_for |
| 43 | + ) |
| 44 | + |
| 45 | + |
18 | 46 | @app.shell_context_processor |
19 | 47 | def make_shell_context(): |
20 | | - return {'db': db, 'Resource': Resource, 'Category': Category, 'Language': Language} |
| 48 | + return {'db': db, 'Resource': Resource, 'Category': Category, 'Language': Language, |
| 49 | + 'User': User, 'Role': Role} |
| 50 | + |
| 51 | + |
| 52 | +@app.before_first_request |
| 53 | +def before_first_request(): |
| 54 | + """ Adds admin/user roles and default admin account and password if none exists""" |
| 55 | + db.create_all() |
| 56 | + user_datastore.find_or_create_role(name='admin', description='Administrator') |
| 57 | + user_datastore.find_or_create_role(name='user', description='End User') |
| 58 | + |
| 59 | + admin_email = os.environ.get('ADMIN_EMAIL', "admin@example.com") |
| 60 | + admin_password = os.environ.get('ADMIN_PASSWORD', 'password') |
| 61 | + |
| 62 | + encrypted_password = utils.encrypt_password(admin_password) |
| 63 | + |
| 64 | + if not user_datastore.get_user(admin_email): |
| 65 | + user_datastore.create_user(email=admin_email, password=encrypted_password) |
| 66 | + db.session.commit() |
| 67 | + |
| 68 | + user_datastore.add_role_to_user(admin_email, 'admin') |
| 69 | + db.session.commit() |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + app.run() |
0 commit comments