Example #1
0
def create_app(settings_override=None):
    """Return the PyGotham admin application.

    :param settings_override: a ``dict`` of settings to override.

    """
    app = factory.create_app(__name__, __path__, settings_override)

    app.jinja_env.filters['rst'] = filters.rst_to_html

    # Because the admin is being wrapped inside an app, the url needs to
    # be overridden to use / instead of the default of /admin/. One of
    # the side effects of doing this is that the static assets won't
    # serve correctly without overriding static_url_path as well.
    admin = Admin(
        app, name='PyGotham',
        static_url_path='/admin',
        index_view=HomeView(endpoint='', url='/'),
    )

    # Iterate through all the modules of the current package. For each
    # module, check the public API for any instances of types that can
    # be added to the Flask-Admin menu and register them.
    for _, name, _ in pkgutil.iter_modules(__path__):
        module = importlib.import_module('{}.{}'.format(__name__, name))
        for attr in dir(module):
            view = getattr(module, attr)
            if isinstance(view, ModelView):
                admin.add_view(view)
            elif isinstance(view, MenuLink):
                admin.add_link(view)

    return app
Example #2
0
def init_admin(app):
    admin = Admin(app, name='Redash Admin', template_mode='bootstrap3')

    admin.add_view(QueryModelView(models.Query, models.db.session))
    admin.add_view(QueryResultModelView(models.QueryResult, models.db.session))
    admin.add_view(DashboardModelView(models.Dashboard, models.db.session))
    logout_link = MenuLink('Logout', '/logout', 'logout')

    for m in (models.Visualization, models.Widget, models.Event, models.Organization):
        admin.add_view(BaseModelView(m, models.db.session))

    admin.add_link(logout_link)
Example #3
0
File: admin.py Project: hudl/redash
def init_admin(app):
    admin = Admin(app, name='re:dash admin', template_mode='bootstrap3')

    admin.add_view(QueryModelView(models.Query))
    admin.add_view(QueryResultModelView(models.QueryResult))
    admin.add_view(DashboardModelView(models.Dashboard))
    admin.add_view(SchemaTableModelView(models.DataSourceTable))
    admin.add_view(SchemaTableModelView(models.DataSourceColumn))
    admin.add_view(SchemaJoinModelView(models.DataSourceJoin))
    logout_link = MenuLink('Logout', '/logout', 'logout')

    for m in (models.Visualization, models.Widget, models.Event, models.Organization):
        admin.add_view(BaseModelView(m))

    admin.add_link(logout_link)
Example #4
0
def create_admin(app, csrf):
    from models import db, User, Legislator, AdminUser, UserMessageInfo, Message, MessageLegislator, Topic
    from flask.ext.admin.menu import MenuLink

    admin = Admin(index_view=views.MyAdminIndexView())
    admin.add_link(MenuLink('Logout', url=settings.BASE_PREFIX + '/admin/logout'))
    admin.add_view(User.ModelView(User, db.session))
    admin.add_view(Legislator.ModelView(Legislator, db.session))
    admin.add_view(AdminUser.ModelView(AdminUser, db.session))
    admin.add_view(UserMessageInfo.ModelView(UserMessageInfo, db.session))
    admin.add_view(Message.ModelView(Message, db.session))
    admin.add_view(MessageLegislator.ModelView(MessageLegislator, db.session))
    admin.add_view(Topic.ModelView(Topic, db.session))

    return admin
Example #5
0
    inline_models = (Registration,)
    can_delete = False
    form_choices = {'role': [
        ('Admin', 'Administrator'),
        ('Student', 'Student'),
        ('Teacher', 'Teacher')
    ]}

    def get_query(self):
        return self.session.query(self.model).filter(self.model.role == 'Student')

    def is_accessible(self):
        return current_user.role == 'Admin' or current_user.role == 'Teacher'

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for('login', next=request.url))

"""Flask-Admin"""
admin = Admin(app, name='Bnhs', template_mode='bootstrap3', index_view=None)
admin.add_view(UserView(User, db.session, endpoint='user-admin'))
admin.add_view(RegistrationView(Registration, db.session))
admin.add_link(IsnotLoggedinMenuLink(name='Login', endpoint='login'))
admin.add_link(IsAdminMenuLink(name='Logout', endpoint='logout'))
#admin.add_view(TeacherView(User, db.session, endpoint='user'))
"""main program"""
if __name__ == '__main__':
#    db.drop_all()
#    db.create_all()
    app.run(debug=True)

Example #6
0
    # Pass additional parameters to 'path' to FileUploadField constructor
    form_columns = ('id', 'name', 'path')
    column_searchable_list = ('id', 'name', 'path')
    form_overrides = {'path': form.FileUploadField}
    form_args = {
        'path': {
            'label': 'File',
            'base_path': file_path,
            'allow_overwrite': False
        }
    }


# Add views
admin.add_view(FileView(File, db.session, endpoint="File"))
admin.add_view(UserView(User, db.session, name='User', endpoint="Accounts"))
admin.add_link(
    MenuLink(name='Scan', url='../../upload', endpoint="Back to Index"))
admin.add_link(MenuLink(name='Logout', url='../../logout', endpoint="Logout"))
instructor.add_view(FilesView(File, db.session, endpoint="Files"))
instructor.add_link(
    MenuLink(name='Scan', url='../../upload', endpoint="Back to Index"))
instructor.add_link(
    MenuLink(name='Logout', url='../../logout', endpoint="Signout"))

if __name__ == "__main__":
    db.create_all()
    app_dir = op.realpath(os.path.dirname(__file__))
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port, debug=True)
Example #7
0
    #跳转
    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for('security.login', next=request.url))

    #后台首页
    @expose('/')
    def index(self):
        return self.render('admin/index.html')

# admin = Admin(name='chahua3287',index_view=MyAdminIndexView())



admin = Admin(name='home',template_mode="bootstrap3",
              index_view= MyAdminIndexView())
from .user import UserModelView
from .shop import ShopModelView

admin.add_view(UserModelView(User, db.session, name = u'用户管理'))
admin.add_view(ShopModelView(Shop_Info, db.session, name = u'商铺管理'))
admin.add_view(ModelView(Role, db.session))
admin.add_view(ModelView(Addr,db.session))
admin.add_view(ModelView(Product_Category,db.session))
admin.add_view(ModelView(Product_info,db.session))
admin.add_view(ModelView(Brand_info,db.session))
admin.add_view(ModelView(Sku_price,db.session))
admin.add_link(AuthenticatedMenuLink(name = 'logout',
                                     endpoint='security.logout'))
admin.add_view(ModelView(Cart_master,db.session))
admin.add_view(ModelView(Cart_detail,db.session))
Example #8
0
from flask_admin import Admin
from core import app, db
from core.admin_portal.admin_models import MyModelViewUser, MyModelViewPost, MyAdminIndexView
from core.models import User, Post
from flask_admin.menu import MenuLink


admin = Admin(app, name='corgiTexter', template_mode='bootstrap3', index_view=MyAdminIndexView())

admin.add_view(MyModelViewUser(User, db.session))
admin.add_view(MyModelViewPost(Post, db.session))
admin.add_link(MenuLink(name='Main Site', url='/'))


app.config['FLASK_ADMIN_SWATCH'] = 'cerulean'
Example #9
0
class MyAdminIndexView(AdminIndexView):

    @expose('/')
    def index(self):
        if not current_user.is_authenticated:
            return redirect(url_for('security.login', next=request.url))
        return super(MyAdminIndexView, self).index()


class AuthenticatedMenuLink(MenuLink):
    def is_accessible(self):
        return current_user.is_authenticated
    


admin = Admin(name="Riverflo.ws",
              index_view=MyAdminIndexView(),
              template_mode='bootstrap3',
              )
admin.add_view(UserView(User, db.session))
admin.add_view(ModelView(Region, db.session))
admin.add_view(ModelView(River, db.session))
admin.add_view(SectionView(Section, db.session))
admin.add_view(GageView(Gage, db.session))
admin.add_view(SensorView(Sensor, db.session))
admin.add_view(ModelView(Correlation, db.session))
admin.add_view(FileAdmin(path, '/static/images/', name='Images'))
admin.add_link(AuthenticatedMenuLink(name='Logout',
                                     endpoint='security.logout'))
Example #10
0
        return False 
    
    def on_model_change(self, form, model, is_created):
        # send the email to the user created.
        email_id = form.email.data        
        user_pass = form.password.data         
        user_username = form.username.data 
        mail.send_message("RPA FACULTY ASSISTANT ACCOUNT CREATED!",
                          sender=params["ADMIN_EMAIL"],
                          recipients=[email_id],
                          body="Your account has been created.\n\nUsername: %s\nPassword: %s"%(user_username,user_pass)
        )
        super().on_model_change(form, model, is_created)       

admin.add_views(UserView(Users,db.session))
admin.add_link(MenuLink(name='Log out', url='/admin/logout'))
# admin.add_views(ModelView(Tasks,db.session))


# dash app with the baseurl as visuals and the bootstrap linked

dashapp = dash.Dash(__name__, server=app, url_base_pathname="/visuals/",external_stylesheets=[dbc.themes.BOOTSTRAP])

# changing the title

dashapp.title="Visuals"

