Esempio n. 1
0
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))
    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)
Esempio n. 2
0
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))
    logout_link = MenuLink('logout', '/logout', 'logout') # name, url, endpoint

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

    admin.add_link(logout_link)
Esempio n. 3
0
def config_admin():
    from app.models.User import User
    from app.models.PaperMeta import PaperMeta
    from app.models.ScholarMeta import ScholarMeta

    admin = Admin(name='Academi', index_view = AdminView())

    admin.add_view(UserView(User))
    admin.add_view(PaperMetaView(PaperMeta))
    admin.add_view(ScholarMetaView(ScholarMeta))

    admin.add_link(MenuLink(name = 'Go Back', url = '/'))
    admin.add_link(MenuLink(name = 'Logout', url = '/logout'))

    return admin
Esempio n. 4
0
def init_app(app):
    admin = Admin(app=app, name='簿记员', url='/',
                  index_view=index.IndexView(url='/', menu_class_name='hide'),
                  template_mode='bootstrap3', base_template='base.html')
    admin.add_view(voucher.VoucherView(models.Voucher, db.session, '凭证'))
    admin.add_view(ModelView(
        models.Account, db.session, '科目', category='设置'))
    admin.add_view(ModelView(models.User, db.session, '用户', category='设置'))
    admin.add_view(ModelView(models.Role, db.session, '角色', category='设置'))
    admin.add_view(ModelView(
        models.CompanyRole, db.session, '角色分配', category='设置'))
    admin.add_view(company.CompanyView(
        models.Company, db.session, '公司', category='设置'))
    admin.add_view(
        period.PeriodView(models.Period, db.session, '账期', category='设置'))
    admin.add_link(AnonymousLink('登入', endpoint='security.login'))
    admin.add_link(PeriodLink('period', endpoint='period.index_view'))
    admin.add_link(CompanyLink('company', endpoint='company.index_view'))
    admin.add_link(UserNameLink('name', endpoint='user.edit_view'))
    admin.add_link(UserLink('登出', endpoint='security.logout'))
Esempio n. 5
0
        }
    }
    form_subdocuments = {
        'comments': {
            'form_subdocuments': {
                None: {
                    # Add <hr> at the end of the form
                    'form_rules': ('author', 'content', rules.HTML('<hr>')),
                    'form_widget_args': {
                        'content': {
                            'class': 'ckeditor'
                        }
                    }
                }
            }
        },
        }
    form_ajax_refs = {
        'author': {
            'fields': ('email',),
            'page_size': 10
        }
    }


admin.add_view(UserView(User, name='Usuários'))
admin.add_view(PostView(Post, name='Posts'))
admin.add_view(UploadView(Upload, name='Uploads'))
admin.add_view(AuthenticatedFileView(op.join(op.dirname(__file__), 'static/files'), '/files/', name='Arquivos'))
admin.add_link(MenuLink(name='Voltar', url='/'))
admin.add_link(MenuLink(name='Sair', endpoint='logout_view'))
Esempio n. 6
0
    def on_model_change(self, form, model):
        temp = request.files[form.im.name].read()
        if temp:
            model.im = temp
        
    def _image_link(view, context, model, name):
        return Markup(
            '<a href="/pic/%s">%s</a>' % (model.id, model.id)
        ) if model.id else ""

    def _image_view(view, context, model, name):
        return Markup(
            '<a href="/pic/%s/"><img src="/pic/%s/" style="width: 100px; height: 100px"/></a>' % (model.id, model.id)
        ) if model.im else ""
    column_formatters = { 'id': _image_view }
            
# Add pages to the admin page
admin.add_view(MyModelView(UserType, db.session))
admin.add_view(UserView(User, db.session))
admin.add_view(MyModelView(Case, db.session))
admin.add_view(ImageView(Image, db.session))
admin.add_view(MyModelView(MalType, db.session))
admin.add_view(MyModelView(LabelerType,db.session))
admin.add_view(MyModelView(Labeler,db.session))
admin.add_view(MyModelView(TrainingImage,db.session))
admin.add_view(MyModelView(TrainingImageLabel,db.session,'TIL'))
admin.add_view(MyModelView(TrainingImageLabelCell,db.session,'TILC'))

