Exemplo n.º 1
0
def create_app(config_name):
    dash = Flask(__name__)
    dash.config.from_object(config[config_name])
    config[config_name].init_app(dash)

    AdminLTE.init_app(dash)
    mail.init_app(dash)
    moment.init_app(dash)
    db.init_app(dash)
    login_manager.init_app(dash)
    Principal.init_app(dash)
    toolbar.init_app(dash)

    # special helper functions
    @dash.context_processor
    def my_utility_processor():
        from .models import Provider

        def all_providers():
            """ returns all providers """
            return Provider.query.all()

        return dict(all_providers=all_providers)

    # attach routes and custom error pages here

    # main application
    from dash.main import main as main_blueprint
    dash.register_blueprint(main_blueprint)

    # auth application
    from .auth import auth as auth_blueprint
    dash.register_blueprint(auth_blueprint, url_prefix='/auth')

    # user profile application
    from .profile import profile as profile_blueprint
    dash.register_blueprint(profile_blueprint, url_prefix='/profile')

    # server application
    from .server import server as server_blueprint
    dash.register_blueprint(server_blueprint, url_prefix='/server')

    # image application
    from .image import image as image_blueprint
    dash.register_blueprint(image_blueprint, url_prefix='/image')

    # security application
    from .security import security as security_blueprint
    dash.register_blueprint(security_blueprint, url_prefix='/security')

    # network application
    from .network import network as network_blueprint
    dash.register_blueprint(network_blueprint, url_prefix='/network')

    # admin application
    from .admin import admin as admin_blueprint
    dash.register_blueprint(admin_blueprint, url_prefix='/admin')

    return dash
Exemplo n.º 2
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(config.DevelopmentConfig)
    # adds jinja2 support for break and continue in loops
    app.jinja_env.add_extension('jinja2.ext.loopcontrols')
    with app.app_context():
        from apluslms_shepherd.auth.models import write_user_to_db, login_manager
        from apluslms_shepherd.views import main_bp
        from apluslms_shepherd.auth.views import auth_bp
        from apluslms_shepherd.courses.views import course_bp
        from apluslms_shepherd.build.views import build_log_bp
        from apluslms_shepherd.webhooks.views import webhooks_bp
        from apluslms_shepherd.groups.views import groups_bp
        from apluslms_shepherd.repos.views import repo_bp
        login_manager.init_app(app=app)
        db.init_app(app=app)
        migrate = Migrate(app, db, render_as_batch=True)
        lti_login_authenticated.connect(write_user_to_db)
        # Flask-Principal: ---  Setup ------------------------------------
        principals = Principal(app)
        principals.init_app(app)
        # -----------------------------------------------------------------
        app.register_blueprint(main_bp)
        app.register_blueprint(build_log_bp)
        app.register_blueprint(course_bp)
        app.register_blueprint(lti)
        app.register_blueprint(auth_bp)
        app.register_blueprint(webhooks_bp)
        app.register_blueprint(groups_bp)
        app.register_blueprint(repo_bp)

        # Add info to the Identity instance
        @identity_loaded.connect_via(app)
        def on_identity_loaded(sender, identity):
            # Set the identity user object
            identity.user = current_user

            # Add the UserNeed to the identity
            if hasattr(current_user, 'id'):
                identity.provides.add(UserNeed(current_user.id))

            # Update the identity with the role that the user provides
            if hasattr(current_user, 'roles'):
                for role in current_user.roles.split(','):
                    identity.provides.add(RoleNeed(role))

            app.logger.info(identity)

        # Handle HTTP 403 error
        @app.errorhandler(403)
        def access_forbidden(e):
            session['redirected_from'] = request.url
            flash('Access Forbidden')
            return redirect('/')

    return app
Exemplo n.º 3
0
def create_app(config=None):
    app = flask.Flask(__name__)

    app.config.from_object('config')

    if config is not None:
        app.config.update(**config)

    db.init_app(app)
    api.init_app(app)
    influx_db.init_app(app)
    menu.init_app(app)

    security.init_app(app, users)

    principal = Principal()
    principal.init_app(app)

    init_signals(app)
    configure_uploads(app, logos)
    app.register_blueprint(bp)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        if not isinstance(identity, AnonymousIdentity):
            identity.provides.add(UserNeed(identity.id))

            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))

    @principal.identity_loader
    def read_identity_from_flask_login():
        if current_user.is_authenticated:
            return Identity(current_user.id)
        return AnonymousIdentity()

    @app.after_request
    def set_cid_cookie(response):
        if 'cid' not in flask.request.cookies:
            cid = str(uuid.uuid4())
            expires = datetime.datetime.now() + datetime.timedelta(days=365*2)
            response.set_cookie('cid', cid, expires=expires)
        return response

    return app