# basic layout of the dashapp
dashapp.layout = html.Div([

    dcc.Location(id='url'),
        if current_user.has_role('admin') or current_user.has_role('superuser'):
            return True

    def inaccessible_callback(self, name, **kwargs):
        if current_user.is_authenticated:
            abort(403) # permission denied
        else:
            return redirect(url_for('login', next=request.url)) # divert to login 
        
class RoleView(ModelView):
    
    def is_accessible(self):
        if not current_user.is_active or not current_user.is_authenticated:
            return False

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

    def inaccessible_callback(self, name, **kwargs):
        if current_user.is_authenticated:
            abort(403) # permission denied
        else:
            return redirect(url_for('login', next=request.url)) # divert to login 
             
# Add administrative views here
admin.add_view(UserView(models.User, db.session))
admin.add_view(RoleView(models.Role, db.session))

# Add menu links
admin.add_link(MenuLink(name='Sign out', url='/logout'))
Example #12
0
def app_init():
    setup_logging()
    app = Flask(__name__)
    app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=1)
    app.config.from_object(FlaskConfig)
    if app.config['LOCAL']:
        CORS(app)
    if not app.config['LOCAL']:
        app.wsgi_app = ReverseProxied(app.wsgi_app)
    for bp in blueprints:
        app.register_blueprint(bp)

    configure_uploads(app, images)
    patch_request_class(app)
    db.init_app(app)

    # Flask-Security setup

    class UserDatastore(PeeweeUserDatastore):
        def login_user_silent(self, user):
            login_user(user)
            user.login_count -= 1
            self.put(user)

        def get_user(self, identifier):
            if isinstance(identifier, int):
                try:
                    return self.user_model.get(
                        self.user_model.id == identifier)
                except self.user_model.DoesNotExist:
                    pass
            for attr in get_identity_attributes():
                column = getattr(self.user_model, attr)
                try:
                    return self.user_model.get(
                        fn.Lower(column) == fn.Lower(identifier))
                except self.user_model.DoesNotExist:
                    pass

    init_social(app, db.database)
    user_datastore = UserDatastore(db, User, Role, UserRole)
    security = Security(app, user_datastore)
    security.login_manager.login_view = 'auth.login'

    @security.login_manager.unauthorized_handler
    def unauthorized():
        return 'Unauthorized', HTTPStatus.UNAUTHORIZED

    @user_logged_out.connect_via(app)
    def on_logout(*args, **kwargs):
        user = kwargs['user']
        if user.has_role('superuser'):
            return
        user_datastore.add_role_to_user(user, 'anonymous')
        user_datastore.remove_role_from_user(user, 'user')
        user_datastore.login_user_silent(user)

    @app.before_request
    def login_implicitly():
        if isinstance(current_user._get_current_object(), AnonymousUser):
            u = user_datastore.create_user(roles=['anonymous'])
            user_datastore.login_user_silent(u)
        g.user = current_user

    @app.context_processor
    def inject_user():
        try:
            return {'user': g.user}
        except AttributeError:
            return {'user': None}

    if not DEV:

        @app.errorhandler(500)
        def error_handler(error):
            if isinstance(error, SocialAuthBaseException):
                return redirect('/socialerror')

    # Flask-Admin setup

    class SecureModelView(ModelView):
        def is_accessible(self):
            return current_user.is_active and \
                   current_user.is_authenticated and \
                   current_user.has_role('superuser')

        def _handle_view(self, name, **kwargs):
            if not self.is_accessible():
                if current_user.is_authenticated:
                    abort(403)
                return redirect(url_for('auth.admin_login', next=request.url))

    class AuthenticatedMenuLink(MenuLink):
        def is_accessible(self):
            return current_user.is_authenticated

    admin = Admin(app, name='pushmoney', template_mode='bootstrap3')
    admin.add_view(SecureModelView(Shop))
    admin.add_view(SecureModelView(Category))
    admin.add_view(SecureModelView(Product))
    admin.add_view(SecureModelView(User))
    admin.add_view(SecureModelView(PushWallet))
    admin.add_view(SecureModelView(PushCampaign))
    admin.add_view(SecureModelView(OrderHistory))
    admin.add_view(SecureModelView(WebhookEvent))
    admin.add_view(SecureModelView(Recipient))
    admin.add_view(SecureModelView(UserImage))
    admin.add_view(SecureModelView(CustomizationSetting))
    admin.add_link(
        AuthenticatedMenuLink(name='Logout', endpoint='security.logout'))

    @security.context_processor
    def security_context_processor():
        return dict(admin_base_template=admin.base_template,
                    admin_view=admin.index_view,
                    h=admin_helpers,
                    get_url=url_for)

    @app.before_first_request
    def create_admin():
        if User.get_or_none(email='admin'):
            db.close_db(None)
            return
        anonymous_role, _ = Role.get_or_create(name='anonymous')
        super_role, _ = Role.get_or_create(name='superuser')
        user_role, _ = Role.get_or_create(name='user')
        user_datastore.create_user(first_name='Admin',
                                   email='admin',
                                   password=hash_password(ADMIN_PASS),
                                   confirmed_at=datetime.utcnow(),
                                   roles=[user_role, super_role])
        db.close_db(None)

    endpoints = sorted([
        str(rule) for rule in app.url_map.iter_rules()
        if 'admin' not in str(rule)
    ])
    info('\n'.join(endpoints))
    return app
Example #13
0
def start_admin(app, db):
	admin = Admin(app, name="Console", index_view=AdminIndex(), template_mode="bootstrap3")
	admin.add_view(UserModelView(User, db.session))
	admin.add_view(ReaderModelView(Reader, db.session))
	admin.add_link(MenuLink(name="Back to Console", url="/index"))
Example #14
0
admin.add_view(
    MyModelView(Case, db.session, category='Case Data', name='Case Summary'))
admin.add_view(MyModelView(Chunklist, db.session, category='Case Data'))
admin.add_view(MyModelView(Chunk, db.session, category='Case Data'))
admin.add_view(
    ImageView(Image, db.session, category='Case Data', name='Images'))
admin.add_view(
    PatchView(Patch, db.session, category='Case Data', name='Image Patches'))
admin.add_view(
    InfectionView(Infection,
                  db.session,
                  category='Diseases',
                  name='Diseases and Infections'))
admin.add_view(
    ParTypeView(db.session, name='Diagnosis List', category='Diseases'))
admin.add_view(
    MyModelView(Region, db.session, category='Locations', name='Regions'))
admin.add_view(
    MyModelView(Province, db.session, category='Locations', name='Provinces'))
admin.add_view(
    MyModelView(Municipality,
                db.session,
                category='Locations',
                name='Municipalities'))
admin.add_view(FileAdmin(log_path, '/log/', name='Logs', url="/admin/logview"))

# Navbar links
admin.add_link(
    AuthenticatedMenuLink(name='Back to Website', url='/monitoring/1'))
Example #15
0
def create_app(config=None):
    app = Flask(__name__)
    app.secret_key = configuration.get('webserver', 'SECRET_KEY')
    app.config['LOGIN_DISABLED'] = not configuration.getboolean(
        'webserver', 'AUTHENTICATE')

    csrf.init_app(app)

    #app.config = config
    airflow.load_login()
    airflow.login.login_manager.init_app(app)

    cache = Cache(app=app,
                  config={
                      'CACHE_TYPE': 'filesystem',
                      'CACHE_DIR': '/tmp'
                  })

    app.register_blueprint(ck, url_prefix='/ck')
    app.register_blueprint(routes)
    app.jinja_env.add_extension("chartkick.ext.charts")

    with app.app_context():
        from airflow.www import views

        admin = Admin(
            app,
            name='Airflow',
            static_url_path='/admin',
            index_view=views.HomeView(endpoint='', url='/admin', name="DAGs"),
            template_mode='bootstrap3',
        )
        av = admin.add_view
        vs = views
        av(vs.Airflow(name='DAGs', category='DAGs'))

        av(vs.QueryView(name='Ad Hoc Query', category="Data Profiling"))
        av(
            vs.ChartModelView(models.Chart,
                              Session,
                              name="Charts",
                              category="Data Profiling"))
        av(
            vs.KnowEventView(models.KnownEvent,
                             Session,
                             name="Known Events",
                             category="Data Profiling"))
        av(
            vs.SlaMissModelView(models.SlaMiss,
                                Session,
                                name="SLA Misses",
                                category="Browse"))
        av(
            vs.TaskInstanceModelView(models.TaskInstance,
                                     Session,
                                     name="Task Instances",
                                     category="Browse"))
        av(vs.LogModelView(models.Log, Session, name="Logs",
                           category="Browse"))
        av(
            vs.JobModelView(jobs.BaseJob,
                            Session,
                            name="Jobs",
                            category="Browse"))
        av(
            vs.PoolModelView(models.Pool,
                             Session,
                             name="Pools",
                             category="Admin"))
        av(vs.ConfigurationView(name='Configuration', category="Admin"))
        av(
            vs.UserModelView(models.User,
                             Session,
                             name="Users",
                             category="Admin"))
        av(
            vs.ConnectionModelView(models.Connection,
                                   Session,
                                   name="Connections",
                                   category="Admin"))
        av(
            vs.VariableView(models.Variable,
                            Session,
                            name="Variables",
                            category="Admin"))

        admin.add_link(
            base.MenuLink(category='Docs',
                          name='Documentation',
                          url='http://pythonhosted.org/airflow/'))
        admin.add_link(
            base.MenuLink(category='Docs',
                          name='Github',
                          url='https://github.com/airbnb/airflow'))

        av(
            vs.DagRunModelView(models.DagRun,
                               Session,
                               name="DAG Runs",
                               category="Browse"))
        av(vs.DagModelView(models.DagModel, Session, name=None))
        # Hack to not add this view to the menu
        admin._menu = admin._menu[:-1]

        def integrate_plugins():
            """Integrate plugins to the context"""
            from airflow.plugins_manager import (admin_views, flask_blueprints,
                                                 menu_links)
            for v in admin_views:
                admin.add_view(v)
            for bp in flask_blueprints:
                app.register_blueprint(bp)
            for ml in menu_links:
                admin.add_link(ml)

        integrate_plugins()

        @app.context_processor
        def jinja_globals():
            return {
                'hostname': socket.gethostname(),
            }

        @app.teardown_appcontext
        def shutdown_session(exception=None):
            settings.Session.remove()

        return app
Example #16
0
def create_app(config_object=ProductionConfig):
    app = Flask(__name__)
    # Sentry(app, dsn='https://*****:*****@sentry.io/300199')  # noqa

    # CORS(app)
    app.config.from_object(config_object)

    db.init_app(app)
    migrate.init_app(app, db)
    csrf.init_app(app)
    from Mandark.project import models

    userstore = SQLAlchemyUserDatastore(db, models.User, models.Role)
    Security(app, userstore)

    @app.before_request
    def before_request():
        g.user = current_user

    @app.errorhandler(404)
    def not_found_error(e):
        print(e)
        return render_template('404.html', title='FourOhFour')

    @app.errorhandler(500)
    def internal_error():
        return render_template('500.html', title='A server oops happened')

    try:
        with app.app_context():
            userstore.find_or_create_role(name='admin',
                                          description='Administrator')
            userstore.find_or_create_role(name='moderator',
                                          description='Moderator')
            userstore.find_or_create_role(name='projectmgr',
                                          description='Project Manager')
            userstore.find_or_create_role(name='user',
                                          description='General User')
            userstore.create_user(email='*****@*****.**',
                                  password=hash_password('admin'))
            userstore.create_user(email='*****@*****.**',
                                  password=hash_password('user'))
            userstore.create_user(email='*****@*****.**',
                                  password=hash_password('Allanice-001'))
            userstore.add_role_to_user('*****@*****.**', 'admin')
            userstore.add_role_to_user('*****@*****.**', 'user')
            userstore.add_role_to_user('*****@*****.**', 'admin')
            db.session.commit()
            print('IGETHEE')
    except OperationalError:
        if app.debug:
            print(OperationalError)
        else:
            pass
    except Exception as e:
        with app.app_context():
            print(e)
            db.session.rollback()

    from Mandark.project.views import main, admin
    app.register_blueprint(main.main)

    app_admin = Admin(app,
                      'Administration Section',
                      template_mode='bootstrap3',
                      index_view=admin.MyAdminIndexView())
    app_admin.add_view(admin.UserModelView(models.User, db.session))
    app_admin.add_view(admin.RoleModelView(models.Role, db.session))
    app_admin.add_view(admin.ProjectModelView(models.Project, db.session))
    app_admin.add_view(admin.ProjectMgrModelView(models.Projectmgr,
                                                 db.session))
    app_admin.add_view(
        admin.OrganisationModelView(models.Organisation, db.session))
    app_admin.add_view(
        admin.ChangeRequestTypeView(models.ChangeRequestType, db.session))
    app_admin.add_view(
        admin.ChangeRequestSubmitterView(models.ChangeRequestSubmitter,
                                         db.session))
    app_admin.add_link(MenuLink(name='Back to Site', url='/'))

    return app
Example #17
0
class AdministrationApplication(object):

    def __init__(self, app, cfg_manager, core_server, bypass_authz = False):
        super(AdministrationApplication, self).__init__()
        app.json_encoder = CustomJSONEncoder
        
        self.cfg_manager = cfg_manager
        pub_directory = os.path.join(os.path.abspath(self.cfg_manager.get('deployment_dir', '')), 'pub')
        self.config = cfg_manager
        db.initialize(cfg_manager)

        self.core_server = core_server

        db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=db.engine))

        files_directory = cfg_manager.get_doc_value(configuration_doc.CORE_STORE_STUDENTS_PROGRAMS_PATH)
        core_server_url  = cfg_manager.get_value( 'core_server_url', '' )
        self.script_name = urlparse.urlparse(core_server_url).path.split('/weblab')[0] or ''

        self.app = app

        static_folder = os.path.abspath(os.path.join(os.path.dirname(web.__file__), 'static'))

        # Not allowed
        @app.route('/weblab/not_allowed')
        def not_allowed():
            return "You are logged in, but not allowed to see this content. Please log in with a proper account"

        # Back
        @app.route('/weblab/back')
        def back_to_client():
            return redirect(url_for('core_webclient.labs'))
   
        ################################################
        # 
        #  Administration panel for administrators
        # 
        # 

        admin_url = '/weblab/admin'
        category_system = lazy_gettext("System")
        category_users = lazy_gettext("Users")
        category_logs = lazy_gettext("Logs")
        category_experiments = lazy_gettext("Experiments")
        category_permissions = lazy_gettext("Permissions")
        self.admin = Admin(index_view = admin_views.HomeView(db_session, url = admin_url),name = lazy_gettext('WebLab-Deusto Admin'), url = admin_url, endpoint = admin_url, base_template = 'weblab-master.html', template_mode = 'bootstrap3')
        self.admin.weblab_admin_app = self

        self.admin.add_view(admin_views.SystemProperties(db_session, category = category_system, name = lazy_gettext('Settings'), endpoint = 'system/settings', url='settings'))
        self.admin.add_view(admin_views.AuthsPanel(db_session, category = category_system, name = lazy_gettext('Authentication'), endpoint = 'system/auth', url='auth'))
        if not os.path.exists(pub_directory):
            try:
                os.mkdir(pub_directory)
            except (IOError, OSError) as e:
                print("WARNING: %s not found. Create it to upload files to it." % pub_directory)
                    
        if os.path.exists(pub_directory):
            self.admin.add_view(admin_views.AdministratorFileAdmin(pub_directory, category = category_system, name = lazy_gettext('Public directory'), endpoint = 'system/pub', url='pub'))

        self.admin.add_view(admin_views.UsersAddingView(db_session,  category = category_users, name = lazy_gettext('Add multiple users'),  endpoint = 'users/multiple'))
        self.admin.add_view(admin_views.UsersPanel(db_session,  category = category_users, name = lazy_gettext('Users'),  endpoint = 'users/users', url='users'))
        self.admin.add_view(admin_views.GroupsPanel(db_session, category = category_users, name = lazy_gettext('Groups'), endpoint = 'users/groups', url='groups'))
        self.admin.add_view(admin_views.InvitationsPanel(db_session, category = category_users, name = lazy_gettext('Invitations'),
                                                         endpoint = 'users/invitations', url='invitations'))

        self.admin.add_view(admin_views.UserUsedExperimentPanel(files_directory, db_session, category = category_logs, name = lazy_gettext('User logs'), endpoint = 'logs/users', url='logs'))

        self.admin.add_view(admin_views.ExperimentCategoryPanel(db_session, category = category_experiments, name = lazy_gettext('Categories'),  endpoint = 'experiments/categories', url='experiments/categories'))
        self.admin.add_view(admin_views.ExperimentPanel(db_session,         category = category_experiments, name = lazy_gettext('Experiments'), endpoint = 'experiments/experiments', url='experiments'))
        # TODO: Until finished, do not display
        # self.admin.add_view(admin_views.SchedulerPanel(db_session,         category = category_experiments, name = lazy_gettext('Schedulers'), endpoint = 'experiments/schedulers'))

        self.admin.add_view(admin_views.PermissionsAddingView(db_session,  category = category_permissions, name = lazy_gettext('Create'), endpoint = 'permissions/create', url='permissions'))
        self.admin.add_view(admin_views.UserPermissionPanel(db_session,  category = category_permissions, name = lazy_gettext('User'),   endpoint = 'permissions/user'))
        self.admin.add_view(admin_views.GroupPermissionPanel(db_session, category = category_permissions, name = lazy_gettext('Group'),  endpoint = 'permissions/group'))
        self.admin.add_view(admin_views.RolePermissionPanel(db_session,  category = category_permissions, name = lazy_gettext('Roles'),  endpoint = 'permissions/role'))

        self.admin.add_link(MenuLink(endpoint='instructor.index', name = lazy_gettext('Instructor panel'), icon_type='glyph', icon_value='glyphicon-stats'))
        self.admin.add_link(MenuLink(endpoint='profile.index', name = lazy_gettext('My profile'), icon_type='glyph', icon_value='glyphicon-user'))
        self.admin.add_link(MenuLink(endpoint = 'back_to_client', name = lazy_gettext('Back'), icon_type='glyph', icon_value='glyphicon-log-out'))

        self.admin.init_app(self.app)

        self.full_admin_url = self.script_name + admin_url

        ################################################
        # 
        #  Profile panel
        # 

        profile_url = '/weblab/profile'
        self.profile = Admin(index_view = profile_views.ProfileHomeView(db_session, url = profile_url, endpoint = 'profile'),name = lazy_gettext('WebLab-Deusto profile'), url = profile_url, endpoint = profile_url, base_template = 'weblab-master.html', template_mode='bootstrap3')
        self.profile.weblab_admin_app = self

        self.profile.add_view(profile_views.ProfileEditView(db_session, name = lazy_gettext('Edit'), endpoint = 'edit'))

        self.profile.add_view(profile_views.MyAccessesPanel(files_directory, db_session,  name = lazy_gettext('My accesses'), endpoint = 'accesses'))
        self.profile.add_link(MenuLink(endpoint = 'back_to_client', name = lazy_gettext('Back'), icon_type='glyph', icon_value='glyphicon-log-out'))

        self.profile.init_app(self.app)

        ################################################
        # 
        #  Instructors panel
        # 
    
        # TODO. There should be able a new M2M relation between instructors and groups.
        # 
        # Instructor should be able to:
        # 
        # a) Create new groups (of which they are in charge)
        # b) Make other instructors in charge of these groups
        # c) Add students (and only students) to the system; forcing a group
        # d) Edit users (only students; of those groups that the administrator is in charge of)
        # e) Assign permissions on these courses
        # f) Manage the permissions on these courses
        # g) See the logs of their own students
        # h) See a panel with analytics of each of these groups (this panel is common to the administrator, and has not been implemented)

        instructor_url = '/weblab/instructor'
        instructor_home = instructor_views.InstructorHomeView(db_session, url = instructor_url, endpoint = 'instructor')
        instructor_home.static_folder = static_folder
        self.instructor = Admin(index_view = instructor_home, name = lazy_gettext("Weblab-Deusto instructor"), url = instructor_url, endpoint = instructor_url, base_template = 'weblab-master.html', template_mode='bootstrap3')
        self.instructor.weblab_admin_app = self
        
        category_general = lazy_gettext("General")
        category_stats = lazy_gettext("Stats")
        self.instructor.add_view(instructor_views.UsersPanel(db_session, category = category_general, name = lazy_gettext('Users'), endpoint = 'users'))
        self.instructor.add_view(instructor_views.GroupsPanel(db_session, category = category_general, name = lazy_gettext('Groups'), endpoint = 'groups'))
        self.instructor.add_view(instructor_views.UserUsedExperimentPanel(db_session, category = category_general, name = lazy_gettext('Raw accesses'), endpoint = 'logs'))

        self.instructor.add_view(instructor_views.GroupStats(db_session, category = category_stats, name = lazy_gettext('Group'), endpoint = 'stats/groups'))
        self.instructor.add_link(MenuLink(endpoint='profile.index', name = lazy_gettext('My profile'), icon_type='glyph', icon_value='glyphicon-user'))
        self.instructor.add_link(MenuLink(endpoint = 'back_to_client', name = lazy_gettext('Back'), icon_type='glyph', icon_value='glyphicon-log-out'))

        self.instructor.init_app(self.app)

        ################################################
        # 
        #  Other
        # 
        self.bypass_authz = bypass_authz

    @property
    def db(self):
        return self.core_server.db

    def get_db(self):
        return self.core_server.db

    def is_admin(self):
        if self.bypass_authz:
            return True

        try:
            session_id = (request.cookies.get('weblabsessionid') or '').split('.')[0]
            if not session_id:
                return False
            
            with weblab_api(self.core_server, session_id = session_id):
                is_admin = weblab_api.is_admin
            
            return is_admin
        except:
            traceback.print_exc()
            return False

    def get_user_role(self):
        if self.bypass_authz:
            return 'admin'

        try:
            session_id = (request.cookies.get('weblabsessionid') or '').split('.')[0]
            if session_id:
                try:
                    with weblab_api(self.core_server, session_id = session_id):
                        user_info = weblab.core.server.get_user_information()
                except SessionNotFoundError:
                    # Gotcha
                    traceback.print_exc()
                else:
                    return user_info.role.name
            return None
        except:
            traceback.print_exc()
            return None

    def _reserve_fake_session(self):
        fake_names = ('student1', 'porduna', 'user7', 'admin')
        exc = None
        for fake_name in fake_names:
            try:
                session_id, route = self.core_server._reserve_session(ValidDatabaseSessionId(fake_name, 'administrator'))
            except Exception as exc:
                pass
            else:
                return session_id, route
        raise exc

    def get_permissions(self):
        if self.bypass_authz:
            session_id, _ = self._reserve_fake_session()
            with weblab_api(self.core_server, session_id = session_id.id):
                return weblab.core.server.get_user_permissions()

        session_id = (request.cookies.get('weblabsessionid') or '').split('.')[0]
        if session_id:
            try:
                with weblab_api(self.core_server, session_id = session_id):
                    return weblab.core.server.get_user_permissions()
            except:
                traceback.print_exc()
        return None

    def get_user_information(self):
        if self.bypass_authz:
            session_id, _ = self._reserve_fake_session()
            with weblab_api(self.core_server, session_id = session_id.id):
                return weblab.core.server.get_user_information()

        session_id = (request.cookies.get('weblabsessionid') or '').split('.')[0]
        if session_id:
            try:
                with weblab_api(self.core_server, session_id = session_id):
                    return weblab.core.server.get_user_information()
            except SessionNotFoundError:
                pass
        return None
