|
1 | 1 | from app import app, cli, admin
|
| 2 | +import os |
2 | 3 | from app.models import Category, Language, Resource, db, User, Role
|
3 |
| -from flask_security import Security, SQLAlchemyUserDatastore |
| 4 | +from flask_security import Security, SQLAlchemyUserDatastore, utils |
4 | 5 | from werkzeug.middleware.dispatcher import DispatcherMiddleware
|
5 | 6 | from prometheus_client import make_wsgi_app
|
6 | 7 |
|
|
23 | 24 |
|
24 | 25 | @app.shell_context_processor
|
25 | 26 | def make_shell_context():
|
26 |
| - return {'db': db, 'Resource': Resource, 'Category': Category, 'Language': Language} |
| 27 | + return {'db': db, 'Resource': Resource, 'Category': Category, |
| 28 | + 'Language': Language, 'User': User, 'Role': Role} |
| 29 | + |
| 30 | +# Create Admin user and role. |
| 31 | +@app.before_first_request |
| 32 | +def before_first_request(): |
| 33 | + # Create any database tables that don't exist yet. |
| 34 | + db.create_all() |
| 35 | + |
| 36 | + # Create the Roles "admin" and "user" -- unless they already exist |
| 37 | + user_datastore.find_or_create_role(name='admin', description='Administrator') |
| 38 | + user_datastore.find_or_create_role(name='user', description='End user') |
| 39 | + |
| 40 | + admin_email = os. environ. get( 'ADMIN_EMAIL', '[email protected]') |
| 41 | + admin_password = os.environ.get('ADMIN_PASSWORD', 'password') |
| 42 | + |
| 43 | + # Create two Users for testing purposes -- unless they already exists. |
| 44 | + # In each case, use Flask-Security utility function to encrypt the password. |
| 45 | + encrypted_password = utils.encrypt_password(admin_password) |
| 46 | + if not user_datastore.get_user(admin_email): |
| 47 | + user_datastore.create_user(admin_email, password=encrypted_password) |
| 48 | + # Add more users. |
| 49 | + |
| 50 | + # Commit any database changes; the User and Roles must exist before we |
| 51 | + # can add a Role to the User |
| 52 | + db.session.commit() |
| 53 | + |
| 54 | + # Give one User has the "end-user" role, while the other has the "admin" |
| 55 | + # role. (This will have no effect if the |
| 56 | + # Users already have these Roles.) Again, commit any database changes. |
| 57 | + user_datastore.add_role_to_user(admin_email, 'admin') |
| 58 | + db.session.commit() |
0 commit comments