# Navbar links
admin.add_link(AuthenticatedMenuLink(name='Back to Website', endpoint='dashboard'))
Esempio n. 7
0
        
    def _image_link(view, context, model, name):
        return Markup(
            '<a href="/pic/%s">%s</a>' % (model.id, model.id)
        ) if model.id else ""

    def _image_view(view, context, model, name):
        return Markup(
            '<a href="/pic/%s/" ><img src="/thumb/pic/%s/" class="thumbnail pull-left" style="width: 160px; height: 120px"/></a>' % (model.id, model.id)
        ) if model.im else ""
    column_formatters = { 'id': _image_view }
    
log_path = os.path.join(app.config['BASE_DIR'], "logs")
            
# Add pages to the admin page
admin.add_view(MyModelView(UserType, db.session))
admin.add_view(UserView(User, db.session))
admin.add_view(MyModelView(Case, db.session))
admin.add_view(ImageView(Image, db.session))
admin.add_view(MyModelView(ParType, db.session))
admin.add_view(MyModelView(Chunklist, db.session))
admin.add_view(MyModelView(Chunk, db.session))
admin.add_view(MyModelView(Region, db.session))
admin.add_view(MyModelView(Province, db.session))
admin.add_view(MyModelView(Municipality, db.session))
admin.add_view(MyModelView(Validation, db.session))
admin.add_view(FileAdmin(log_path, '/log/', name='Logs', url="/admin/logview"))

# Navbar links
admin.add_link(AuthenticatedMenuLink(name='Back to Website', endpoint='monitoring'))
Esempio n. 8
0
def is_admin():
    if app.config["DEBUG"]:  # pragma: nocover
        return True
    if not "user_id" in session:
        return False
    user = User.query.filter_by(id=session["user_id"]).first_or_404()
    return bool(user.type & TYPE_ADMINISTRATOR)


class FiktivModelView(ModelView):
    def is_accessible(self):
        return is_admin()


class FiktivFileAdmin(FileAdmin):
    def is_accessible(self):
        return is_admin()

# To add a model to the admin interface, simply add it below.
admin.add_view(ModelView(User, db.session))
admin.add_view(FiktivModelView(Resident, db.session))
admin.add_view(FiktivModelView(BarCharge, db.session, category="Bar"))
admin.add_view(FiktivModelView(Item, db.session, category="Bar"))
admin.add_view(FiktivModelView(SoldItemBar, db.session, category="Bar"))
admin.add_view(FiktivModelView(BarCalendar, db.session, category="Bar"))
admin.add_view(FiktivModelView(Announcement, db.session))
admin.add_view(FiktivModelView(Category, db.session))

admin.add_link(MenuLink(name='FIKtiv', url='/'))

Esempio n. 9
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.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
Esempio n. 10
0
        if temp:
            model.im = temp

    def _image_link(view, context, model, name):
        return Markup('<a href="/pic/%s">%s</a>' %
                      (model.id, model.id)) if model.id else ""

    def _image_view(view, context, model, name):
        return Markup(
            '<a href="/pic/%s/"><img src="/pic/%s/" style="width: 100px; height: 100px"/></a>'
            % (model.id, model.id)) if model.im else ""

    column_formatters = {'id': _image_view}


# Add pages to the admin page
admin.add_view(MyModelView(UserType, db.session))
admin.add_view(UserView(User, db.session))
admin.add_view(MyModelView(Case, db.session))
admin.add_view(ImageView(Image, db.session))
admin.add_view(MyModelView(MalType, db.session))
admin.add_view(MyModelView(LabelerType, db.session))
admin.add_view(MyModelView(Labeler, db.session))
admin.add_view(MyModelView(TrainingImage, db.session))
admin.add_view(MyModelView(TrainingImageLabel, db.session, 'TIL'))
admin.add_view(MyModelView(TrainingImageLabelCell, db.session, 'TILC'))