Example #18
0
class MySecureModelView(MyModelView):
    def is_accessible(self):
        return current_user.is_authenticated and current_user.admin

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for('login'))


class MyAdminIndexViews(AdminIndexView):
    def is_accessible(self):
        return current_user.is_authenticated

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for('login'))


admin = Admin(app, index_view=MyAdminIndexViews())
login = LoginManager(app)


@login.user_loader
def load_user(user_id):
    return User.query.get(user_id)


admin.add_view(MySecureModelView(User, db.session))
admin.add_view(MySecureModelView(Pet, db.session))
admin.add_view(MyModelView(Owner, db.session))
admin.add_link(MenuLink('LogOut', '/logout'))
Example #19
0
                    name='Admin Console',
                    template_mode='bootstrap3',
                    index_view=admin.HomeView())
flask_admin.add_view(admin.ChannelModelView)
flask_admin.add_view(admin.CounterModelView)
flask_admin.add_view(admin.CSRModelView)
flask_admin.add_view(admin.CSRGAModelView)
flask_admin.add_view(admin.InvigilatorModelView)
flask_admin.add_view(admin.OfficeModelView)
flask_admin.add_view(admin.OfficeGAModelView)
flask_admin.add_view(admin.RoleModelView)
flask_admin.add_view(admin.ServiceModelView)
flask_admin.add_view(admin.SmartBoardModelView)
flask_admin.add_view(admin.RoomModelView)
flask_admin.add_view(admin.ExamTypeModelView)
flask_admin.add_link(
    admin.LoginMenuLink(name='Login', category='', url="/api/v1/login/"))
flask_admin.add_link(
    admin.LogoutMenuLink(name='Logout', category='', url="/api/v1/logout/"))

login_manager = LoginManager()
login_manager.init_app(application)
import app.auth

compress = Compress()
compress.init_app(application)

#   Get long running query logger.
logger = logging.getLogger("myapp.sqltime")
logger.setLevel(logging.DEBUG)

#   Configure all logging except basic logging
Example #20
0
        if not model.filename:
            return ''
        image_loc = url_for('send_file',
                            folder=app.config['via_folder'],
                            filename=model.filename)
        url = url_for('via_template', ids=model.id)
        return Markup(
            f'<a href="{url}"><img src="{image_loc}" height="42" width="42"></a>'
        )

    column_formatters = {'img': _list_img, 'edit regions': _edit}


admin.add_view(AnnotatedImageView(AnnotatedImage, db.session))
admin.add_view(ModelView(ImageRegion, db.session))
admin.add_link(MenuLink(name='Homepage', url='/'))
admin.add_link(MenuLink(name='VIA', url='/via_template'))


@app.route('/', methods=['GET'])
def index():
    return '<a href="/via_template">VIA</a><br><a href="/admin/annotatedimage">admin</a>'


@app.route('/via_template', methods=['GET'])
def via_template():
    return render_template('via_flask.html')


@app.route('/send_file/<path:folder>/<path:filename>')
def send_file(folder, filename):
Example #21
0
from flask.app import Flask
from flask.ext.admin.base import MenuLink
import settings
from todo_app.admin_views import AdminIndex
from werkzeug.debug import DebuggedApplication
from flask_admin import Admin
from google.appengine.api import users


flask_app = Flask(__name__)
flask_app.config.from_object(settings)

admin = Admin(flask_app, name='TODO', index_view=AdminIndex(url='/admin', name='Home'), )
admin.add_link(MenuLink(name='Logout',url = users.create_logout_url('/')))

if flask_app.config['DEBUG']:
    flask_app.debug = True
    app = DebuggedApplication(flask_app, evalex=True)

app = flask_app