Exemplo n.º 4
0
def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object("config")

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile("config.py", silent=True)
    else:
        # load the test config if passed in
        app.config.update(test_config)

    # Connect the db
    db.init_app(app)

    # Set up flask-login
    login_manager = LoginManager()
    login_manager.init_app(app)

    # Set up flask-principal for roles management
    principals = Principal()
    principals.init_app(app)

    # Set up csrf protection
    csrf = CSRFProtect()
    csrf.init_app(app)
    csrf.exempt(login_blueprint)

    app.register_blueprint(login_blueprint)
    app.register_blueprint(admin_blueprint, url_prefix="/admin")
    app.register_blueprint(token_management_blueprint, url_prefix="/user")
    app.register_blueprint(aggregation_unit_blueprint,
                           url_prefix="/spatial_aggregation")

    @app.after_request
    def set_xsrf_cookie(response):
        """
        Sets the csrf token used by csrf protect as a cookie to allow usage with
        react.
        """
        response.set_cookie("X-CSRF", generate_csrf())
        return response

    @app.errorhandler(CSRFError)
    def handle_csrf_error(e):
        """
        CSRF errors are interpreted as an access denied.
        """
        return "CSRF error", 401

    @app.errorhandler(InvalidUsage)
    def handle_invalid_usage(error):
        response = flask.jsonify(error.to_dict())
        response.status_code = error.status_code
        return response

    @app.before_request
    def before_request():
        """
        Make sessions expire after 20 minutes of inactivity.
        """
        flask.session.permanent = True
        app.permanent_session_lifetime = datetime.timedelta(minutes=20)
        flask.session.modified = True
        flask.g.user = flask_login.current_user

    @login_manager.user_loader
    def load_user(userid):
        """Helper for flask-login."""
        return User.query.filter(User.id == userid).first()

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        """Helper for flask-principal."""
        # Set the identity user object
        identity.user = current_user

        # Add the UserNeed to the identity
        if hasattr(current_user, "id"):
            identity.provides.add(UserNeed(current_user.id))

        try:
            if current_user.is_admin:
                identity.provides.add(RoleNeed("admin"))
        except AttributeError:
            pass  # Definitely not an admin

    @app.cli.command("get-fernet")
    def make_fernet_key():
        """
        Generate a new Fernet key for symmetric encryption of data at
        rest.
        """
        print(f'FERNET_KEY="{Fernet.generate_key().decode()}"')

    # Add flask <command> CLI commands
    app.cli.add_command(demodata)
    app.cli.add_command(init_db_command)
    app.cli.add_command(add_admin)
    return app
Exemplo n.º 5
0
def register_principal(app):
    principal = Principal()
    principal.init_app(app)
Exemplo n.º 6
0
def mkapp(with_factory=False):
    app = Flask(__name__)
    app.secret_key = 'notverysecret'
    app.debug = True

    if with_factory:
        p = Principal()
        p.init_app(app)
    else:
        p = Principal(app)

    identity_loaded.connect(_on_principal_init)

    @app.route('/')
    def index():
        with admin_permission.require():
            pass
        return Response('hello')

    @app.route('/a')
    @admin_permission.require()
    def a():
        return Response('hello')

    @app.route('/b')
    @anon_permission.require()
    def b():
        return Response('hello')

    @app.route('/c')
    def c():
        with anon_permission.require():
            raise ReraiseException

    @app.route('/d')
    @anon_permission.require()
    def d():
        raise ReraiseException

    @app.route('/e')
    def e():
        i = mkadmin()
        identity_changed.send(app, identity=i)
        with admin_permission.require():
            return Response('hello')

    @app.route('/f')
    def f():
        i = mkadmin()
        identity_changed.send(app, identity=i)
        with admin_or_editor.require():
            return Response('hello')

    @app.route('/g')
    @admin_permission.require()
    @editor_permission.require()
    def g():
        return Response('hello')

    @app.route('/h')
    def h():
        i = Identity('james')
        identity_changed.send(app, identity=i)
        with admin_permission.require():
            with editor_permission.require():
                pass

    @app.route('/j')
    def j():
        i = Identity('james')
        identity_changed.send(app, identity=i)
        with admin_permission.require(403):
            with editor_permission.require(403):
                pass

    @app.route('/k')
    @admin_permission.require(403)
    def k():
        return Response('hello')

    @app.route('/l')
    def l():
        s = []
        if not admin_or_editor:
            s.append("not admin")

        i = Identity('ali')
        identity_changed.send(app, identity=i)
        if admin_or_editor:
            s.append("now admin")
        return Response('\n'.join(s))

    @app.route("/m")
    def m():
        with admin_denied.require():
            pass

        return Response("OK")

    @app.route("/n")
    def n():
        i = mkadmin()
        identity_changed.send(app, identity=i)
        with admin_denied.require():
            pass

        return Response("OK")

    @app.route("/o")
    def o():
        admin_or_editor.test()
        return Response("OK")

    @app.route("/p")
    def p():
        admin_or_editor.test(404)
        return Response("OK")

    return app