# Navbar links
admin.add_link(
    AuthenticatedMenuLink(name='Back to Website', endpoint='dashboard'))
Esempio n. 11
0
admin.add_view(
    BadgesHistoryAdmin(BadgesHistory,
                       db.session,
                       name='Badge Activity Log',
                       endpoint='badgehistory',
                       category="Manage Badges"))

admin.add_view(BadgeAPI('Badge API', endpoint='badgeapi'))

admin.add_view(BadgeRequest('Badge Request', endpoint='badge_request'))

admin.add_view(Login('Login', endpoint='login'))
admin.add_view(Logout('Logout', endpoint='logout'))

# menu links - admin only
admin.add_link(
    AdminMenuLink(name='Active Badges',
                  url=app.config['SERVER_URL'] +
                  'badges/?flt0_status_equals=Active',
                  category="Manage Badges"))
admin.add_link(
    AdminMenuLink(name='Deactivated Badges',
                  url=app.config['SERVER_URL'] +
                  'badges/?flt0_status_equals=Deactivated',
                  category="Manage Badges"))
admin.add_link(
    AdminMenuLink(name='Pending Badges',
                  url=app.config['SERVER_URL'] +
                  'badges/?flt0_status_equals=Pending',
                  category="Manage Badges"))
Esempio n. 12
0
def create_app(config=None):
    app = Flask(__name__)
    app.secret_key = conf.get("webserver", "SECRET_KEY")
    # app.config = config
    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.views import HomeView

        admin = Admin(
            app,
            name="Airflow",
            static_url_path="/admin",
            index_view=HomeView(endpoint="", url="/admin"),
            template_mode="bootstrap3",
        )

        from airflow.www import views

        admin.add_view(views.Airflow(name="DAGs"))

        admin.add_view(views.SlaMissModelView(models.SlaMiss, Session, name="SLA Misses", category="Browse"))
        admin.add_view(
            views.TaskInstanceModelView(models.TaskInstance, Session, name="Task Instances", category="Browse")
        )

        admin.add_view(views.LogModelView(models.Log, Session, name="Logs", category="Browse"))
        admin.add_view(views.JobModelView(jobs.BaseJob, Session, name="Jobs", category="Browse"))

        admin.add_view(views.QueryView(name="Ad Hoc Query", category="Data Profiling"))
        admin.add_view(views.ChartModelView(models.Chart, Session, name="Charts", category="Data Profiling"))
        admin.add_view(views.KnowEventView(models.KnownEvent, Session, name="Known Events", category="Data Profiling"))

        admin.add_view(views.PoolModelView(models.Pool, Session, name="Pools", category="Admin"))
        admin.add_view(views.ConfigurationView(name="Configuration", category="Admin"))
        admin.add_view(views.UserModelView(models.User, Session, name="Users", category="Admin"))
        admin.add_view(views.ConnectionModelView(models.Connection, Session, name="Connections", category="Admin"))
        admin.add_view(views.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"))

        admin.add_view(views.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:
                print(bp)
                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
Esempio n. 13
0
app.config['MONGODB_SETTINGS'] = {'DB': environ['DB'], 'HOST': environ['HOST']}

# Configurations for storing password hashes
app.config['SECURITY_PASSWORD_HASH'] = environ['SECURITY_PASSWORD_HASH']
app.config['SECURITY_PASSWORD_SALT'] = environ['SECURITY_PASSWORD_SALT']

app.config['SECURITY_POST_LOGIN_VIEW'] = environ['SECURITY_POST_LOGIN_VIEW']

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.add_link(NotAuthenticatedMenuLink(name='Login', url='/login'))
admin.add_link(AuthenticatedMenuLink(name='Logout', url='/logout'))

db.init_app(app)
admin.init_app(app)

from api import models
from api import views
from api import administration

# Setup Flask-Security
user_datastore = MongoEngineUserDatastore(db, models.User, models.Role)
security = Security(app, user_datastore)
Esempio n. 14
0
            db.session.commit()
        response = {'message': str(orders[0]['user']) + '\'s order has been updated', 'priority': 'success', 'items': []}
        return json.dumps(response)

admin = Admin(app)


# Admin Views
class MyModelView(ModelView):
    def is_accessible(self):
        return True  # remove to lock down admin
        # return current_user.has_role('admin')  # uncomment to lock down admin


class MyFileView(FileAdmin):
    def is_accessible(self):
        return True  # remove to lock down admin
        # return current_user.has_role('admin')  # uncomment to lock down admin

admin.add_view(MyModelView(User, db.session, name='Users', category='Models'))
admin.add_view(MyModelView(Role, db.session, name='Roles', category='Models'))
admin.add_view(MyModelView(Item, db.session, name='Items', category='Models'))
admin.add_view(MyModelView(Order, db.session, name='Orders', category='Models'))
admin.add_view(MyModelView(Week, db.session, name='Weeks', category='Models'))
path = op.join(op.dirname(__file__), 'static')
admin.add_view(MyFileView(path, '/static/', name='Static Files'))
admin.add_link(MenuLink(name='Main Site', url='/'))

if __name__ == '__main__':
    manager.run()
Esempio n. 15
0
                              category='Category',
                              name='Categories',
                              endpoint='categoryview'))