from todo_app import admin_views
from todo_app import views
Example #22
0
def create_app(config=None, testing=False):
    app = Flask(__name__)
    app.secret_key = configuration.get('webserver', 'SECRET_KEY')
    app.config['LOGIN_DISABLED'] = not configuration.getboolean(
        'webserver', 'AUTHENTICATE')

    csrf.init_app(app)

    app.config['TESTING'] = testing

    airflow.load_login()
    airflow.login.login_manager.init_app(app)

    from airflow import api
    api.load_auth()
    api.api_auth.init_app(app)

    cache = Cache(app=app,
                  config={
                      'CACHE_TYPE': 'filesystem',
                      'CACHE_DIR': '/tmp'
                  })

    app.register_blueprint(routes)

    log_format = airflow.settings.LOG_FORMAT_WITH_PID
    airflow.settings.configure_logging(log_format=log_format)

    with app.app_context():
        from airflow.www import views

        admin = Admin(
            app,
            name='Airflow',
            static_url_path='/admin',
            index_view=views.HomeView(endpoint='', url='/admin', name="DAGs"),
            template_mode='bootstrap3',
        )
        av = admin.add_view
        vs = views
        av(vs.Airflow(name='DAGs', category='DAGs'))

        av(vs.QueryView(name='Ad Hoc Query', category="Data Profiling"))
        av(
            vs.ChartModelView(models.Chart,
                              Session,
                              name="Charts",
                              category="Data Profiling"))
        av(
            vs.KnowEventView(models.KnownEvent,
                             Session,
                             name="Known Events",
                             category="Data Profiling"))
        av(
            vs.SlaMissModelView(models.SlaMiss,
                                Session,
                                name="SLA Misses",
                                category="Browse"))
        av(
            vs.TaskInstanceModelView(models.TaskInstance,
                                     Session,
                                     name="Task Instances",
                                     category="Browse"))
        av(vs.LogModelView(models.Log, Session, name="Logs",
                           category="Browse"))
        av(
            vs.JobModelView(jobs.BaseJob,
                            Session,
                            name="Jobs",
                            category="Browse"))
        av(
            vs.PoolModelView(models.Pool,
                             Session,
                             name="Pools",
                             category="Admin"))
        av(vs.ConfigurationView(name='Configuration', category="Admin"))
        av(
            vs.UserModelView(models.User,
                             Session,
                             name="Users",
                             category="Admin"))
        av(
            vs.ConnectionModelView(models.Connection,
                                   Session,
                                   name="Connections",
                                   category="Admin"))
        av(
            vs.VariableView(models.Variable,
                            Session,
                            name="Variables",
                            category="Admin"))
        av(vs.XComView(models.XCom, Session, name="XComs", category="Admin"))

        admin.add_link(
            base.MenuLink(category='Docs',
                          name='Documentation',
                          url='http://pythonhosted.org/airflow/'))
        admin.add_link(
            base.MenuLink(category='Docs',
                          name='Github',
                          url='https://github.com/apache/incubator-airflow'))

        av(vs.VersionView(name='Version', category="About"))

        av(
            vs.DagRunModelView(models.DagRun,
                               Session,
                               name="DAG Runs",
                               category="Browse"))
        av(vs.DagModelView(models.DagModel, Session, name=None))
        # Hack to not add this view to the menu
        admin._menu = admin._menu[:-1]

        def integrate_plugins():
            """Integrate plugins to the context"""
            from airflow.plugins_manager import (admin_views, flask_blueprints,
                                                 menu_links)
            for v in admin_views:
                logging.debug('Adding view ' + v.name)
                admin.add_view(v)
            for bp in flask_blueprints:
                logging.debug('Adding blueprint ' + bp.name)
                app.register_blueprint(bp)
            for ml in sorted(menu_links, key=lambda x: x.name):
                logging.debug('Adding menu link ' + ml.name)
                admin.add_link(ml)

        integrate_plugins()

        import airflow.www.api.experimental.endpoints as e
        # required for testing purposes otherwise the module retains
        # a link to the default_auth
        if app.config['TESTING']:
            if six.PY2:
                reload(e)
            else:
                import importlib
                importlib.reload(e)

        app.register_blueprint(e.api_experimental,
                               url_prefix='/api/experimental')

        @app.context_processor
        def jinja_globals():
            return {
                'hostname': socket.getfqdn(),
            }

        @app.teardown_appcontext
        def shutdown_session(exception=None):
            settings.Session.remove()

        return app
Example #23
0
    def on_form_prefill(self, form, id):
        print(form)

@app.route("/")
def index():
    return redirect(url_for('admin.index'))

admin = Admin(app, name='Agenda Publica', template_mode='bootstrap3', index_view=IndexView())
# Add administrative views here
admin.add_view(EventoView(Evento, db.session))
#admin.add_view(SuperuserView(Evento, db.session))
admin.add_view(SuperuserView(Responsavel, db.session))
admin.add_view(SuperuserView(Orgao, db.session))
admin.add_view(SuperuserView(Tipo, db.session))
admin.add_view(SuperuserView(Tag, db.session))
admin.add_link(MenuLink(name='Logout', endpoint='security.logout'))

# Create the Flask-Restless API manager.
manager = flask_restless.APIManager(app, flask_sqlalchemy_db=db)

# Create API endpoints, which will be available at /api/<tablename> by
# default. Allowed HTTP methods can be specified as well.
manager.create_api(Evento, methods=['GET'])

@security.context_processor
def security_context_processor():
    return dict(
        admin_base_template=admin.base_template,
        admin_view=admin.index_view,
        h=admin_helpers,
    )
Example #24
0
def create_app(config=None, testing=False):
    app = Flask(__name__)
    if conf.getboolean('webserver', 'ENABLE_PROXY_FIX'):
        app.wsgi_app = ProxyFix(
            app.wsgi_app,
            x_for=conf.getint("webserver", "PROXY_FIX_X_FOR", fallback=1),
            x_proto=conf.getint("webserver", "PROXY_FIX_X_PROTO", fallback=1),
            x_host=conf.getint("webserver", "PROXY_FIX_X_HOST", fallback=1),
            x_port=conf.getint("webserver", "PROXY_FIX_X_PORT", fallback=1),
            x_prefix=conf.getint("webserver", "PROXY_FIX_X_PREFIX", fallback=1)
        )
    app.secret_key = conf.get('webserver', 'SECRET_KEY')
    app.config['LOGIN_DISABLED'] = not conf.getboolean(
        'webserver', 'AUTHENTICATE')

    app.config['SESSION_COOKIE_HTTPONLY'] = True
    app.config['SESSION_COOKIE_SECURE'] = conf.getboolean('webserver', 'COOKIE_SECURE')
    app.config['SESSION_COOKIE_SAMESITE'] = conf.get('webserver', 'COOKIE_SAMESITE')

    if config:
        app.config.from_mapping(config)

    csrf.init_app(app)

    app.config['TESTING'] = testing

    airflow.load_login()
    airflow.login.LOGIN_MANAGER.init_app(app)

    from airflow import api
    api.load_auth()
    api.API_AUTH.api_auth.init_app(app)

    # flake8: noqa: F841
    cache = Cache(app=app, config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': '/tmp'})

    app.register_blueprint(routes)

    configure_logging()

    with app.app_context():
        from airflow.www import views

        admin = Admin(
            app, name='Airflow',
            static_url_path='/admin',
            index_view=views.HomeView(endpoint='', url='/admin', name="DAGs"),
            template_mode='bootstrap3',
        )
        av = admin.add_view
        vs = views
        av(vs.Airflow(name='DAGs', category='DAGs'))

        if not conf.getboolean('core', 'secure_mode'):
            av(vs.QueryView(name='Ad Hoc Query', category="Data Profiling"))
            av(vs.ChartModelView(
                models.Chart, Session, name="Charts", category="Data Profiling"))
        av(vs.KnownEventView(
            models.KnownEvent,
            Session, name="Known Events", category="Data Profiling"))
        av(vs.SlaMissModelView(
            models.SlaMiss,
            Session, name="SLA Misses", category="Browse"))
        av(vs.TaskInstanceModelView(models.TaskInstance,
                                    Session, name="Task Instances", category="Browse"))
        av(vs.TaskExecutionModelView(models.TaskExecution,
                                     Session, name="Task Executions", category="Browse"))
        av(vs.EventModelView(EventModel,
                                     Session, name="Events", category="Browse"))
        av(vs.LogModelView(
            models.Log, Session, name="Logs", category="Browse"))
        av(vs.JobModelView(
            jobs.BaseJob, Session, name="Jobs", category="Browse"))
        av(vs.PoolModelView(
            models.Pool, Session, name="Pools", category="Admin"))
        av(vs.ConfigurationView(
            name='Configuration', category="Admin"))
        av(vs.UserModelView(
            models.User, Session, name="Users", category="Admin"))
        av(vs.ConnectionModelView(
            Connection, Session, name="Connections", category="Admin"))
        av(vs.VariableView(
            models.Variable, Session, name="Variables", category="Admin"))
        av(vs.XComView(
            models.XCom, Session, name="XComs", category="Admin"))

        if "dev" in version.version:
            airflow_doc_site = "https://airflow.readthedocs.io/en/latest"
        else:
            airflow_doc_site = 'https://airflow.apache.org/docs/{}'.format(version.version)

        admin.add_link(base.MenuLink(
            name="Website",
            url='https://airflow.apache.org',
            category="Docs"))
        admin.add_link(base.MenuLink(
            category='Docs', name='Documentation',
            url=airflow_doc_site))
        admin.add_link(
            base.MenuLink(category='Docs',
                          name='GitHub',
                          url='https://github.com/apache/airflow'))

        av(vs.VersionView(name='Version', category="About"))

        av(vs.DagRunModelView(
            models.DagRun, Session, name="DAG Runs", category="Browse"))
        av(vs.DagModelView(models.DagModel, Session, name=None))
        # Hack to not add this view to the menu
        admin._menu = admin._menu[:-1]

        def integrate_plugins():
            """Integrate plugins to the context"""
            log = LoggingMixin().log
            from airflow.plugins_manager import (
                admin_views, flask_blueprints, menu_links)
            for v in admin_views:
                log.debug('Adding view %s', v.name)
                admin.add_view(v)
            for bp in flask_blueprints:
                log.debug("Adding blueprint %s:%s", bp["name"], bp["blueprint"].import_name)
                app.register_blueprint(bp["blueprint"])
            for ml in sorted(menu_links, key=lambda x: x.name):
                log.debug('Adding menu link %s', ml.name)
                admin.add_link(ml)

        integrate_plugins()

        import airflow.www.api.experimental.endpoints as e
        # required for testing purposes otherwise the module retains
        # a link to the default_auth
        if app.config['TESTING']:
            six.moves.reload_module(e)

        app.register_blueprint(e.api_experimental, url_prefix='/api/experimental')

        @app.context_processor
        def jinja_globals():
            return {
                'hostname': get_hostname() if conf.getboolean(
                    'webserver', 'EXPOSE_HOSTNAME',
                    fallback=True) else 'redact',
                'navbar_color': conf.get(
                    'webserver', 'NAVBAR_COLOR'),
                'log_fetch_delay_sec': conf.getint(
                    'webserver', 'log_fetch_delay_sec', fallback=2),
                'log_auto_tailing_offset': conf.getint(
                    'webserver', 'log_auto_tailing_offset', fallback=30),
                'log_animation_speed': conf.getint(
                    'webserver', 'log_animation_speed', fallback=1000)
            }

        @app.before_request
        def before_request():
            _force_log_out_after = conf.getint('webserver', 'FORCE_LOG_OUT_AFTER', fallback=0)
            if _force_log_out_after > 0:
                flask.session.permanent = True
                app.permanent_session_lifetime = datetime.timedelta(minutes=_force_log_out_after)
                flask.session.modified = True
                flask.g.user = flask_login.current_user

        @app.after_request
        def apply_caching(response):
            _x_frame_enabled = conf.getboolean('webserver', 'X_FRAME_ENABLED', fallback=True)
            if not _x_frame_enabled:
                response.headers["X-Frame-Options"] = "DENY"
            return response

        @app.teardown_appcontext
        def shutdown_session(exception=None):
            settings.Session.remove()

        return app
Example #25
0
        else:
            flash('You cannot access that page!', category='error')
            self.inaccessible_callback(name='')

    def inaccessible_callback(self, name, **kwargs):
        abort(403)


admin = Admin(index_view=MyAdminIndexView(), template_mode='bootstrap4')
admin.add_view(AdminUserModelView(User, db.session, category='People'))
admin.add_view(AdminModelView(Pupil, db.session, category='People'))
admin.add_view(AdminModelView(Parent, db.session, category='People'))
admin.add_view(AdminModelView(Proposal, db.session))
admin.add_view(AdminModelView(ClassEvent, db.session))
admin.add_view(AdminModelView(Class, db.session))
admin.add_link(MenuLink(name='Logout', category='', url='/logout'))


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(Config)

    db.init_app(app)
    mail.init_app(app)
    admin.init_app(app)
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))
Example #26
0
from flask_admin import Admin
from flask_admin.menu import MenuLink