Exemplo n.º 7
0
def create_app(test_config=None):
    app=Flask(__name__)
    try:
        app.config.from_pyfile('free_shark.cfg')
        app.config.from_pyfile('db_config.cfg')
        app.config.from_pyfile('mail_config.cfg')
    except:
        pass
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    app.config['WTF_CSRF_ENABLED'] = False
    if test_config is None:
    # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    d=load_config_from_envvar()
    app.config.from_mapping(d)
    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    debugFlag=app.config['DEBUG']

    db.init_app(app)
    
    app.register_blueprint(auth.bp)
    app.register_blueprint(resources.bp)
    app.register_blueprint(comController.bp)
    app.register_blueprint(admin.bp)


    app.add_template_global(set_var, 'set_var')
    app.add_template_global(get_var, 'get_var')

    app.jinja_env.globals['HEARTBEAT_FLAG']=not debugFlag

    from urllib.parse import urlencode
    from free_shark.utils import replace_dict
    app.jinja_env.filters['urlencode']=urlencode
    app.jinja_env.filters['replace_dict']=replace_dict
    app.jinja_env.filters['set_default']=set_default

    app.register_error_handler(403,frobidden_handler)

    principals = Principal(app)
    principals.init_app(app)

    login_manager=LoginManager()   
    login_manager.init_app(app)

    bootstrap=Bootstrap()
    bootstrap.init_app(app)
  
    csrf=CSRFProtect(app)
    csrf.init_app(app)

    
    from free_shark.utils import api_limiter,mail
    api_limiter.init_app(app)
    mail.init_app(app)

    @login_manager.user_loader
    def load_user(userid):
        try:
            id=int(userid)
            return user.User.get_user_by_id(id)
        except:
            return user.User.get_user_by_token(userid) 



    # a simple page that says hello
    
    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        identity.user=current_user
        if current_user is not None and not current_user.is_anonymous:
            identity.provides.add(UserNeed(current_user.id))
            for role in current_user.role:
                identity.provides.add(RoleNeed(role))
        else:
            identity.provides.add(RoleNeed("anonymous"))

    return app
Exemplo n.º 8
0
def create_app(test_config=None):
    app = Flask(__name__)

    app.config.from_mapping(get_config())

    if test_config is not None:
        # load the test config if passed in
        app.config.update(test_config)

    # Connect the db
    db.init_app(app)

    # Set up flask-login
    login_manager = LoginManager()
    login_manager.init_app(app)

    # Set up flask-principal for roles management
    principals = Principal()
    principals.init_app(app)

    # Set up csrf protection
    csrf = CSRFProtect()
    csrf.init_app(app)
    csrf.exempt(login_blueprint)

    app.register_blueprint(login_blueprint)
    app.register_blueprint(admin_blueprint, url_prefix="/admin")
    app.register_blueprint(token_management_blueprint, url_prefix="/user")
    app.register_blueprint(aggregation_unit_blueprint,
                           url_prefix="/spatial_aggregation")

    # Set the log level
    app.before_first_request(
        partial(app.logger.setLevel, app.config["LOG_LEVEL"]))

    if app.config["DEMO_MODE"]:  # Create demo data
        app.before_first_request(make_demodata)
    else:
        # Initialise the database
        app.before_first_request(partial(init_db,
                                         force=app.config["RESET_DB"]))
        # Create an admin user
        app.before_first_request(
            partial(
                add_admin,
                username=app.config["ADMIN_USER"],
                password=app.config["ADMIN_PASSWORD"],
            ))

    app.before_first_request(app.config["DB_IS_SET_UP"].wait
                             )  # Cause workers to wait for db to set up

    @app.after_request
    def set_xsrf_cookie(response):
        """
        Sets the csrf token used by csrf protect as a cookie to allow usage with
        react.
        """
        response.set_cookie("X-CSRF", generate_csrf())
        try:
            current_app.logger.debug(
                f"Logged in user was {flask.g.user.username}:{flask.g.user.id}"
            )
            current_app.logger.debug(flask.session)
        except AttributeError:
            current_app.logger.debug(f"User was not logged in.")
        return response

    @app.errorhandler(CSRFError)
    def handle_csrf_error(e):
        """
        CSRF errors are interpreted as an access denied.
        """
        return "CSRF error", 401

    @app.errorhandler(InvalidUsage)
    def handle_invalid_usage(error):
        response = flask.jsonify(error.to_dict())
        response.status_code = error.status_code
        return response

    @app.before_request
    def before_request():
        """
        Make sessions expire after 20 minutes of inactivity.
        """
        flask.session.permanent = True
        app.permanent_session_lifetime = datetime.timedelta(minutes=20)
        flask.session.modified = True
        flask.g.user = flask_login.current_user
        try:
            current_app.logger.debug(
                f"Logged in user is {flask.g.user.username}:{flask.g.user.id}")
            current_app.logger.debug(flask.session)
        except AttributeError:
            current_app.logger.debug(f"User is not logged in.")

    @login_manager.user_loader
    def load_user(userid):
        """Helper for flask-login."""
        return User.query.filter(User.id == userid).first()

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        """Helper for flask-principal."""
        # Set the identity user object
        identity.user = current_user

        # Add the UserNeed to the identity
        if hasattr(current_user, "id"):
            identity.provides.add(UserNeed(current_user.id))

        try:
            if current_user.is_admin:
                identity.provides.add(RoleNeed("admin"))
        except AttributeError:
            pass  # Definitely not an admin

    @app.cli.command("get-fernet")
    def make_flowauth_fernet_key():
        """
        Generate a new Fernet key for symmetric encryption of data at
        rest.
        """
        print(f'FLOWAUTH_FERNET_KEY="{Fernet.generate_key().decode()}"')

    # Add flask <command> CLI commands
    app.cli.add_command(demodata)
    app.cli.add_command(init_db_command)
    app.cli.add_command(add_admin_command)
    return app