admin.add_view(
    categorygroupview.CategoryGroupView(db.session,
                                        category='Category',
                                        name='Groups',
                                        endpoint='categorygroupview'))

admin.add_view(categoryview.CategoryMergeView(db.session))

admin.add_view(
    populationview.PopulationView(db.session,
                                  category='Population',
                                  name='Populations',
                                  endpoint='populationview'))
admin.add_view(
    populationgroupview.PopulationGroupView(db.session,
                                            category='Population',
                                            name='Groups',
                                            endpoint='populationgroupview'))

admin.add_view(reviewview.ReviewView(db.session, endpoint='reviewview'))

admin.add_view(maintenanceview.MaintenanceView(db.session))

# Add a link back to the main site
admin.add_link(MenuLink(name="Main Site", url='/'))

admin.add_view(newsview.NewsView(db.session, endpoint='newsview', name='News'))
Esempio n. 16
0
# coding=utf-8
from __future__ import unicode_literals, print_function
from flask.ext.admin import Admin
from flask.ext.admin.menu import MenuLink
from web_site.admin.views import IndexView
from flask.ext.admin.contrib.sqla import ModelView
from web_site import db
from web_site.user.models import Role, User


admin = Admin(index_view=IndexView(name=u'首页'))

admin.add_view(ModelView(Role, db.session, endpoint="model_role", category="User"))
admin.add_view(ModelView(User, db.session, endpoint="model_user", category="User"))


admin.add_link(MenuLink(u'返回前台', url='/'))
Esempio n. 17
0
from flask.ext.security import Security, SQLAlchemyUserDatastore
from flask_wtf.csrf import CsrfProtect
from config import FIRST_USER_PASS, FIRST_USER_NAME

# Initialize the app and database, import the config
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
CsrfProtect(app)
app.killswitch = 0

# setup db, create the db, setup security, and add first user
from app import models
userstore = SQLAlchemyUserDatastore(db, models.User, None)
sec = Security(app, userstore)
db.create_all()
try:
    userstore.create_user(email=FIRST_USER_NAME, password=FIRST_USER_PASS)
    db.session.commit()
except: db.session.rollback()

#this loads all views
from app.views import main, admin

#admin setup
_admin = Admin(app, 'NYX Admin', template_mode='bootstrap3',
              index_view=admin.ProtectedIndexView())