from flask_site import create_app, db
from flask_site.about.models import About
from flask_site.admin import AdminPostView, AdminUserView, AdminPageView, ContactThankYouAdminPageView, \
    UniversalPageAdmin, RolePageView, LogoutAdminMenuLink
from flask_site.blog.models import Post
from flask_site.common.filters import subtract
from flask_site.contact.models import Contact, ContactThankYou
from flask_site.main.models import Home
from flask_site.universal_page.models import UniversalPage
from flask_site.users.models import User, Role

app = create_app()
admin = Admin(app, index_view=AdminPostView(Post, db.session, url='/admin'))
admin.add_view(AdminUserView(User, db.session))
admin.add_view(AdminPageView(About, db.session))
admin.add_view(AdminPageView(Home, db.session))
admin.add_view(AdminPageView(Contact, db.session))
admin.add_view(ContactThankYouAdminPageView(ContactThankYou, db.session))
admin.add_view(UniversalPageAdmin(UniversalPage, db.session))
admin.add_view(RolePageView(Role, db.session))
admin.add_link(LogoutAdminMenuLink(name='Logout', url='/logout'))
admin.add_link(MenuLink(name="Home Page", url='/'))

app.jinja_env.filters['subtract'] = subtract

if __name__ == '__main__':
    app.run()
Example #27
0
from datetime import datetime
from flask import g, redirect, request, url_for
from flask_admin import Admin, AdminIndexView, expose
from flask_admin.contrib.sqla import ModelView
from flask_admin.menu import MenuLink

from app import app, db 
from models import Book, LPElement, User

class AdminAuthentication(object):
  def is_accessible(self):
    return g.user.is_authenticated and g.user.is_admin()

class BaseModelView(AdminAuthentication, ModelView):
  pass

class IndexView(AdminIndexView):
  @expose('/')
  def index(self):
    if not (g.user.is_authenticated and g.user.is_admin()):
      return redirect(url_for('login', next=request.path))
    return self.render('admin/index.html', now=datetime.utcnow())

admin = Admin(app, 'Searchinator Admin', index_view=IndexView())
admin.add_view(ModelView(Book, db.session))
admin.add_view(ModelView(LPElement, db.session))
admin.add_view(ModelView(User, db.session))
admin.add_link(MenuLink(name='Back to App', url='/'))
Example #28
0
class Teacher(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)

    def __repr__(self):
        return f"teacher id: {self.username}, password: {self.password}"

"""class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))"""

admin.add_view(ModelView(Student, db.session))
admin.add_view(ModelView(Teacher, db.session))
admin.add_link(MenuLink(name='Make Announcements', category='Actions', url='/makeannouncement'))
admin.add_link(MenuLink(name='Return Home', category='Actions', url='/home'))

"""class Admin(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), nullable=False)
    password = db.Column(db.String(60), nullable=False)"""

"""def __repr__(self):
    return f"admin id: {self.name}, password: {self.password}"""""




@app.route('/')
@app.route('/home', methods = ['GET', 'POST'])
Example #29
0

class UserTools(ModelView):
    """User tools"""
    can_create = False
    can_delete = True
    page_size = 50
    column_list = ['email', 'active', 'roles']
    form_edit_rules = ['email', 'active', 'roles']
    column_searchable_list = ['email']


class VacationTools(ModelView):
    """Vacation Tools"""
    can_create = False
    can_delete = False
    column_searchable_list = [
        User.email, AvaliableVacationDay.avaliable_day, State.name
    ]


admin = Admin(app, name="Vacation Manager", index_view=MyAdminIndexView())
admin.add_link(MenuLink(name='Home Page', url='/', category='Go To'))
admin.add_link(MenuLink(name='Logout', url='/logout', category='Go To'))
admin.add_view(UserTools(User, db.session))
admin.add_view(VacationTools(UserAvaliableVacationDays, db.session))

user_manager = UserManager(app, db, User)
# pylint: disable=wrong-import-position
from vacation_manager import routes, models
Example #30
0
    def inaccessible_callback(self, name, **kwargs):
        '''
        if not accessible then go to login
        '''
        return redirect(url_for('admin.login_view', next=request.url))


ADMIN = Admin(APP,
              "QeeqBox",
              index_view=CustomAdminIndexView(url='/'),
              base_template='base.html',
              template_mode='bootstrap3')
ADMIN.add_link(
    CustomMenuLink(name='',
                   category='',
                   url="https://github.com/qeeqbox/analyzer",
                   icon_type='glyph',
                   icon_value='glyphicon-star'))
ADMIN.add_link(
    CustomMenuLink(
        name='',
        category='',
        url="https://github.com/qeeqbox/analyzer/archive/master.zip",
        icon_type='glyph',
        icon_value='glyphicon-download-alt'))
ADMIN.add_link(
    CustomMenuLink(name='',
                   category='',
                   url="https://github.com/qeeqbox/analyzer/subscription",
                   icon_type='glyph',
                   icon_value='glyphicon glyphicon-eye-open'))