Exemplo n.º 9
0
db.init_app(app)
with app.app_context():
    db.create_all()

login_manager = LoginManager()
login_manager.init_app(app)


@login_manager.user_loader
def user_loader(username):
    return user.query.filter_by(username=username).first()


principal = Principal()
principal.init_app(app)

administrator_permission = Permission(RoleNeed('administrator'))
team_member_permission = Permission(RoleNeed('team member'))
project_manager_permission = Permission(RoleNeed('project manager'))
client_permission = Permission(RoleNeed('client'))


@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
    identity.user = current_user

    if hasattr(current_user, 'rolename'):
        identity.provides.add(RoleNeed(current_user.rolename))

Exemplo n.º 10
0
def mkapp(with_factory=False):
    app = Flask(__name__)
    app.secret_key = 'notverysecret'
    app.debug = True

    if with_factory:
        p = Principal()
        p.init_app(app)
    else:
        p = Principal(app)

    identity_loaded.connect(_on_principal_init)

    @app.route('/')
    def index():
        with admin_permission.require():
            pass
        return Response('hello')

    @app.route('/a')
    @admin_permission.require()
    def a():
        return Response('hello')

    @app.route('/b')
    @anon_permission.require()
    def b():
        return Response('hello')

    @app.route('/c')
    def c():
        with anon_permission.require():
            raise ReraiseException

    @app.route('/d')
    @anon_permission.require()
    def d():
        raise ReraiseException

    @app.route('/e')
    def e():
        i = mkadmin()
        identity_changed.send(app, identity=i)
        with admin_permission.require():
            return Response('hello')

    @app.route('/f')
    def f():
        i = mkadmin()
        identity_changed.send(app, identity=i)
        with admin_or_editor.require():
            return Response('hello')

    @app.route('/g')
    @admin_permission.require()
    @editor_permission.require()
    def g():
        return Response('hello')

    @app.route('/h')
    def h():
        i = Identity('james')
        identity_changed.send(app, identity=i)
        with admin_permission.require():
            with editor_permission.require():
                pass

    @app.route('/j')
    def j():
        i = Identity('james')
        identity_changed.send(app, identity=i)
        with admin_permission.require(403):
            with editor_permission.require(403):
                pass

    @app.route('/k')
    @admin_permission.require(403)
    def k():
        return Response('hello')

    @app.route('/l')
    def l():
        s = []
        if not admin_or_editor:
            s.append("not admin")

        i = Identity('ali')
        identity_changed.send(app, identity=i)
        if admin_or_editor:
            s.append("now admin")
        return Response('\n'.join(s))

    @app.route("/m")
    def m():
        with admin_denied.require():
            pass

        return Response("OK")

    @app.route("/n")
    def n():
        i = mkadmin()
        identity_changed.send(app, identity=i)
        with admin_denied.require():
            pass

        return Response("OK")

    @app.route("/o")
    def o():
        admin_or_editor.test()
        return Response("OK")

    @app.route("/p")
    def p():
        admin_or_editor.test(404)
        return Response("OK")

    return app