_admin.add_link(MenuLink(name='Back to Site', url='/'))
_admin.add_view(admin.UserModelView(models.User, db.session))
_admin.add_view(admin.BotModelView(models.Bot, db.session))
Esempio n. 18
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
Esempio n. 19
0
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/profile')
@login_required
def profile():
    return render_template('profile.html')
        
admin = Admin(app)

# Admin Views
class MyModelView(ModelView):
    def is_accessible(self):
        return True  # remove
        # return current_user.has_role('admin')  # uncomment to lock down admin

class MyFileView(FileAdmin):
    def is_accessible(self):
        return True  # remove
        # return current_user.has_role('admin')  # uncomment to lock down admin

admin.add_view(MyModelView(User, db.session))
admin.add_view(MyModelView(Role, db.session))
path = op.join(op.dirname(__file__), 'static')
admin.add_view(MyFileView(path, '/static/', name='Static Files'))
admin.add_link(MenuLink(name='Back Home', url='/'))

if __name__ == '__main__':
    manager.run()
Esempio n. 20
0
        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, 'Flask-Easy Admin', index_view=MyAdminIndexView())
admin.add_view(TasksAdminView(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="log_out"))

# --------------------------  END ADMIN PART ---------------------------------



# --------------------------- QUICK SEO PART ----------------------------
@app.errorhandler(404)
def page_not_found(e):
    return render_template('other/404.html'), 404


@app.errorhandler(403)
def page_forbiden(e):
    return render_template('other/403.html'), 403
Esempio n. 21
0
import datetime
from flask.ext.admin import Admin
from admin import MyView, AuthenticatedMenuLink, MyModel
from flask.ext.login import LoginManager, logout_user, login_user, current_user, login_required

app = Flask(__name__)
app.config.from_object('config')
login_manager = LoginManager()
login_manager.init_app(app)
db = SQLAlchemy(app)
admin = Admin(app)
admin.add_view(MyView(name='Index'))
login_manager.login_view = 'login'
from models import Post, User
admin.add_view(MyModel(Post, db.session))
admin.add_link(AuthenticatedMenuLink(name='Logout', endpoint='logout'))


@login_manager.user_loader
def load_user(user_id):
    """Given *user_id*, return the associated User object.

    :param unicode user_id: user_id (username) user to retrieve
    """
    return User.query.get(user_id)