Example #31
0
def create_app(config=None, testing=False):

    log = LoggingMixin().log

    app = Flask(__name__)
    if configuration.conf.getboolean('webserver', 'ENABLE_PROXY_FIX'):
        app.wsgi_app = ProxyFix(app.wsgi_app)
    app.secret_key = configuration.conf.get('webserver', 'SECRET_KEY')
    app.config['LOGIN_DISABLED'] = not configuration.conf.getboolean(
        'webserver', 'AUTHENTICATE')

    csrf.init_app(app)

    app.config['TESTING'] = testing

    airflow.load_login()
    airflow.login.login_manager.init_app(app)

    from airflow import api
    api.load_auth()
    api.api_auth.init_app(app)

    # flake8: noqa: F841
    cache = Cache(app=app, config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': '/tmp'})

    app.register_blueprint(routes)

    configure_logging()

    with app.app_context():
        from airflow.www import views

        admin = Admin(
            app, name='Airflow',
            static_url_path='/admin',
            index_view=views.HomeView(endpoint='', url='/admin', name="DAGs"),
            template_mode='bootstrap3',
        )
        av = admin.add_view
        vs = views
        av(vs.Airflow(name='DAGs', category='DAGs'))

        if not conf.getboolean('core', 'secure_mode'):
            av(vs.QueryView(name='Ad Hoc Query', category="Data Profiling"))
            av(vs.ChartModelView(
                models.Chart, Session, name="Charts", category="Data Profiling"))
        av(vs.SlaMissModelView(
            models.SlaMiss,
            Session, name="SLA Misses", category="Browse"))
        av(vs.TaskInstanceModelView(models.TaskInstance,
            Session, name="Task Instances", category="Browse"))
        av(vs.LogModelView(
            models.Log, Session, name="Logs", category="Browse"))
        av(vs.JobModelView(
            jobs.BaseJob, Session, name="Jobs", category="Browse"))
        av(vs.PoolModelView(
            models.Pool, Session, name="Pools", category="Admin"))
        av(vs.ConfigurationView(
            name='Configuration', category="Admin"))
        av(vs.UserModelView(
            models.User, Session, name="Users", category="Admin"))
        av(vs.ConnectionModelView(
            Connection, Session, name="Connections", category="Admin"))
        av(vs.VariableView(
            models.Variable, Session, name="Variables", category="Admin"))
        av(vs.XComView(
            models.XCom, Session, name="XComs", category="Admin"))

        admin.add_link(base.MenuLink(
            category='Docs', name='Documentation',
            url='https://airflow.apache.org/'))
        admin.add_link(
            base.MenuLink(category='Docs',
                          name='Github',
                          url='https://github.com/apache/airflow'))

        av(vs.VersionView(name='Version', category="About"))

        av(vs.DagRunModelView(
            models.DagRun, Session, name="DAG Runs", category="Browse"))
        av(vs.DagModelView(models.DagModel, Session, name=None))
        # Hack to not add this view to the menu
        admin._menu = admin._menu[:-1]

        def integrate_plugins():
            """Integrate plugins to the context"""
            from airflow.plugins_manager import (
                admin_views, flask_blueprints, menu_links)
            for v in admin_views:
                log.debug('Adding view %s', v.name)
                admin.add_view(v)
            for bp in flask_blueprints:
                log.debug('Adding blueprint %s', bp.name)
                app.register_blueprint(bp)
            for ml in sorted(menu_links, key=lambda x: x.name):
                log.debug('Adding menu link %s', ml.name)
                admin.add_link(ml)

        integrate_plugins()

        import airflow.www.api.experimental.endpoints as e
        # required for testing purposes otherwise the module retains
        # a link to the default_auth
        if app.config['TESTING']:
            six.moves.reload_module(e)

        app.register_blueprint(e.api_experimental, url_prefix='/api/experimental')

        @app.context_processor
        def jinja_globals():
            return {
                'hostname': get_hostname(),
                'navbar_color': configuration.get('webserver', 'NAVBAR_COLOR'),
            }

        @app.teardown_appcontext
        def shutdown_session(exception=None):
            settings.Session.remove()

        return app
Example #32
0
    column_searchable_list = ['whitepapers.WTitle']
    column_sortable_list = ('whitepapers','whitepapers.WTitle')
    column_labels = dict(WWID='White Paper',
            WViews='Views', whitepaper_month='Month'
    )
    form_args = dict(
        whitepapers = dict(validators=[InputRequired(message='Please Select a whitepaper'),
                                 DataRequired(message='Please Select a whitepaper')]),
        whitepaper_month = dict(validators=[InputRequired(message='Please select a month'),
                                       DataRequired(message='Pleasea select a month')]),
        WViews = dict(validators=[DataRequired(message='Please provide Video Duration'),
                                             NumberRange(min=0, max=999999, message='Please enter the number of views')])
    )

real_home = menu.MenuLink(name='Back to Application',url='/')
admin.add_link(real_home)
admin.add_view(AudienceProfileModelView(AudienceProfile,db.session, category='Company'))
admin.add_view(BlogModelView(Blog,db.session, category='Company'))
admin.add_view(BlogStatsModelView(BlogStats,db.session, category='Company'))
admin.add_view(EmailModelView(Email,db.session, category='Company'))
admin.add_view(EmailStatsModelView(EmailStats,db.session, category='Company'))
admin.add_view(TopCompanyModelView(TopCompany, db.session, category='Company'))
admin.add_view(VideoModelView(Video, db.session, category='Video'))
admin.add_view(VideoStatsModelView(VideoStats,db.session, category='Video'))
admin.add_view(VideoTopCompanyModelView(VideoTopCompany, db.session, category='Video'))
admin.add_view(WhitepaperModelView(Whitepaper, db.session, category='Company'))
admin.add_view(WhitepaperStatsModelView(WhitepaperStats, db.session, category='Company'))



Example #33
0
    def __init__(self, session, **kwargs):
        super(ExpenseAdminView, self).__init__(Tasks, session, **kwargs)


class UserAdminView(MyModelView):
    column_exclude_list = ('password')

    def is_accessible(self):
        return current_user.has_role('admin')

    def __init__(self, session, **kwargs):
        super(UserAdminView, self).__init__(User, session, **kwargs)


class RoleView(MyModelView):
    def is_accessible(self):
        return current_user.has_role('admin')

    def __init__(self, session, **kwargs):
        super(RoleView, self).__init__(Role, session, **kwargs)


admin = Admin(app, name='Hive Admin', index_view=MyAdminIndexView(), template_mode='bootstrap3')
admin.add_view(ExpenseAdminView(db.session))
admin.add_view(UserAdminView(db.session))
admin.add_view(RoleView(db.session))
admin.add_link(base.MenuLink('Web Home', endpoint="index"))
admin.add_link(base.MenuLink('Logout', endpoint="logout"))

# --------------------------  END ADMIN PART ---------------------------------
Example #34
0
def create_app(extra_config_settings={}):
    # Create a Flask applicaction.

    # Instantiate Flask
    app = Flask(__name__)

    # Load App Config settings
    # Load common settings from 'app/settings.py' file
    app.config.from_object('app.settings')
    # Load local settings from 'app/local_settings.py'
    app.config.from_object('app.local_settings')
    # Load extra config settings from 'extra_config_settings' param
    app.config.update(extra_config_settings)

    # Setup Flask-Extensions -- do this _after_ app config has been loaded

    # Setup Flask-SQLAlchemy
    db.init_app(app)

    # Setup Flask-Migrate
    migrate.init_app(app, db)

    # Setup Flask-Mail
    mail.init_app(app)

    # Setup WTForms CSRFProtect
    csrf_protect.init_app(app)

    # Register blueprints
    from app.views.public_views import public_blueprint
    app.register_blueprint(public_blueprint)
    from app.views.members_views import members_blueprint
    app.register_blueprint(members_blueprint)
    # from app.views.admin_views import admin_blueprint
    # app.register_blueprint(admin_blueprint)

    # Define bootstrap_is_hidden_field for flask-bootstrap's bootstrap_wtf.html
    from wtforms.fields import HiddenField

    def is_hidden_field_filter(field):
        return isinstance(field, HiddenField)

    app.jinja_env.globals['bootstrap_is_hidden_field'] = is_hidden_field_filter

    # Setup an error-logger to send emails to app.config.ADMINS
    init_email_error_handler(app)

    # Setup Flask-User to handle user account related forms
    from .models.user_models import User, MyRegisterForm
    from .views.members_views import user_profile_page
    db_adapter = SQLAlchemyAdapter(db, User)  # Setup the SQLAlchemy DB Adapter
    UserManager(
        db_adapter,
        app,  # Init Flask-User and bind to app
        register_form=MyRegisterForm,  # Custom register form UserProfile fields
        user_profile_view_function=user_profile_page,
    )

    babel.init_app(app)  # Initialize Flask-Babel

    Bootstrap(app)  # Initialize flask_bootstrap

    # Admin part
    class AdminUserView(ModelView):
        can_create = False
        column_display_pk = True
        column_exclude_list = ('password')
        form_overrides = dict(password=HiddenField)

    class AdmUsersRolesView(ModelView):
        column_display_pk = True

    class AdmRolesView(ModelView):
        column_display_pk = True

    from .models.models import AdmUsers, AdmUsersRoles, AdmRoles
    admin = Admin(app, template_mode='bootstrap3')
    admin.add_view(AdminUserView(AdmUsers, db.session, name='Users'))
    admin.add_view(AdmRolesView(AdmUsersRoles, db.session, name='Roles-User'))
    admin.add_view(AdmUsersRolesView(AdmRoles, db.session, name='Role'))
    path = op.join(op.dirname(__file__), 'static')
    admin.add_view(FileAdmin(path, '/static/', name='Files'))
    admin.add_link(MenuLink(name='Profile', endpoint='user.profile'))
    admin.add_link(MenuLink(name='Logout', endpoint='user.logout'))

    return app
Example #35
0
File: views.py Project: OSPK/kef
    form_extra_fields = {
        'img': form.ImageUploadField('Featured Image',
                                      base_path=file_path)
    }


admin = Admin(app, template_mode='bootstrap3')
admin.add_view(UserModelView(User, db.session))
admin.add_view(UniModelView(Universities, db.session))
admin.add_view(MyModelView(Colleges, db.session))
admin.add_view(ProgAdmin(Programs, db.session))
admin.add_view(PostsView(Posts, db.session))
admin.add_view(ImageView(Image, db.session))
admin.add_view(VideosView(Video, db.session))
admin.add_view(WidgetsView(Widgets, db.session))
admin.add_link(MenuLink(name='Site', category='', url="/"))
admin.add_link(MenuLink(name='Logout', category='', url="/logout"))
# admin.add_view(MyFileAdmin(file_path, '/static/', name='Static Files'))

CITIES = ['Abbottabad', 'Bagh', 'Bahawalpur', 'Bannu', 'Bhimber', 'Charsadda', 'D.I.Khan', 'Dera Ghazi Khan', 'Dir', 'Faisalabad', 'Gilgit', 'Gujranwala', 'Gujrat', 'Haripur', 'Hyderabad', 'Islamabad', 'Jamshoro', 'Karachi', 'Karak', 'Khairpur', 'Khuzdar', 'Kohat', 'Kotli', 'Lahore', 'Larkana', 'Lasbela', 'Loralai', 'Malakand', 'Manshera', 'Mardan', 'Mirpur', 'Multan', 'Muzaffarabad', 'Nawabshah', 'Nerain Sharif', 'Nowshera', 'Peshawar', 'Quetta', 'Rahim Yar Khan', 'Rawalakot', 'Rawalpindi', 'Sakrand', 'Sargodha', 'Sialkot', 'Sukkur', 'Swabi', 'Swat', 'Tandojam', 'Taxila', 'Topi', 'Turbat', 'Wah']
PROVINCES = ["Islamabad", "Khyber Pakhtunkhwa", "Punjab", "Sindh", "Balochistan", "Azad Jammu and Kashmir", "Gilgit-Baltistan"]

@app.context_processor
def ctites_provinces():
    return {'cities': CITIES, 'provinces': PROVINCES}


def widget_maker(placement, **kwargs):
    category = kwargs.get('category', '*')

    if placement=='homepage':
Example #36
0
from .assets import bundles
assets = Environment(app)
assets.append_path(os.path.join(os.path.dirname(__file__), './static'))
assets.append_path(
    os.path.join(os.path.dirname(__file__), './static/bower_components'))
assets.register(bundles)

# Flask-Admin
admin = Admin(app,
              name='Interface Admin',
              index_view=StatisticsView(url='/admin', name='Vue générale'))
admin.add_view(CompanyView(get_db().companies, name='Entreprises'))
admin.add_view(UserView(get_db().users, name='Utilisateurs'))
admin.add_view(JobView(get_db().jobs, name='Offres'))
admin.add_view(StreamView(get_db().stream, name='Stream'))
admin.add_link(MenuLink(name='Se déconnecter', url='/deconnexion'))

# SSLify
with app.app_context():
    sslify = SSLify()
    sslify.init_app(app)

# CDN
cdn = CDN()
cdn.init_app(app)

# S3 client
s3_client = boto3.client('s3')

# Blueprints
from .views import bp as bp_main
Example #37
0
@app.route("/api/import/csv/demand", methods=['POST'])
def api_import_csv():
    if request.method == 'POST':
        print 'uploading CSV'
        request.files['upload'].save("uploads/demand.csv")
        return redirect("/admin")
    return redirect("/admin")

@app.route("/api/database/demand")
def api_demand():
    data = []
    for row in session.query(Demand).order_by(Demand.id).all():
        data.append({
            'id': row.id,
            'period': row.period,
            'demand': row.demand,
            'week': row.week
        })
    return json.dumps(data)
    

if __name__ == "__main__":
    admin.add_view(ModelView(Flight, session))
    admin.add_view(ModelView(Seasonal_schedule, session))
    admin.add_view(ModelView(Daily_schedule, session))
    admin.add_view(ModelView(Demand, session))
    admin.add_link(MenuLink(name='Back Home', url='/'))
    Base.metadata.create_all(engine)
    app.run(debug=True)
Example #38
0
    login_user()
    return redirect(url_for('admin.index'))


class AuthenticatedMenuLink(MenuLink):
    def is_accessible(self):
        return current_user.is_authenticated


class NotAuthenticatedMenuLink(MenuLink):
    def is_accessible(self):
        return not current_user.is_authenticated


admin = Admin(app, name='web_develop', template_mode='bootstrap3')
admin.add_link(NotAuthenticatedMenuLink(name='Login', endpoint='login_view'))
admin.add_link(AuthenticatedMenuLink(name='Logout', endpoint='logout_view'))


class MyAdminView(BaseView):
    @expose('/')
    def index(self):
        return self.render('authenticated-admin.html')

    def is_accessible(self):
        return current_user.is_authenticated


admin.add_view(ModelView(User, db.session))

path = os.path.join(os.path.dirname(__file__), 'static')
Example #39
0
    return redirect(url_for('admin.index'))


@app.route('/logout/')
def logout_view():
    logout_user()
    return redirect(url_for('admin.index'))


admin = Admin(app, name='web_develop', template_mode='bootstrap3')
admin.add_view(ModelView(User, db.session))

path = os.path.join(os.path.dirname(__file__), '../../static')
admin.add_view(FileAdmin(path, '/static/', name='Static Files'))

admin.add_view(MyAdminView(name='Authenticated'))

admin.add_link(MenuLink(name='Back Home', url='/'))
admin.add_link(NotAuthenticatedMenuLink(name='Login',
                                        endpoint='login_view'))
admin.add_link(MenuLink(name='Google', category='Links',
                        url='http://www.google.com/'))
admin.add_link(MenuLink(name='Github', category='Links',
                        url='https://github.com/dongweiming'))
admin.add_link(AuthenticatedMenuLink(name='Logout',
                                     endpoint='logout_view'))


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000, debug=True)
Example #40
0
            user = load_user(current_user.id)
            return user.isAdmin()
        return current_user.is_authenticated

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for('login'))


class MyAdminIndexView(AdminIndexView):
    def is_accessible(self):
        if current_user.is_authenticated:
            user = load_user(current_user.id)
            return user.isAdmin()
        return current_user.is_authenticated

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for('login'))


admin = Admin(app, index_view=MyAdminIndexView(), name="Quizards")

admin.add_view(MyModelView(User, db.session))
admin.add_view(MyModelView(Post, db.session))
admin.add_view(MyModelView(Quizzes, db.session))
admin.add_view(MyQuestionView(Questions, db.session))
admin.add_view(MyMCQuestionView(multiChoice, db.session))
admin.add_view(MyLQuestionView(LongQuestions, db.session))
admin.add_view(MyLAnswerView(LongAnswers, db.session))
admin.add_view(MyMarksView(quizMarks, db.session))
admin.add_link(MenuLink(name='Back to Website', category='', url='/'))
Example #41
0
from flask_admin.menu import MenuLink


class MyAdminIndexView(AdminIndexView):
    def is_accessible(self):
        print(current_user, flush=True)
        if current_user.is_authenticated:
            print('AUTENTICADO', flush=True)
            return current_user.has_role('Gerencia')
        else:
            print('NO AUTENTICADO', flush=True)


class LogoutMenuLink(MenuLink):
    def is_accessible(self):
        return current_user.is_authenticated


admin = Admin(app, index_view=MyAdminIndexView())
admin.add_link(LogoutMenuLink(name='Cerrar Sesión', category='',
                              url="/logout"))