Exemplo n.º 11
0
def mkapp(with_factory=False):
    app = Flask(__name__)
    app.secret_key = 'notverysecret'
    app.debug = True

    if with_factory:
        p = Principal()
        p.init_app(app)
    else:
        p = Principal(app)

    identity_loaded.connect(_on_principal_init)

    @app.route('/')
    def index():
        with admin_permission.require():
            pass
        return Response('hello')

    @app.route('/a')
    @admin_permission.require()
    def a():
        return Response('hello')

    @app.route('/b')
    @anon_permission.require()
    def b():
        return Response('hello')

    @app.route('/c')
    def c():
        with anon_permission.require():
            raise ReraiseException

    @app.route('/d')
    @anon_permission.require()
    def d():
        raise ReraiseException

    @app.route('/e')
    def e():
        i = mkadmin()
        identity_changed.send(app, identity=i)
        with admin_permission.require():
            return Response('hello')

    @app.route('/f')
    def f():
        i = mkadmin()
        identity_changed.send(app, identity=i)
        with admin_or_editor.require():
            return Response('hello')

    @app.route('/and_base_fail')
    def and_base_fail():
        i = mkadmin()
        admin_and_editor_rp = (admin_role_permission & editor_role_permission)
        identity_changed.send(app, identity=i)
        with admin_and_editor_rp.require():
            return Response('fail')

    @app.route('/and_base_success')
    def and_base_success():
        i = Identity('admin_editor')
        identity_changed.send(app, identity=i)
        # using both formerly default, calling parent __and__
        admin_and_editor_rp = (admin_permission & editor_permission)
        with admin_and_editor_rp.require():
            return Response('good')

    @app.route('/and_bunch')
    def and_bunch():
        result = []

        bunch = AndPermission(
            admin_role_permission,
            editor_role_permission,
            manager_role_permission,
        )

        identity_changed.send(app, identity=Identity('admin'))
        if bunch.can():
            result.append('bad')

        identity_changed.send(app, identity=Identity('manager'))
        if bunch.can():
            result.append('bad')

        identity_changed.send(app, identity=Identity('reviewer'))
        if bunch.can():
            result.append('bad')

        identity_changed.send(app, identity=Identity('admin_editor_manager'))
        if bunch.can():
            result.append('good')

        return ''.join(result)

    @app.route('/and_mixed1')
    def and_mixed1():
        admin_and_editor_mixed = (admin_role_permission & editor_permission)
        i = Identity('editor')
        identity_changed.send(app, identity=i)
        with admin_and_editor_mixed.require():
            return Response('fail')

    @app.route('/and_mixed2')  # reversed type of the above.
    def and_mixed2():
        admin_and_editor_mixed = (admin_permission & editor_role_permission)
        i = Identity('admin_editor')
        identity_changed.send(app, identity=i)
        with admin_and_editor_mixed.require():
            return Response('good')

    @app.route('/or_base')
    def or_base():
        i = mkadmin()
        admin_or_editor_rp = (admin_role_permission | editor_role_permission)
        identity_changed.send(app, identity=i)
        with admin_or_editor_rp.require():
            return Response('hello')

    @app.route('/or_bunch')
    def or_bunch():
        result = []

        bunch = OrPermission(
            admin_role_permission,
            editor_role_permission,
            manager_role_permission,
            reviewer_role_permission,
        )

        identity_changed.send(app, identity=Identity('admin'))
        if bunch.can():
            result.append('good')

        identity_changed.send(app, identity=Identity('manager'))
        if bunch.can():
            result.append('good')

        identity_changed.send(app, identity=Identity('reviewer'))
        if bunch.can():
            result.append('good')

        return ''.join(result)

    @app.route('/or_mixed1')
    def or_mixed1():
        result = []
        admin_or_editor_mixed = (admin_role_permission | editor_permission)

        i = Identity('admin')
        identity_changed.send(app, identity=i)
        with admin_or_editor_mixed.require():
            result.append('good')

        i = Identity('editor')
        identity_changed.send(app, identity=i)
        with admin_or_editor_mixed.require():
            result.append('good')

        return Response(''.join(result))

    @app.route('/or_mixed2')  # reversed type of the above.
    def or_mixed2():
        result = []
        admin_or_editor_mixed = (admin_permission | editor_role_permission)

        i = Identity('admin')
        identity_changed.send(app, identity=i)
        with admin_or_editor_mixed.require():
            result.append('good')

        i = Identity('editor')
        identity_changed.send(app, identity=i)
        with admin_or_editor_mixed.require():
            result.append('good')

        return Response(''.join(result))

    @app.route('/not_base')
    def not_base():
        result = []
        not_admin_perm = ~admin_role_permission

        identity_changed.send(app, identity=Identity('admin'))
        if not_admin_perm.can():
            result.append('admin')

        identity_changed.send(app, identity=Identity('editor'))
        if not_admin_perm.can():
            result.append('editor')

        identity_changed.send(app, identity=Identity('admin_manager'))
        if not_admin_perm.can():
            result.append('admin_manager')

        return Response(''.join(result))

    @app.route('/mixed_ops_fail')
    def mixed_ops_fail():
        mixed_perms = (admin_permission | manager_permission |
                       (reviewer_role_permission & editor_role_permission))

        i = Identity('editor')
        identity_changed.send(app, identity=i)
        with mixed_perms.require():
            return Response('fail')

    @app.route('/mixed_ops1')
    def mixed_ops1():
        result = []
        mixed_perms = (admin_permission | manager_permission |
                       (reviewer_role_permission & editor_role_permission))

        i = Identity('reviewer_editor')
        identity_changed.send(app, identity=i)
        with mixed_perms.require():
            result.append('good')

        i = Identity('manager')
        identity_changed.send(app, identity=i)
        with mixed_perms.require():
            result.append('good')

        i = Identity('admin')
        identity_changed.send(app, identity=i)
        with mixed_perms.require():
            result.append('good')

        return Response(''.join(result))

    @app.route('/mixed_ops2')
    def mixed_ops2():
        result = []
        mixed_perms = ((admin_permission & editor_permission) |
                       (manager_role_permission & editor_role_permission))

        i = Identity('manager_editor')
        identity_changed.send(app, identity=i)
        if mixed_perms.can():
            result.append('good')

        i = Identity('manager')
        identity_changed.send(app, identity=i)
        if mixed_perms.can():
            result.append('bad')

        i = Identity('editor')
        identity_changed.send(app, identity=i)
        if mixed_perms.can():
            result.append('bad')

        i = Identity('admin_editor')
        identity_changed.send(app, identity=i)
        if mixed_perms.can():
            result.append('good')

        i = Identity('admin')
        identity_changed.send(app, identity=i)
        if mixed_perms.can():
            result.append('bad')

        return Response(''.join(result))

    @app.route('/mixed_ops3')
    def mixed_ops3():
        result = []
        mixed_perms = (((admin_permission & editor_permission) |
                        (manager_role_permission & editor_role_permission))
                       & ~(manager_role_permission & admin_permission)
                       & ~reviewer_role_permission)

        i = Identity('manager_editor')
        identity_changed.send(app, identity=i)
        if mixed_perms.can():
            result.append('good')

        i = Identity('admin_editor')
        identity_changed.send(app, identity=i)
        if mixed_perms.can():
            result.append('good')

        i = Identity('admin_manager')
        identity_changed.send(app, identity=i)
        if mixed_perms.can():
            result.append('bad')

        i = Identity('manager_editor_admin')
        identity_changed.send(app, identity=i)
        if mixed_perms.can():
            result.append('bad')

        i = Identity('reviewer')
        identity_changed.send(app, identity=i)
        if mixed_perms.can():
            result.append('bad')

        return Response(''.join(result))

    @app.route('/g')
    @admin_permission.require()
    @editor_permission.require()
    def g():
        return Response('hello')

    @app.route('/h')
    def h():
        i = Identity('james')
        identity_changed.send(app, identity=i)
        with admin_permission.require():
            with editor_permission.require():
                pass

    @app.route('/j')
    def j():
        i = Identity('james')
        identity_changed.send(app, identity=i)
        with admin_permission.require(403):
            with editor_permission.require(403):
                pass

    @app.route('/k')
    @admin_permission.require(403)
    def k():
        return Response('hello')

    @app.route('/l')
    def l():
        s = []
        if not admin_or_editor:
            s.append("not admin_or_editor")
        if not (admin_permission or editor_permission):
            s.append("not (admin or editor)")

        i = Identity('ali')
        identity_changed.send(app, identity=i)
        if admin_or_editor:
            s.append("now admin_or_editor")
        if admin_permission or editor_permission:
            s.append("now admin or editor")
        return Response('\n'.join(s))

    @app.route("/m")
    def m():
        with admin_denied.require():
            pass

        return Response("OK")

    @app.route("/n")
    def n():
        i = mkadmin()
        identity_changed.send(app, identity=i)
        with admin_denied.require():
            pass

        return Response("OK")

    @app.route("/o")
    def o():
        admin_or_editor.test()
        return Response("OK")

    @app.route("/o2")
    def o2():
        (admin_permission | editor_permission).test()
        return Response("OK")

    @app.route("/o3")
    def o3():
        i = mkadmin()
        identity_changed.send(app, identity=i)
        (admin_permission | editor_permission).test()
        return Response("OK")

    @app.route("/p")
    def p():
        admin_or_editor.test(404)
        return Response("OK")

    return app