def flash_errors(form):
    for field, errors in form.errors.items():
        for error in errors:
            flash(
Esempio n. 22
0
app.config['SECURITY_PASSWORD_SALT'] = 'SECURITY_PASSWORD_SALT'

# app.config['SECURITY_POST_LOGIN_VIEW'] = environ['SECURITY_POST_LOGIN_VIEW']
# app.config['SECURITY_POST_LOGIN_VIEW'] = environ['SECURITY_POST_LOGIN_VIEW']
app.config['SECURITY_POST_LOGIN_VIEW'] = '/admin/customer/'

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.add_link(NotAuthenticatedMenuLink(name='Login', url='/login'))
admin.add_link(AuthenticatedMenuLink(name='Logout', url='/logout'))

db.init_app(app)
admin.init_app(app)

from api import models
from api import views
from api import administration

# Setup Flask-Security
user_datastore = MongoEngineUserDatastore(db, models.User, models.Role)
security = Security(app, user_datastore)

# sanyam = models.User(email="*****@*****.**", password="******")
@app.before_first_request
Esempio n. 23
0
    Basic home view, just showing the README.md file
    """
    @expose("/")
    def index(self):
        dags = sorted(dagbag.dags.values(), key=lambda dag: dag.dag_id)
        return self.render('airflow/dags.html', dags=dags)

admin = Admin(
    app,
    name="Airflow",
    index_view=HomeView(name='DAGs'),
    template_mode='bootstrap3')

admin.add_link(
    base.MenuLink(
        category='Tools',
        name='Ad Hoc Query',
        url='/admin/airflow/query'))


class Airflow(BaseView):

    def is_visible(self):
        return False

    @expose('/')
    def index(self):
        return self.render('airflow/dags.html')

    @expose('/query')
    @login_required
Esempio n. 24
0
from config import SITE_ROOT
from .model import *


translations = {}

def _(string):
    if string in translations:
        return translations[string]
    ret = translations[string] = lazy_gettext(string)
    return ret



class MenuLink(BaseMenuLink):

    def __init__(self, name, url=None, endpoint=None, target='_self'):
        self.name = name
        self.url = url
        self.endpoint = endpoint
        self.target = target



admin = Admin(index_view=AdminIndex(name=_('Home'), url='/dad'))


admin.add_link(MenuLink(_('Visit Site'), url=SITE_ROOT, target='_blank'))
admin.add_link(MenuLink(_('Logout'), endpoint='security.logout'))
Esempio n. 25
0
from flask.ext.admin import Admin
from admin import MyView, AuthenticatedMenuLink, MyModel
from flask.ext.login import LoginManager, logout_user, login_user, current_user, login_required


app = Flask(__name__)
app.config.from_object('config')
login_manager = LoginManager()
login_manager.init_app(app)
db = SQLAlchemy(app)
admin = Admin(app)
admin.add_view(MyView(name='Index'))
login_manager.login_view = 'login'
from models import Post, User
admin.add_view(MyModel(Post, db.session))
admin.add_link(AuthenticatedMenuLink(name='Logout', endpoint='logout'))



@login_manager.user_loader
def load_user(user_id):
    """Given *user_id*, return the associated User object.

    :param unicode user_id: user_id (username) user to retrieve
    """
    return User.query.get(user_id)


def flash_errors(form):
    for field, errors in form.errors.items():
        for error in errors:
Esempio n. 26
0
from app.home.views import mod as homeModule
from app.users.views import mod as userModule
from app.pages.views import mod as pageModule
from app.tree.views import mod as treeModule

app.register_blueprint(homeModule)
app.register_blueprint(userModule)
app.register_blueprint(pageModule)  # register page
app.register_blueprint(treeModule)  # register tree

from app.diagnostic.views import admin_views
for view_class in admin_views:
    backend.add_view(view_class(db.session))
backend.add_link(
    MenuLink(name='New Campaign',
             category='Campaign',
             url='/admin/#/campaign?equipment_ids=0'))

# from diagnostic.api import api_blueprint
# app.register_blueprint(api_blueprint)

from app.admin.views import UserAdmin, RoleAdmin, FileView, ImageView, MenuView

backend.add_view(UserAdmin(db.session))
backend.add_view(RoleAdmin(db.session))

backend.add_view(FileView(db.session))
backend.add_view(ImageView(db.session))

backend.add_view(MenuView(name="Menu", category='CMS'))
Esempio n. 27
0
    request_token_url=None,
    access_token_method="POST",
    access_token_url="https://accounts.google.com/o/oauth2/token",
    authorize_url="https://accounts.google.com/o/oauth2/auth",
)

lm = LoginManager()
lm.init_app(app)
lm.login_view = "main.login"

mail = Mail(app)

from app import models

db.create_all()
db.session.commit()
from app.views import main, adminviews

admin = Admin(app, "KDR Points Admin", template_mode="bootstrap3", index_view=adminviews.ProtectedAdminIndex())
admin.add_link(MenuLink(name="Back to Site", url="/"))
admin.add_view(adminviews.EventModelView(db.session))
admin.add_view(adminviews.AwardModelView(db.session))
admin.add_view(adminviews.ServiceModelView(db.session))
admin.add_view(adminviews.PointsModelView(db.session))
admin.add_view(adminviews.SignUpSheetsView(db.session))
admin.add_view(adminviews.BrotherModelView(db.session))
admin.add_view(adminviews.PositionModelView(db.session))
admin.add_view(adminviews.FamilyModelView(db.session))
admin.add_view(adminviews.SemesterModelView(db.session))
app.register_blueprint(main.main)
Esempio n. 28
0
        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, 'Flask-Easy Admin', index_view=MyAdminIndexView())
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="log_out"))

# --------------------------  END ADMIN PART ---------------------------------


# --------------------------- QUICK SEO PART ----------------------------
@app.errorhandler(404)
def page_not_found(e):
    return render_template('other/404.html'), 404


@app.errorhandler(403)
def page_forbiden(e):
    return render_template('other/403.html'), 403
Esempio n. 29
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')

    #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'),
            template_mode='bootstrap3',
        )

        admin.add_view(views.Airflow(name='DAGs'))

        admin.add_view(views.SlaMissModelView(models.SlaMiss, Session, name="SLA Misses", category="Browse"))
        admin.add_view(
            views.TaskInstanceModelView(models.TaskInstance, Session, name="Task Instances", category="Browse")
        )

        admin.add_view(views.LogModelView(models.Log, Session, name="Logs", category="Browse"))
        admin.add_view(views.JobModelView(jobs.BaseJob, Session, name="Jobs", category="Browse"))

        admin.add_view(views.QueryView(name='Ad Hoc Query', category="Data Profiling"))
        admin.add_view(views.ChartModelView(models.Chart, Session, name="Charts", category="Data Profiling"))
        admin.add_view(views.KnowEventView(models.KnownEvent, Session, name="Known Events", category="Data Profiling"))

        admin.add_view(views.PoolModelView(models.Pool, Session, name="Pools", category="Admin"))
        admin.add_view(views.ConfigurationView(name='Configuration', category="Admin"))
        admin.add_view(views.UserModelView(models.User, Session, name="Users", category="Admin"))
        admin.add_view(views.ConnectionModelView(models.Connection, Session, name="Connections", category="Admin"))
        admin.add_view(views.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'))

        admin.add_view(views.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:
                print(bp)
                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
Esempio n. 30
0
        'content',
    )
    column_filters = ['published_date']
    form_widget_args = {'content': {'class': 'ckeditor'}}
    form_subdocuments = {
        'comments': {
            'form_subdocuments': {
                None: {
                    # Add <hr> at the end of the form
                    'form_rules': ('author', 'content', rules.HTML('<hr>')),
                    'form_widget_args': {
                        'content': {
                            'class': 'ckeditor'
                        }
                    }
                }
            }
        },
    }
    form_ajax_refs = {'author': {'fields': ('email', ), 'page_size': 10}}


admin.add_view(UserView(User, name='Usuários'))
admin.add_view(PostView(Post, name='Posts'))
admin.add_view(UploadView(Upload, name='Uploads'))
admin.add_view(
    AuthenticatedFileView(op.join(op.dirname(__file__), 'static/files'),
                          '/files/',
                          name='Arquivos'))
admin.add_link(MenuLink(name='Voltar', url='/'))
admin.add_link(MenuLink(name='Sair', endpoint='logout_view'))
Esempio n. 31
0
admin.add_view(categorygroupview.CategoryGroupView(
    db.session,
    category='Category',
    name='Groups',
    endpoint='categorygroupview'))

admin.add_view(categoryview.CategoryMergeView(
    db.session))

admin.add_view(populationview.PopulationView(
    db.session,
    category='Population',
    name='Populations',
    endpoint='populationview'))
admin.add_view(populationgroupview.PopulationGroupView(
    db.session,
    category='Population',
    name='Groups',
    endpoint='populationgroupview'))

admin.add_view(reviewview.ReviewView(
    db.session,
    endpoint='reviewview'))

admin.add_view(maintenanceview.MaintenanceView(db.session))

# Add a link back to the main site
admin.add_link(MenuLink(name="Main Site", url='/'))

admin.add_view(newsview.NewsView(db.session, endpoint='newsview', name='News'))
Esempio n. 32
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