admin.add_view(ModelView(Provincia, db.session))
admin.add_view(ModelView(Localidad, db.session))
admin.add_view(ModelView(Usuario, db.session))
admin.add_view(ModelView(Rol, db.session))
admin.add_view(ModelView(Permiso, db.session))
admin.add_view(ModelView(Persona, db.session))

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
Example #42
0
class AdministrationApplication(object):
    def __init__(self, app, cfg_manager, core_server, bypass_authz=False):
        super(AdministrationApplication, self).__init__()
        app.json_encoder = CustomJSONEncoder

        self.cfg_manager = cfg_manager
        pub_directory = os.path.join(
            os.path.abspath(self.cfg_manager.get('deployment_dir', '')), 'pub')
        self.config = cfg_manager
        db.initialize(cfg_manager)

        self.core_server = core_server

        db_session = scoped_session(
            sessionmaker(autocommit=False, autoflush=False, bind=db.engine))

        files_directory = cfg_manager.get_doc_value(
            configuration_doc.CORE_STORE_STUDENTS_PROGRAMS_PATH)
        core_server_url = cfg_manager.get_value('core_server_url', '')
        self.script_name = urlparse.urlparse(core_server_url).path.split(
            '/weblab')[0] or ''

        self.app = app

        static_folder = os.path.abspath(
            os.path.join(os.path.dirname(web.__file__), 'static'))

        # Not allowed
        @app.route('/weblab/not_allowed')
        def not_allowed():
            return "You are logged in, but not allowed to see this content. Please log in with a proper account"

        # Back
        @app.route('/weblab/back')
        def back_to_client():
            return redirect(url_for('core_webclient.labs'))

        ################################################
        #
        #  Administration panel for administrators
        #
        #

        admin_url = '/weblab/admin'
        category_system = lazy_gettext("System")
        category_users = lazy_gettext("Users")
        category_logs = lazy_gettext("Logs")
        category_experiments = lazy_gettext("Experiments")
        category_permissions = lazy_gettext("Permissions")
        self.admin = Admin(index_view=admin_views.HomeView(db_session,
                                                           url=admin_url),
                           name=lazy_gettext('WebLab-Deusto Admin'),
                           url=admin_url,
                           endpoint=admin_url,
                           base_template='weblab-master.html',
                           template_mode='bootstrap3')
        self.admin.weblab_admin_app = self

        self.admin.add_view(
            admin_views.SystemProperties(db_session,
                                         category=category_system,
                                         name=lazy_gettext('Settings'),
                                         endpoint='system/settings',
                                         url='settings'))
        self.admin.add_view(
            admin_views.AuthsPanel(db_session,
                                   category=category_system,
                                   name=lazy_gettext('Authentication'),
                                   endpoint='system/auth',
                                   url='auth'))
        if not os.path.exists(pub_directory):
            try:
                os.mkdir(pub_directory)
            except (IOError, OSError) as e:
                print(
                    "WARNING: %s not found. Create it to upload files to it." %
                    pub_directory)

        if os.path.exists(pub_directory):
            self.admin.add_view(
                admin_views.AdministratorFileAdmin(
                    pub_directory,
                    category=category_system,
                    name=lazy_gettext('Public directory'),
                    endpoint='system/pub',
                    url='pub'))

        self.admin.add_view(
            admin_views.UsersAddingView(
                db_session,
                category=category_users,
                name=lazy_gettext('Add multiple users'),
                endpoint='users/multiple'))
        self.admin.add_view(
            admin_views.UsersPanel(db_session,
                                   category=category_users,
                                   name=lazy_gettext('Users'),
                                   endpoint='users/users',
                                   url='users'))
        self.admin.add_view(
            admin_views.GroupsPanel(db_session,
                                    category=category_users,
                                    name=lazy_gettext('Groups'),
                                    endpoint='users/groups',
                                    url='groups'))
        self.admin.add_view(
            admin_views.InvitationsPanel(db_session,
                                         category=category_users,
                                         name=lazy_gettext('Invitations'),
                                         endpoint='users/invitations',
                                         url='invitations'))

        self.admin.add_view(
            admin_views.UserUsedExperimentPanel(files_directory,
                                                db_session,
                                                category=category_logs,
                                                name=lazy_gettext('User logs'),
                                                endpoint='logs/users',
                                                url='logs'))

        self.admin.add_view(
            admin_views.ExperimentCategoryPanel(
                db_session,
                category=category_experiments,
                name=lazy_gettext('Categories'),
                endpoint='experiments/categories',
                url='experiments/categories'))
        self.admin.add_view(
            admin_views.ExperimentPanel(db_session,
                                        category=category_experiments,
                                        name=lazy_gettext('Experiments'),
                                        endpoint='experiments/experiments',
                                        url='experiments'))
        # TODO: Until finished, do not display
        # self.admin.add_view(admin_views.SchedulerPanel(db_session,         category = category_experiments, name = lazy_gettext('Schedulers'), endpoint = 'experiments/schedulers'))

        self.admin.add_view(
            admin_views.PermissionsAddingView(db_session,
                                              category=category_permissions,
                                              name=lazy_gettext('Create'),
                                              endpoint='permissions/create',
                                              url='permissions'))
        self.admin.add_view(
            admin_views.UserPermissionPanel(db_session,
                                            category=category_permissions,
                                            name=lazy_gettext('User'),
                                            endpoint='permissions/user'))
        self.admin.add_view(
            admin_views.GroupPermissionPanel(db_session,
                                             category=category_permissions,
                                             name=lazy_gettext('Group'),
                                             endpoint='permissions/group'))
        self.admin.add_view(
            admin_views.RolePermissionPanel(db_session,
                                            category=category_permissions,
                                            name=lazy_gettext('Roles'),
                                            endpoint='permissions/role'))

        self.admin.add_link(
            MenuLink(endpoint='instructor.index',
                     name=lazy_gettext('Instructor panel'),
                     icon_type='glyph',
                     icon_value='glyphicon-stats'))
        self.admin.add_link(
            MenuLink(endpoint='profile.index',
                     name=lazy_gettext('My profile'),
                     icon_type='glyph',
                     icon_value='glyphicon-user'))
        self.admin.add_link(
            MenuLink(endpoint='back_to_client',
                     name=lazy_gettext('Back'),
                     icon_type='glyph',
                     icon_value='glyphicon-log-out'))

        self.admin.init_app(self.app)

        self.full_admin_url = self.script_name + admin_url

        ################################################
        #
        #  Profile panel
        #

        profile_url = '/weblab/profile'
        self.profile = Admin(index_view=profile_views.ProfileHomeView(
            db_session, url=profile_url, endpoint='profile'),
                             name=lazy_gettext('WebLab-Deusto profile'),
                             url=profile_url,
                             endpoint=profile_url,
                             base_template='weblab-master.html',
                             template_mode='bootstrap3')
        self.profile.weblab_admin_app = self

        self.profile.add_view(
            profile_views.ProfileEditView(db_session,
                                          name=lazy_gettext('Edit'),
                                          endpoint='edit'))

        self.profile.add_view(
            profile_views.MyAccessesPanel(files_directory,
                                          db_session,
                                          name=lazy_gettext('My accesses'),
                                          endpoint='accesses'))
        self.profile.add_link(
            MenuLink(endpoint='back_to_client',
                     name=lazy_gettext('Back'),
                     icon_type='glyph',
                     icon_value='glyphicon-log-out'))

        self.profile.init_app(self.app)

        ################################################
        #
        #  Instructors panel
        #

        # TODO. There should be able a new M2M relation between instructors and groups.
        #
        # Instructor should be able to:
        #
        # a) Create new groups (of which they are in charge)
        # b) Make other instructors in charge of these groups
        # c) Add students (and only students) to the system; forcing a group
        # d) Edit users (only students; of those groups that the administrator is in charge of)
        # e) Assign permissions on these courses
        # f) Manage the permissions on these courses
        # g) See the logs of their own students
        # h) See a panel with analytics of each of these groups (this panel is common to the administrator, and has not been implemented)

        instructor_url = '/weblab/instructor'
        instructor_home = instructor_views.InstructorHomeView(
            db_session, url=instructor_url, endpoint='instructor')
        instructor_home.static_folder = static_folder
        self.instructor = Admin(index_view=instructor_home,
                                name=lazy_gettext("Weblab-Deusto instructor"),
                                url=instructor_url,
                                endpoint=instructor_url,
                                base_template='weblab-master.html',
                                template_mode='bootstrap3')
        self.instructor.weblab_admin_app = self

        category_general = lazy_gettext("General")
        category_stats = lazy_gettext("Stats")
        self.instructor.add_view(
            instructor_views.UsersPanel(db_session,
                                        category=category_general,
                                        name=lazy_gettext('Users'),
                                        endpoint='users'))
        self.instructor.add_view(
            instructor_views.GroupsPanel(db_session,
                                         category=category_general,
                                         name=lazy_gettext('Groups'),
                                         endpoint='groups'))
        self.instructor.add_view(
            instructor_views.UserUsedExperimentPanel(
                db_session,
                category=category_general,
                name=lazy_gettext('Raw accesses'),
                endpoint='logs'))

        self.instructor.add_view(
            instructor_views.GroupStats(db_session,
                                        category=category_stats,
                                        name=lazy_gettext('Group'),
                                        endpoint='stats/groups'))
        self.instructor.add_link(
            MenuLink(endpoint='profile.index',
                     name=lazy_gettext('My profile'),
                     icon_type='glyph',
                     icon_value='glyphicon-user'))
        self.instructor.add_link(
            MenuLink(endpoint='back_to_client',
                     name=lazy_gettext('Back'),
                     icon_type='glyph',
                     icon_value='glyphicon-log-out'))

        self.instructor.init_app(self.app)

        ################################################
        #
        #  Other
        #
        self.bypass_authz = bypass_authz

    @property
    def db(self):
        return self.core_server.db

    def get_db(self):
        return self.core_server.db

    def is_admin(self):
        if self.bypass_authz:
            return True

        try:
            session_id = (request.cookies.get('weblabsessionid')
                          or '').split('.')[0]
            if not session_id:
                return False

            with weblab_api(self.core_server, session_id=session_id):
                is_admin = weblab_api.is_admin

            return is_admin
        except:
            traceback.print_exc()
            return False

    def get_user_role(self):
        if self.bypass_authz:
            return 'admin'

        try:
            session_id = (request.cookies.get('weblabsessionid')
                          or '').split('.')[0]
            if session_id:
                try:
                    with weblab_api(self.core_server, session_id=session_id):
                        user_info = weblab.core.server.get_user_information()
                except SessionNotFoundError:
                    # Gotcha
                    traceback.print_exc()
                else:
                    return user_info.role.name
            return None
        except:
            traceback.print_exc()
            return None

    def _reserve_fake_session(self):
        fake_names = ('student1', 'porduna', 'user7', 'admin')
        exc = None
        for fake_name in fake_names:
            try:
                session_id, route = self.core_server._reserve_session(
                    ValidDatabaseSessionId(fake_name, 'administrator'))
            except Exception as exc:
                pass
            else:
                return session_id, route
        raise exc

    def get_permissions(self):
        if self.bypass_authz:
            session_id, _ = self._reserve_fake_session()
            with weblab_api(self.core_server, session_id=session_id.id):
                return weblab.core.server.get_user_permissions()

        session_id = (request.cookies.get('weblabsessionid')
                      or '').split('.')[0]
        if session_id:
            try:
                with weblab_api(self.core_server, session_id=session_id):
                    return weblab.core.server.get_user_permissions()
            except:
                traceback.print_exc()
        return None

    def get_user_information(self):
        if self.bypass_authz:
            session_id, _ = self._reserve_fake_session()
            with weblab_api(self.core_server, session_id=session_id.id):
                return weblab.core.server.get_user_information()

        session_id = (request.cookies.get('weblabsessionid')
                      or '').split('.')[0]
        if session_id:
            try:
                with weblab_api(self.core_server, session_id=session_id):
                    return weblab.core.server.get_user_information()
            except SessionNotFoundError:
                pass
        return None
Example #43
0
# set up the database model if not already set up
from app import models
db.create_all()
db.session.commit()

# setup the User/Role tables with flask-security, create base users/groups if neccessary
userstore = SQLAlchemyUserDatastore(db, models.User, models.Role)
sec = Security(app, userstore)
try:
    with app.app_context():
        userstore.find_or_create_role(name='admin', description='Administrator')
        userstore.find_or_create_role(name='user', description='General user')
        userstore.create_user(email=FIRST_USER_NAME,
                            password=utils.encrypt_password(FIRST_USER_PASS))
        userstore.add_role_to_user(FIRST_USER_NAME, 'admin')
        db.session.commit()
except: db.session.rollback()

# get the view controllers for the app
from app.views import main, admin, common

# set up main as a blueprint, add as many blueprints as necessary
app.register_blueprint(main.main)