Exemplo n.º 12
0
def register_principal(app):
    principal = Principal()
    principal.init_app(app)
Exemplo n.º 13
0
class Auth(object):
    """Auth extension."""
    _extension_name = 'carafe.auth'

    def __init__(self, app=None, provider=None):
        self.principal = Principal(use_sessions=False)
        self.require = PermissionFactory()

        self.app = app
        if self.app:  # pragma: no cover
            self.init_app(app, provider)

    def init_app(self, app, provider=None):
        """Initialize app."""
        app.config.setdefault('CARAFE_AUTH_ENABLED', True)
        app.config.setdefault('CARAFE_AUTH_SESSION_ID_KEY', 'user_id')
        app.config.setdefault('CARAFE_AUTH_IDENTITY_ID_KEY', 'id')
        app.config.setdefault('CARAFE_AUTH_IDENTITY_ROLES_KEY', 'roles')

        if not app.config['CARAFE_AUTH_ENABLED']:  # pragma: no cover
            return

        if not hasattr(app, 'extensions'):  # pragma: no cover
            app.extensions = {}

        app.extensions[self._extension_name] = {'provider': provider}

        # NOTE: Instead of having principal use it's session loader, we'll use
        # ours.
        self.principal.init_app(app)
        self.principal.identity_loader(self.session_identity_loader)
        identity_loaded.connect_via(app)(self.on_identity_loaded)

    @property
    def session_id_key(self):
        """Property access to config's CARAFE_AUTH_SESSION_ID_KEY."""
        return current_app.config['CARAFE_AUTH_SESSION_ID_KEY']

    @property
    def identity_id_key(self):
        """Property access to config's CARAFE_AUTH_IDENTITY_ID_KEY."""
        return current_app.config['CARAFE_AUTH_IDENTITY_ID_KEY']

    @property
    def identity_roles_key(self):
        """Property access to config's CARAFE_AUTH_IDENTITY_ROLES_KEY."""
        return current_app.config['CARAFE_AUTH_IDENTITY_ROLES_KEY']

    @property
    def user_id(self):
        """Property access to logged in user id."""
        return session.get(self.session_id_key)

    @property
    def provider(self):
        """Property access to auth provider instance."""
        return current_app.extensions[self._extension_name]['provider']

    def session_identity_loader(self):
        """Fetch user id from session using config's auth id key"""
        if self.session_id_key in session:
            identity = Identity(session[self.session_id_key])
        else:
            identity = None

        return identity

    def on_identity_loaded(self, app, identity):  # pylint: disable=unused-argument
        """Called if session_identity_loader() returns an identity (i.e. not
        None).
        """
        # Whatever is returned is used for our identity. Potentially, provider
        # may return a different user than original identity (e.g. app provides
        # way for admin users to access site using a different user account)

        if self.provider:
            ident = self.provider.identify(identity)
        else:
            ident = {self.identity_id_key: None}

        if self.user_id and not ident:
            # session has an user_id but the ident return is empty
            # user possibly deleted or inactivated in another process
            self.logout()

        # provide auth (whether user is not anonymous)
        if ident.get(self.identity_id_key):
            identity.provides.add(login_need)

        # provide roles
        for role in ident.get(self.identity_roles_key, []):
            identity.provides.add(RoleNeed(role))

    def send_identity_changed(self, user_id):
        """Send identity changed event."""
        if user_id is None:
            identity = AnonymousIdentity()
        else:
            identity = Identity(user_id)

        identity_changed.send(current_app._get_current_object(),
                              identity=identity)

    def login(self, user_id, propagate=True):
        """Call after user has been authenticated for login."""
        if session.get(self.session_id_key) != user_id:
            session[self.session_id_key] = user_id
            if propagate:
                self.send_identity_changed(user_id)

    def logout(self, propagate=True):
        """Call to log user out."""
        if session.get(self.session_id_key):
            del session[self.session_id_key]
            if propagate:
                self.send_identity_changed(None)
Exemplo n.º 14
0
def create_app(config=None):
    """ Create app """

    app = Flask(__name__)

    app.config.from_object('config')

    if config is not None:
        app.config.update(**config)

    db.init_app(app)
    api.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    menu.init_app(app)

    security.init_app(app, users)

    principal = Principal()
    principal.init_app(app)

    configure_uploads(app, (logos, ))
    app.register_blueprint(bp)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        """Load needs onto the identity"""
        if not isinstance(identity, AnonymousIdentity):
            identity.provides.add(UserNeed(identity.id))

            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))

    @principal.identity_loader
    def read_identity_from_flask_login():
        """Convert flask login to identity"""
        if hasattr(current_user, 'id'):
            return Identity(current_user.id)
        return AnonymousIdentity()

    @app.after_request
    def security_measures(response):
        response.headers["X-Content-Type-Options"] = "nosniff"
        response.headers["X-Frame-Options"] = "DENY"
        response.headers["X-XSS-Protection"] = "1"
        if 'Cache-Control' not in response.headers:
            response.headers[
                "Cache-Control"] = "no-cache, no-store, must-revalidate"
        response.headers["Pragma"] = "no-cache"
        return response

    @app.template_filter()
    def local_datetime(value, format="%I:%M %p"):
        tz = tzlocal()
        utc = pytz.timezone('UTC')
        value = utc.localize(value, is_dst=None).astimezone(pytz.utc)
        local_dt = value.astimezone(tz)
        return local_dt.strftime(format)

    @app.context_processor
    def context_processor():
        """Context processors for use in templates"""
        return dict(constants=constants, six=six)

    return app