# configure the admin interface, populate it with pages and links
app_admin = Admin(app, 'Flask Skeleton Admin', template_mode='bootstrap3', index_view=admin.AdminIndexView())
app_admin.add_view(admin.UserModelView(models.User, db.session))
app_admin.add_view(admin.RoleModelView(models.Role, db.session))
app_admin.add_link(MenuLink(name='Back to Site', url='/'))
Example #44
0
            By default, it will check if the admin class is accessable
            and if it is NOT it will throw a 404.

            :param name:
                View function name
            :param kwargs:
                View function arguments
        """
        if not self.is_accessible():
            return redirect(url_for("login"))


from app import routes, models, errors
admin = Admin(app, name=f'{app_name} Admin Panel', index_view=MyAdminIndex())
admin.add_view(ModelView(models.Post, db.session))
admin.add_link(MenuLink(name='Sign Out', url='/logout'))
app.config['FLASK_ADMIN_SWATCH'] = 'cyborg'

# ERROR LOGGING TO EMAIL
# if not app.debug:
# if app.config['MAIL_SERVER']:
# auth = None
# if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
# auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
# secure = None
# if app.config['MAIL_USE_TLS']:
# secure = ()
# mail_handler = SMTPHandler(
# mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
# fromaddr='no-reply@' + app.config['MAIL_SERVER'],
# toaddrs=app.config['ADMINS'], subject='Musicblog Failure',
Example #45
0
class UserView(ModelView):
    column_exclude_list = ['pwdhash']
    column_editable_list = ['email', 'name']
    def is_accessible(self):
        return current_user.is_authenticated and current_user.is_admin

class ShelterView(ModelView):
    column_exclude_list = ['properties']
    form_excluded_columns = ['properties']
    def is_accessible(self):
        return current_user.is_authenticated and current_user.is_admin

menu_link_back_dashboard = MenuLink(name='Back to dashboard',
                                url='/admin/dashboard')
menu_link_back_home = MenuLink(name='Back to home',
                                url='/')

admin = Admin(current_app,
                name='Management of data',
                template_mode='bootstrap3',
                index_view=AdminIndexView(
                        name='Home',
                        url='/admin/data_management'
                    ))
admin.add_view(UserView(User, db.session))
admin.add_view(ShelterView(Shelter, db.session))
admin.add_view(ValueView(Value, db.session))
admin.add_view(TranslationView(Translation, db.session))
admin.add_link(menu_link_back_home)
admin.add_link(menu_link_back_dashboard)
Example #46
0
    return redirect(url_for("admin_bp.list_organizations"))


# Flask-Admin views


class SecureView(ModelView):
    def is_accessible(self):
        return current_user.is_authenticated and current_user.is_admin


class CustomAdminIndexView(AdminIndexView):
    def is_accessible(self):
        return current_user.is_authenticated and current_user.is_admin


menu_link_back_home = MenuLink(name="Home", url="/")
admin_flask = Admin(
    current_app,
    name="Management of data",
    template_mode="bootstrap3",
    index_view=CustomAdminIndexView(name="Home", url="/admin"),
)
admin_flask.add_view(SecureView(User, db.session))
admin_flask.add_view(SecureView(Organization, db.session))
admin_flask.add_view(SecureView(Schema, db.session))
admin_flask.add_view(SecureView(JsonObject, db.session))
admin_flask.add_view(SecureView(License, db.session))
admin_flask.add_view(SecureView(Event, db.session))
admin_flask.add_link(menu_link_back_home)
Example #47
0
def create_app(config=None):
    app = Flask(__name__)
    app.secret_key = configuration.get('webserver', 'SECRET_KEY')
    app.config['LOGIN_DISABLED'] = not configuration.getboolean('webserver', 'AUTHENTICATE')

    csrf.init_app(app)

    #app.config = config
    airflow.load_login()
    airflow.login.login_manager.init_app(app)

    cache = Cache(
        app=app, config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': '/tmp'})

    app.register_blueprint(ck, url_prefix='/ck')
    app.register_blueprint(routes)
    app.jinja_env.add_extension("chartkick.ext.charts")

    with app.app_context():
        from airflow.www import views

        admin = Admin(
            app, name='Airflow',
            static_url_path='/admin',
            index_view=views.HomeView(endpoint='', url='/admin', name="DAGs"),
            template_mode='bootstrap3',
        )
        av = admin.add_view
        vs = views
        av(vs.Airflow(name='DAGs', category='DAGs'))

        av(vs.QueryView(name='Ad Hoc Query', category="Data Profiling"))
        av(vs.ChartModelView(
            models.Chart, Session, name="Charts", category="Data Profiling"))
        av(vs.KnowEventView(
            models.KnownEvent,
            Session, name="Known Events", category="Data Profiling"))
        av(vs.SlaMissModelView(
            models.SlaMiss,
            Session, name="SLA Misses", category="Browse"))
        av(vs.TaskInstanceModelView(models.TaskInstance,
            Session, name="Task Instances", category="Browse"))
        av(vs.LogModelView(
            models.Log, Session, name="Logs", category="Browse"))
        av(vs.JobModelView(
            jobs.BaseJob, Session, name="Jobs", category="Browse"))
        av(vs.PoolModelView(
            models.Pool, Session, name="Pools", category="Admin"))
        av(vs.ConfigurationView(
            name='Configuration', category="Admin"))
        av(vs.UserModelView(
            models.User, Session, name="Users", category="Admin"))
        av(vs.ConnectionModelView(
            models.Connection, Session, name="Connections", category="Admin"))
        av(vs.VariableView(
            models.Variable, Session, name="Variables", category="Admin"))

        admin.add_link(base.MenuLink(
            category='Docs', name='Documentation',
            url='http://pythonhosted.org/airflow/'))
        admin.add_link(
            base.MenuLink(category='Docs',
                name='Github',url='https://github.com/airbnb/airflow'))

        av(vs.DagRunModelView(
            models.DagRun, Session, name="DAG Runs", category="Browse"))
        av(vs.DagModelView(models.DagModel, Session, name=None))
        # Hack to not add this view to the menu
        admin._menu = admin._menu[:-1]

        def integrate_plugins():
            """Integrate plugins to the context"""
            from airflow.plugins_manager import (
                admin_views, flask_blueprints, menu_links)
            for v in admin_views:
                admin.add_view(v)
            for bp in flask_blueprints:
                app.register_blueprint(bp)
            for ml in menu_links:
                admin.add_link(ml)

        integrate_plugins()

        @app.context_processor
        def jinja_globals():
            return {
                'hostname': socket.gethostname(),
            }

        @app.teardown_appcontext
        def shutdown_session(exception=None):
            settings.Session.remove()

        return app
Example #48
0
def create_app():
    app = Flask(__name__,
                instance_relative_config=True,
                template_folder="templates",
                static_url_path="")

    app.config.from_pyfile("default.py")
    app.config.from_envvar("APP_CONFIG_FILE", silent=True)

    heroku = Heroku()
    heroku.init_app(app)

    db.init_app(app)

    migrate = Migrate(compare_type=True)
    migrate.init_app(app, db)

    admin = Admin(app)
    admin.add_view(AdminModelView(Event, db.session))
    admin.add_link(MenuLink(name="Website", endpoint="index"))
    admin.add_link(MenuLink(name="Login", url="/login"))
    admin.add_link(MenuLink(name="Logout", url='/logout'))

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    @app.context_processor
    def inject_now():
        return {'now': datetime.utcnow()}

    @security.context_processor
    def security_context_processor():
        return dict(admin_base_template=admin.base_template,
                    admin_view=admin.index_view,
                    get_url=url_for,
                    h=helpers)

    @app.before_first_request
    def create_user():
        role = user_datastore.find_or_create_role("admin")
        # password = os.environ.get('ADMIN_PASSWORD')
        if not User.query.filter_by(email=ADMIN_EMAIL).first():
            user = user_datastore.create_user(email=ADMIN_EMAIL,
                                              password=ADMIN_PASSWORD)
            user_datastore.add_role_to_user(user, role)
        db.session.commit()

    @app.route('/')
    @app.route('/index')
    def index():
        events = Event.query.filter(Event.date > datetime.utcnow()).order_by(
            Event.date)
        return render_template('index.html', events=events)

    @app.route('/our_work')
    def our_work():
        current = "our_work"
        return render_template('our_work.html', current=current)

    @app.route('/signup', methods=['POST'])
    def signup():
        email = request.form.get('email')
        api_key = os.environ.get('MAILCHIMP_API_KEY')
        if not api_key or not email:
            flash(
                'Sorry, there was an error during signup. Please come back later and try again!'
            )
            return redirect(url_for('index'))
        server_number = api_key[-4:]
        url = f"https://{server_number}.api.mailchimp.com/3.0/lists/{LIST_ID}/members"
        headers = {
            'content-type': 'application/json',
            'Authorization': f"Basic {api_key}"
        }
        data = {'email_address': email, 'status': 'subscribed'}
        response = requests.post(url, headers=headers, data=json.dumps(data))
        if response.ok or response.json().get('title') == 'Member Exists':
            flash('Thanks for signing up to our newsletter!')
        else:
            flash(
                'Sorry, there was an error during signup. Please come back later and try again!'
            )
        return redirect(url_for('index'))

    return app
Example #49
0
def create_app(config=None, testing=False):

    log = LoggingMixin().log

    app = Flask(__name__)
    app.wsgi_app = ProxyFix(app.wsgi_app)

    if configuration.conf.get('webserver', 'SECRET_KEY') == "temporary_key":
        log.info("SECRET_KEY for Flask App is not specified. Using a random one.")
        app.secret_key = os.urandom(16)
    else:
        app.secret_key = configuration.conf.get('webserver', 'SECRET_KEY')

    app.config['LOGIN_DISABLED'] = not configuration.conf.getboolean(
        'webserver', 'AUTHENTICATE')

    csrf.init_app(app)

    app.config['TESTING'] = testing

    airflow.load_login()
    airflow.login.login_manager.init_app(app)

    from airflow import api
    api.load_auth()
    api.api_auth.init_app(app)

    cache = Cache(
        app=app, config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': '/tmp'})

    app.register_blueprint(routes)

    configure_logging()

    with app.app_context():
        from airflow.www import views

        admin = Admin(
            app, name='Airflow',
            static_url_path='/admin',
            index_view=views.HomeView(endpoint='', url='/admin', name="DAGs"),
            template_mode='bootstrap3',
        )
        av = admin.add_view
        vs = views
        av(vs.Airflow(name='DAGs', category='DAGs'))

        if not conf.getboolean('core', 'secure_mode'):
            av(vs.QueryView(name='Ad Hoc Query', category="Data Profiling"))
            av(vs.ChartModelView(
                models.Chart, Session, name="Charts", category="Data Profiling"))
        av(vs.KnownEventView(
            models.KnownEvent,
            Session, name="Known Events", category="Data Profiling"))
        av(vs.SlaMissModelView(
            models.SlaMiss,
            Session, name="SLA Misses", category="Browse"))
        av(vs.TaskInstanceModelView(models.TaskInstance,
            Session, name="Task Instances", category="Browse"))
        av(vs.LogModelView(
            models.Log, Session, name="Logs", category="Browse"))
        av(vs.JobModelView(
            jobs.BaseJob, Session, name="Jobs", category="Browse"))
        av(vs.PoolModelView(
            models.Pool, Session, name="Pools", category="Admin"))
        av(vs.ConfigurationView(
            name='Configuration', category="Admin"))
        av(vs.UserModelView(
            models.User, Session, name="Users", category="Admin"))
        av(vs.ConnectionModelView(
            models.Connection, Session, name="Connections", category="Admin"))
        av(vs.VariableView(
            models.Variable, Session, name="Variables", category="Admin"))
        av(vs.XComView(
            models.XCom, Session, name="XComs", category="Admin"))

        admin.add_link(base.MenuLink(
            category='Docs', name='Documentation',
            url='https://airflow.incubator.apache.org/'))
        admin.add_link(
            base.MenuLink(category='Docs',
                          name='Github',
                          url='https://github.com/apache/incubator-airflow'))

        av(vs.VersionView(name='Version', category="About"))

        av(vs.DagRunModelView(
            models.DagRun, Session, name="DAG Runs", category="Browse"))
        av(vs.DagModelView(models.DagModel, Session, name=None))
        # Hack to not add this view to the menu
        admin._menu = admin._menu[:-1]

        def integrate_plugins():
            """Integrate plugins to the context"""
            from airflow.plugins_manager import (
                admin_views, flask_blueprints, menu_links)
            for v in admin_views:
                log.debug('Adding view %s', v.name)
                admin.add_view(v)
            for bp in flask_blueprints:
                log.debug('Adding blueprint %s', bp.name)
                app.register_blueprint(bp)
            for ml in sorted(menu_links, key=lambda x: x.name):
                log.debug('Adding menu link %s', ml.name)
                admin.add_link(ml)

        integrate_plugins()

        import airflow.www.api.experimental.endpoints as e
        # required for testing purposes otherwise the module retains
        # a link to the default_auth
        if app.config['TESTING']:
            if six.PY2:
                reload(e)
            else:
                import importlib
                importlib.reload(e)

        app.register_blueprint(e.api_experimental, url_prefix='/api/experimental')

        @app.context_processor
        def jinja_globals():
            return {
                'hostname': get_hostname(),
                'navbar_color': configuration.get('webserver', 'NAVBAR_COLOR'),
            }

        @app.teardown_appcontext
        def shutdown_session(exception=None):
            settings.Session.remove()

        return app
Example #50
0
try:
    with app.app_context():
        userstore.find_or_create_role(name='admin',
                                      description='Administrator')
        userstore.find_or_create_role(name='user', description='General user')
        userstore.create_user(email=FIRST_USER_NAME,
                              password=utils.encrypt_password(FIRST_USER_PASS))
        userstore.add_role_to_user(FIRST_USER_NAME, 'admin')
        db.session.commit()
except:
    db.session.rollback()

docker_client = docker.from_env()

# get the view controllers for the app
from app.views import main, admin, common

# set up main as a blueprint, add as many blueprints as necessary
app.register_blueprint(main.main)

# configure the admin interface, populate it with pages and links
app_admin = Admin(app,
                  'Containerer Admin',
                  template_mode='bootstrap3',
                  index_view=admin.AdminIndexView())
app_admin.add_view(
    admin.ContainerInstanceModelView(models.ContainerInstance, db.session))
app_admin.add_view(admin.UserModelView(models.User, db.session))
app_admin.add_view(admin.RoleModelView(models.Role, db.session))
app_admin.add_link(MenuLink(name='Back to Site', url='/'))