Exemplo n.º 15
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)

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

    login_manager.session_protection = 'strong'
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    principal = Principal()
    principal.init_app(app)

    from app.models import User, Sentence, Quiz, Answer

    # Flask-Blogging database config
    with app.app_context():
        storage = SQLAStorage(db=db)
        db.create_all()
        blog_engine = BloggingEngine()
        blog_engine.init_app(app, storage)

    misaka = Misaka(app=None,
                    renderer=None,
                    strikethrough=True,
                    underline=True,
                    tables=True,
                    wrap=True)
    misaka.init_app(app)

    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

    # TODO: Move these auth handlers out of __init__.py
    @login_manager.user_loader
    # @blog_engine.user_loader
    def load_user(user_id):
        print "ID: ", user_id
        return User.query.get(int(user_id))

    @login_manager.unauthorized_handler
    def handle_unauthorized():
        if session.get('_id'):
            return redirect(url_for('auth.login'))
        else:
            login_user(User().save())
            return redirect(request.url)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        identity.user = current_user

        if hasattr(current_user, "id"):
            identity.provides.add(UserNeed(current_user.id))

        # Shortcut to the give admins "blogger" role.
        if hasattr(current_user, "is_admin"):
            if current_user.is_admin:
                identity.provides.add(RoleNeed("blogger"))

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    # Initialise flask-admin
    admin = Admin(app, template_mode='bootstrap3', index_view=AdminIndexView())
    Post = storage.post_model
    # Add administrative views here
    admin.add_view(ModelView(User, db.session))
    admin.add_view(ModelView(Post, db.session))

    return app
Exemplo n.º 16
0
def create_app(test_config=None):
    from flowauth.config import get_config
    from flowauth.models import db
    from flowauth.cli import (
        init_db_command,
        add_admin_command,
        make_flowauth_fernet_key,
        demo_data,
    )
    from .admin import blueprint as admin_blueprint
    from .users import blueprint as users_blueprint
    from .groups import blueprint as groups_blueprint
    from .servers import blueprint as servers_blueprint
    from .token_management import blueprint as token_management_blueprint
    from .login import blueprint as login_blueprint
    from .user_settings import blueprint as user_settings_blueprint
    from .version import blueprint as version_blueprint

    app = Flask(__name__)

    app.config.from_mapping(get_config())

    # Connect the logger
    app.before_first_request(connect_logger)

    if test_config is not None:
        # load the test config if passed in
        app.config.update(test_config)

    # Connect the db

    db.init_app(app)

    # Set up flask-login
    login_manager = LoginManager()
    login_manager.init_app(app)

    # Set up flask-principal for roles management
    principals = Principal()
    principals.init_app(app)

    # Set up csrf protection
    csrf = CSRFProtect()
    csrf.init_app(app)
    csrf.exempt(login_blueprint)
    csrf.exempt(version_blueprint)

    app.register_blueprint(login_blueprint)
    app.register_blueprint(admin_blueprint, url_prefix="/admin")
    app.register_blueprint(groups_blueprint, url_prefix="/admin")
    app.register_blueprint(servers_blueprint, url_prefix="/admin")
    app.register_blueprint(users_blueprint, url_prefix="/admin")
    app.register_blueprint(token_management_blueprint, url_prefix="/tokens")
    app.register_blueprint(user_settings_blueprint, url_prefix="/user")

    app.register_blueprint(version_blueprint)

    if app.config["DEMO_MODE"]:  # Create demo data
        from flowauth.models import make_demodata

        app.before_first_request(make_demodata)
    else:
        # Initialise the database
        from flowauth.models import init_db
        from flowauth.models import add_admin

        app.before_first_request(lock(partial(init_db, force=app.config["RESET_DB"])))
        # Create an admin user

        app.before_first_request(
            lock(
                partial(
                    add_admin,
                    username=app.config["ADMIN_USER"],
                    password=app.config["ADMIN_PASSWORD"],
                )
            )
        )

    app.before_first_request(
        app.config["DB_IS_SET_UP"].wait
    )  # Cause workers to wait for db to set up

    app.after_request(set_xsrf_cookie)
    app.errorhandler(CSRFError)(handle_csrf_error)
    app.errorhandler(InvalidUsage)(handle_invalid_usage)
    app.before_request(before_request)
    login_manager.user_loader(load_user)
    identity_loaded.connect_via(app)(on_identity_loaded)
    # Add flask <command> CLI commands
    app.cli.add_command(demo_data)
    app.cli.add_command(init_db_command)
    app.cli.add_command(add_admin_command)
    app.cli.add_command(make_flowauth_fernet_key)
    return app