コード例 #1
0
def user_logged_in_succesfull(app, user):
    user_agent = request.headers.get('User-Agent')
    if user_agent.startswith('faraday-client/'):
        HOME_URL = "https://portal.faradaysec.com/api/v1/license_check"
        params = {
            'version': faraday.__version__,
            'key': 'white',
            'client': user_agent
        }
        try:
            logger.debug('Send Faraday-Client license_check')
            res = requests.get(HOME_URL, params=params, timeout=1, verify=True)
            logger.debug("Faraday-Client license_check response: %s", res.text)
        except Exception as e:
            logger.warning("Error sending client license_check [%s]", e)
    # cleanup old sessions
    logger.debug("Cleanup sessions")
    KVSessionExtension(app=app).cleanup_sessions(app)

    user_ip = request.headers.get('X-Forwarded-For', request.remote_addr)
    user_login_at = datetime.datetime.utcnow()
    audit_logger.info(
        f"User [{user.username}] logged in from IP [{user_ip}] at [{user_login_at}]"
    )
    logger.info(
        f"User [{user.username}] logged in from IP [{user_ip}] at [{user_login_at}]"
    )
コード例 #2
0
def create_app(config_name):
    """

    the following  method implement  the application
    factory design pattern !
    it's responsible for creating all the app with 2
     configurations mode test ,develpement

    """

    if config_name == "test":
        app = Flask(__name__)
        app.config.from_object(app_config[config_name])

    else:

        #for template folder when runned as a package
        if getattr(sys, 'frozen', False):
            template_folder = os.path.join(sys._MEIPASS, 'templates')
            static_folder = os.path.join(sys._MEIPASS, 'static')
            app = Flask(__name__,
                        template_folder=template_folder,
                        static_folder=static_folder)
        else:
            app = Flask(__name__)
        app.config.from_object(app_config['development'])
    app.register_blueprint(home)
    """
    will use a kv sesssion to store session data in client side

    """
    store = FilesystemStore(SESSION_FOLDER)
    KVSessionExtension(store, app)

    return app
コード例 #3
0
def expire_session(app, user):
    logger.debug("Cleanup sessions")
    session.destroy()
    KVSessionExtension(app=app).cleanup_sessions(app)

    user_ip = request.headers.get('X-Forwarded-For', request.remote_addr)
    user_logout_at = datetime.datetime.now()
    audit_logger.info(f"User [{user.username}] logged out from IP [{user_ip}] at [{user_logout_at}]")
コード例 #4
0
 def __init__(self, app=None):
     """Extension initialization."""
     if app:
         self.init_app(app)
         store = RedisStore(
             redis.StrictRedis(host=app.config.get(
                 'ACCESS_SESSION_REDIS_HOST', 'localhost')))
         KVSessionExtension(store, app)
コード例 #5
0
def create_app(config_name):

    application = Flask(__name__,
                        static_folder='static/',
                        static_url_path=configs[config_name].ASSET_PATH)

    init_app(application,
             configs[config_name],
             bootstrap=bootstrap,
             data_api_client=data_api_client,
             login_manager=login_manager)

    if application.config['REDIS_SESSIONS']:
        vcap_services = parse_vcap_services()
        redis_opts = {
            'ssl': application.config['REDIS_SSL'],
            'ssl_ca_certs': application.config['REDIS_SSL_CA_CERTS'],
            'ssl_cert_reqs': application.config['REDIS_SSL_HOST_REQ']
        }
        if vcap_services and 'redis' in vcap_services:
            redis_opts['host'] = vcap_services['redis'][0]['credentials'][
                'hostname']
            redis_opts['port'] = vcap_services['redis'][0]['credentials'][
                'port']
            redis_opts['password'] = vcap_services['redis'][0]['credentials'][
                'password']
        else:
            redis_opts['host'] = application.config['REDIS_SERVER_HOST']
            redis_opts['port'] = application.config['REDIS_SERVER_PORT']
            redis_opts['password'] = application.config[
                'REDIS_SERVER_PASSWORD']

        session_store = RedisStore(redis.StrictRedis(**redis_opts))
        KVSessionExtension(session_store, application)

    application.permanent_session_lifetime = timedelta(hours=12)
    from .main import main as main_blueprint
    from .status import status as status_blueprint

    url_prefix = application.config['URL_PREFIX']
    application.register_blueprint(status_blueprint, url_prefix=url_prefix)
    application.register_blueprint(main_blueprint, url_prefix=url_prefix)
    login_manager.login_view = 'main.render_login'
    main_blueprint.config = application.config.copy()

    init_frontend_app(application, data_api_client, login_manager)

    application.add_template_filter(parse_document_upload_time)

    @application.context_processor
    def extra_template_variables():
        return {
            'generic_contact_email':
            application.config['GENERIC_CONTACT_EMAIL'],
        }

    return application
コード例 #6
0
ファイル: __init__.py プロジェクト: nycrecords/timeclock
def create_app(config_name):  # App Factory
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    if os.environ.get("DATABASE_URL") is None:
        app.config["SQLALCHEMY_DATABASE_URI"] = app.config.get(
            "SQLALCHEMY_DATABASE_URI")
    else:
        app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL")

    config[config_name].init_app(app)
    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    migrate.init_app(app, db)
    db.init_app(app)
    with app.app_context():
        # load_db(db)
        store = SQLAlchemyStore(db.engine, db.metadata, "sessions")
        kvsession = KVSessionExtension(store, app)
        logfile_name = "Timeclock" + time.strftime("%Y%m%d-%H%M%S") + ".log"
        handler = RotatingFileHandler(logfile_name,
                                      maxBytes=10000,
                                      backupCount=1)
        handler.setFormatter(
            Formatter("%(asctime)s %(levelname)s: %(message)s "
                      "[in %(pathname)s:%(lineno)d]"))
        handler.setLevel(logging.INFO)
        app.logger.addHandler(handler)
    login_manager.init_app(app)

    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint

    app.register_blueprint(auth_blueprint, url_prefix="/auth")

    from .health_screen import health_screen_bp as health_screen_blueprint

    app.register_blueprint(health_screen_blueprint, url_prefix="/healthscreen")

    app.permanent_session_lifetime = timedelta(minutes=15)

    @app.before_request
    def func():
        session.modified = True

    return app
コード例 #7
0
ファイル: app.py プロジェクト: XZVB12/faraday-pentest
def user_logged_in_succesfull(app, user):
    user_agent = request.headers.get('User-Agent')
    if user_agent.startswith('faraday-client/'):
        HOME_URL = "https://portal.faradaysec.com/api/v1/license_check"
        params = {'version': faraday.__version__, 'key': 'white', 'client': user_agent}
        try:
            logger.debug('Send Faraday-Client license_check')
            res = requests.get(HOME_URL, params=params, timeout=1, verify=True)
            logger.debug("Faraday-Client license_check response: %s", res.text)
        except Exception as e:
            logger.warning("Error sending client license_check [%s]", e)
    # cleanup old sessions
    logger.debug("Cleanup sessions")
    KVSessionExtension(app=app).cleanup_sessions(app)
コード例 #8
0
def register_extensions(app):
    """Register Flask extensions."""
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    csrf_protect.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    mail.init_app(app)
    migrate.init_app(app, db)
    webpack.init_app(app)
    KVSessionExtension(store, app)
    ws.init_app(app)
    return None
コード例 #9
0
def test_delayed_construction(vapp, store):
    ext = KVSessionExtension()

    with pytest.raises(ValueError):
        ext.init_app(vapp)

    ext.init_app(vapp, store)

    assert vapp.kvsession_store is store
コード例 #10
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)

    KVSessionExtension(st, app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app
コード例 #11
0
def app_with_session_interface_factory(store):
    app = Flask(__name__)

    app.config[
        "SESSION_INTERFACE_FACTORY"] = CustomSessionInterfaceWithPermanentAnonymousSession
    app.config["TESTING"] = True
    app.config["SECRET_KEY"] = "devkey"
    app.kvsession = KVSessionExtension(store, app)

    @app.route("/store-in-session/<key>/<value>/")
    def store(key, value):
        session[key] = value
        return "stored %r at %r" % (value, key)

    yield app
コード例 #12
0
    def init_config(self, app):
        """Initialize configuration.

        :param app: The Flask application.
        """
        try:
            pkg_resources.get_distribution('celery')
            app.config.setdefault("ACCOUNTS_USE_CELERY",
                                  not (app.debug or app.testing))
        except pkg_resources.DistributionNotFound:  # pragma: no cover
            app.config.setdefault("ACCOUNTS_USE_CELERY", False)

        # Register Invenio legacy password hashing
        register_crypt_handler(InvenioAesEncryptedEmail)

        # Change Flask defaults
        app.config.setdefault('SESSION_COOKIE_SECURE', not app.debug)

        # Change Flask-Security defaults
        app.config.setdefault('SECURITY_PASSWORD_SALT',
                              app.config['SECRET_KEY'])

        # Set JWT secret key
        app.config.setdefault(
            'ACCOUNTS_JWT_SECRET_KEY',
            app.config.get('ACCOUNTS_JWT_SECRET_KEY',
                           app.config.get('SECRET_KEY')))

        config_apps = ['ACCOUNTS', 'SECURITY_']
        for k in dir(config):
            if any([k.startswith(prefix) for prefix in config_apps]):
                app.config.setdefault(k, getattr(config, k))

        # Set Session KV store
        if app.config.get('ACCOUNTS_SESSION_REDIS_URL'):
            import redis
            from simplekv.memory.redisstore import RedisStore

            session_kvstore = RedisStore(
                redis.StrictRedis.from_url(
                    app.config['ACCOUNTS_SESSION_REDIS_URL']))
        else:
            from simplekv.memory import DictStore

            session_kvstore = DictStore()

        self.kvsession_extension = KVSessionExtension(session_kvstore, app)
コード例 #13
0
def register_extensions(app):
    bcrypt.init_app(app)
    db.init_app(app)
    csrf_protect.init_app(app)
    login.init_app(app)
    migrate.init_app(app, db)
    KVSessionExtension(store, app)
    babel = Babel(app)
    mail.init_app(app)

    @babel.localeselector
    def get_locale():
        # return 'ja'
        return request.accept_languages \
            .best_match(current_app.config['LANGUAGES'])

    return None
コード例 #14
0
def create_app_from_config(config):
    """ Create a new application based on the given configuration
    """
    app = flask.Flask(__name__)
    app.cli.add_command(manage.mailu)

    # Bootstrap is used for basic JS and CSS loading
    # TODO: remove this and use statically generated assets instead
    app.bootstrap = flask_bootstrap.Bootstrap(app)

    # Initialize application extensions
    config.init_app(app)
    models.db.init_app(app)
    KVSessionExtension(
        RedisStore(redis.StrictRedis().from_url('redis://{0}/3'.format(
            config['REDIS_ADDRESS']))), app).cleanup_sessions(app)
    utils.limiter.init_app(app)
    utils.babel.init_app(app)
    utils.login.init_app(app)
    utils.login.user_loader(models.User.get)
    utils.proxy.init_app(app)
    utils.migrate.init_app(app, models.db)

    # Initialize debugging tools
    if app.config.get("DEBUG"):
        debug.toolbar.init_app(app)
        # TODO: add a specific configuration variable for profiling
        # debug.profiler.init_app(app)

    # Inject the default variables in the Jinja parser
    # TODO: move this to blueprints when needed
    @app.context_processor
    def inject_defaults():
        signup_domains = models.Domain.query.filter_by(
            signup_enabled=True).all()
        return dict(signup_domains=signup_domains, config=app.config)

    # Import views
    from mailu import ui, internal
    app.register_blueprint(ui.ui, url_prefix='/ui')
    app.register_blueprint(internal.internal, url_prefix='/internal')

    return app
コード例 #15
0
def init_flask_sessions(context):
    """ Enable third-party server-side session storage """
    redis_config = context.settings.get("sessions", dict()).get("redis", dict())
    #
    if redis_config:
        session_store = RedisStore(
            StrictRedis(
                host=redis_config.get("host", "localhost"),
                password=redis_config.get("password", None),
            )
        )
        session_prefix = context.settings.get("sessions", dict()).get("prefix", None)
        if session_prefix:
            session_store = PrefixDecorator(session_prefix, session_store)
        log.info("Using redis for session storage")
    else:
        session_store = DictStore()
        log.info("Using memory for session storage")
    #
    KVSessionExtension(session_store, context.app)
コード例 #16
0
def issue27app(request):
    app = Flask(__name__)
    app.secret_key = 'foo'

    # toggle for default session
    if request.param is True:
        KVSessionExtension(RedisStore(redis.StrictRedis()), app)

    @app.route('/')
    def index():
        if 'x' not in session:
            session['x'] = 0
        return str(session['x'])

    @app.route('/test')
    def test():
        session['x'] = session.get('x', 0) + 1
        return str(session['x'])

    return app
コード例 #17
0
def issue27app(request):
    app = Flask(__name__)
    app.secret_key = "foo"

    # toggle for default session
    if request.param is True:
        KVSessionExtension(RedisStore(redis.StrictRedis()), app)

    @app.route("/")
    def index():
        if "x" not in session:
            session["x"] = 0
        return str(session["x"])

    @app.route("/test")
    def test():
        session["x"] = session.get("x", 0) + 1
        return str(session["x"])

    return app
コード例 #18
0
ファイル: ext.py プロジェクト: otron/invenio-accounts
    def init_app(self, app, use_celery=True, sessionstore=None):
        """Flask application initialization.

        :param sessionstore: store for sessions. Passed to
            ``flask-kvsession``. Defaults to redis.
        """
        self.init_config(app)

        # Create user datastore
        self.datastore = SQLAlchemyUserDatastore(db, User, Role)

        # Create sessionstore
        if sessionstore is None:
            import redis
            from simplekv.memory.redisstore import RedisStore

            sessionstore = RedisStore(
                redis.StrictRedis.from_url(
                    app.config['ACCOUNTS_SESSION_REDIS_URL']))

        self.sessionstore = sessionstore
        user_logged_in.connect(login_listener, app)

        # Initialize extension.
        state = self.security.init_app(app, datastore=self.datastore)
        self.kvsession_extension = KVSessionExtension(self.sessionstore, app)

        if app.config['ACCOUNTS_USE_CELERY']:
            from invenio_accounts.tasks import send_security_email

            @state.send_mail_task
            def delay_security_email(msg):
                send_security_email.delay(msg.__dict__)

        # Register CLI
        app.cli.add_command(roles_cli, 'roles')
        app.cli.add_command(users_cli, 'users')

        app.extensions['invenio-accounts'] = self
コード例 #19
0
ファイル: app.py プロジェクト: mamsterla/gfdc
def setup_app(app):
    """Do general app setup so we can run from gunicorn or command line"""
    global HOST, PORT
    setup_db()

    app.config['SESSION_TYPE'] = 'redis'
    app.config['SECRET_KEY'] = '12345abcde'
    app.config['REDIS_URL'] = get_redis_url()

    # a DictStore will store everything in memory
    STORE = DictStore()
    # this will replace the app's session handling
    KVSessionExtension(STORE, APP)

    PORT = int(os.environ.get('PORT', 5000))
    HOST = os.environ.get('HOST', 'localhost')
    LOGGER.info("Starting application on PORT=%d", PORT)
    # Bind to PORT if defined, otherwise default to 5000.
    app.debug = False
    #APP.testing = True
    app.secret_key = '12345abcde'
    RQDashboard(app)
コード例 #20
0
def expire_session(app, user):
    logger.debug("Cleanup sessions")
    session.destroy()
    KVSessionExtension(app=app).cleanup_sessions(app)
コード例 #21
0
def create_app(db_connection_string=None, testing=None):
    app = Flask(__name__)

    try:
        secret_key = faraday.server.config.faraday_server.secret_key
    except Exception:
        # Now when the config file does not exist it doesn't enter in this
        # condition, but it could happen in the future. TODO check
        save_new_secret_key(app)
    else:
        if secret_key is None:
            # This is what happens now when the config file doesn't exist.
            # TODO check
            save_new_secret_key(app)
        else:
            app.config['SECRET_KEY'] = secret_key

    if faraday.server.config.faraday_server.agent_token is None:
        save_new_agent_creation_token()

    login_failed_message = ("Invalid username or password", 'error')

    app.config.update({
        'SECURITY_PASSWORD_SINGLE_HASH': True,
        'WTF_CSRF_ENABLED': False,
        'SECURITY_USER_IDENTITY_ATTRIBUTES': ['username'],
        'SECURITY_POST_LOGIN_VIEW': '/_api/session',
        'SECURITY_POST_LOGOUT_VIEW': '/_api/login',
        'SECURITY_POST_CHANGE_VIEW': '/_api/change',
        'SECURITY_CHANGEABLE': True,
        'SECURITY_SEND_PASSWORD_CHANGE_EMAIL': False,
        'SECURITY_MSG_USER_DOES_NOT_EXIST': login_failed_message,
        'SECURITY_TOKEN_AUTHENTICATION_HEADER': 'Authorization',

        # The line bellow should not be necessary because of the
        # CustomLoginForm, but i'll include it anyway.
        'SECURITY_MSG_INVALID_PASSWORD': login_failed_message,

        'SESSION_TYPE': 'filesystem',
        'SESSION_FILE_DIR': faraday.server.config.FARADAY_SERVER_SESSIONS_DIR,

        'SQLALCHEMY_TRACK_MODIFICATIONS': False,
        'SQLALCHEMY_RECORD_QUERIES': True,
        # app.config['SQLALCHEMY_ECHO'] = True
        'SECURITY_PASSWORD_SCHEMES': [
            'bcrypt',  # This should be the default value
            # 'des_crypt',
            'pbkdf2_sha1',  # Used by CouchDB passwords
            # 'pbkdf2_sha256',
            # 'pbkdf2_sha512',
            # 'sha256_crypt',
            # 'sha512_crypt',
            'plaintext',  # TODO: remove it
        ],
        'PERMANENT_SESSION_LIFETIME': datetime.timedelta(hours=12),
        'SESSION_COOKIE_NAME': 'faraday_session_2',
        'SESSION_COOKIE_SAMESITE': 'Lax',
    })

    store = FilesystemStore(app.config['SESSION_FILE_DIR'])
    prefixed_store = PrefixDecorator('sessions_', store)
    KVSessionExtension(prefixed_store, app)
    user_logged_out.connect(expire_session, app)

    storage_path = faraday.server.config.storage.path
    if not storage_path:
        logger.warn('No storage section or path in the .faraday/config/server.ini. Setting the default value to .faraday/storage')
        storage_path = setup_storage_path()

    if not DepotManager.get('default'):
        if testing:
            DepotManager.configure('default', {
                'depot.storage_path': '/tmp'
            })
        else:
            DepotManager.configure('default', {
                'depot.storage_path': storage_path
            })

    check_testing_configuration(testing, app)

    try:
        app.config['SQLALCHEMY_DATABASE_URI'] = db_connection_string or faraday.server.config.database.connection_string.strip("'")
    except AttributeError:
        logger.info('Missing [database] section on server.ini. Please configure the database before running the server.')
    except NoOptionError:
        logger.info('Missing connection_string on [database] section on server.ini. Please configure the database before running the server.')

    from faraday.server.models import db # pylint:disable=import-outside-toplevel
    db.init_app(app)
    #Session(app)

    # Setup Flask-Security
    app.user_datastore = SQLAlchemyUserDatastore(
        db,
        user_model=User,
        role_model=None)  # We won't use flask security roles feature
    Security(app, app.user_datastore, login_form=CustomLoginForm)
    # Make API endpoints require a login user by default. Based on
    # https://stackoverflow.com/questions/13428708/best-way-to-make-flask-logins-login-required-the-default

    app.view_functions['security.login'].is_public = True
    app.view_functions['security.logout'].is_public = True

    app.debug = faraday.server.config.is_debug_mode()
    minify_json_output(app)

    for handler in LOGGING_HANDLERS:
        app.logger.addHandler(handler)

    register_blueprints(app)
    register_handlers(app)

    app.view_functions['agent_api.AgentCreationView:post'].is_public = True

    return app
コード例 #22
0
    def init_app(self, app, sessionstore=None, register_blueprint=True):
        """Flask application initialization.

        The following actions are executed:

        #. Initialize the configuration.

        #. Monkey-patch Flask-Security.

        #. Create the user datastore.

        #. Create the sessionstore.

        #. Initialize the extension, the forms to register users and
           confirms their emails, the CLI and, if ``ACCOUNTS_USE_CELERY`` is
           ``True``, register a celery task to send emails.

        #. Override Flask-Security's default login view function.

        #. Warn if inconsistent configuration is detected

        :param app: The Flask application.
        :param sessionstore: store for sessions. Passed to
            ``flask-kvsession``. If ``None`` then Redis is configured.
            (Default: ``None``)
        :param register_blueprint: If ``True``, the application registers the
            blueprints. (Default: ``True``)
        """
        self.init_config(app)

        # Monkey-patch Flask-Security
        InvenioAccounts.monkey_patch_flask_security()

        # Create user datastore
        if not self.datastore:
            self.datastore = SessionAwareSQLAlchemyUserDatastore(
                db, User, Role)

        if app.config["ACCOUNTS_SESSION_ACTIVITY_ENABLED"]:
            self._enable_session_activity(app=app)

        # Initialize extension.
        _register_blueprint = app.config.get("ACCOUNTS_REGISTER_BLUEPRINT")
        if _register_blueprint is not None:
            register_blueprint = _register_blueprint

        state = self.security.init_app(app,
                                       datastore=self.datastore,
                                       register_blueprint=register_blueprint)

        # Override Flask-Security's default login view function
        new_login_view = obj_or_import_string(
            app.config.get("ACCOUNTS_LOGIN_VIEW_FUNCTION"))
        if new_login_view is not None:
            app.view_functions["security.login"] = new_login_view

        self.register_anonymous_identity_loader(state)

        app.extensions["security"].register_form = register_form_factory(
            app.extensions["security"].register_form, app)

        app.extensions[
            "security"].confirm_register_form = confirm_register_form_factory(
                app.extensions["security"].confirm_register_form, app)

        app.extensions["security"].login_form = login_form_factory(
            app.extensions["security"].login_form, app)

        if app.config["ACCOUNTS_USE_CELERY"]:
            from invenio_accounts.tasks import send_security_email

            @state.send_mail_task
            def delay_security_email(msg):
                send_security_email.delay(msg.__dict__)

        # Register context processor
        if app.config["ACCOUNTS_JWT_DOM_TOKEN"]:
            from invenio_accounts.context_processors.jwt import jwt_proccessor

            app.context_processor(jwt_proccessor)

        # Register signal receiver
        if app.config.get("ACCOUNTS_USERINFO_HEADERS"):
            request_finished.connect(set_session_info, app)

        # Set Session KV store
        session_kvstore_factory = obj_or_import_string(
            app.config["ACCOUNTS_SESSION_STORE_FACTORY"])
        session_kvstore = session_kvstore_factory(app)

        self.kvsession_extension = KVSessionExtension(session_kvstore, app)

        self.check_configuration_consistency(app)

        app.extensions["invenio-accounts"] = self
コード例 #23
0
ファイル: app.py プロジェクト: hecg119/faraday
def create_app(db_connection_string=None, testing=None):
    class CustomFlask(Flask):
        SKIP_RULES = [  # These endpoints will be removed for v3
            '/v3/ws/<workspace_name>/hosts/bulk_delete/',
            '/v3/ws/<workspace_name>/vulns/bulk_delete/',
            '/v3/ws/<workspace_id>/change_readonly/',
            '/v3/ws/<workspace_id>/deactivate/',
            '/v3/ws/<workspace_id>/activate/',
        ]

        def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
            # Flask registers views when an application starts
            # do not add view from SKIP_VIEWS
            for rule_ in CustomFlask.SKIP_RULES:
                if rule_ == rule:
                    return
            return super().add_url_rule(rule, endpoint, view_func, **options)

    app = CustomFlask(__name__, static_folder=None)

    try:
        secret_key = faraday.server.config.faraday_server.secret_key
    except Exception:
        # Now when the config file does not exist it doesn't enter in this
        # condition, but it could happen in the future. TODO check
        save_new_secret_key(app)
    else:
        if secret_key is None:
            # This is what happens now when the config file doesn't exist.
            # TODO check
            save_new_secret_key(app)
        else:
            app.config['SECRET_KEY'] = secret_key

    if faraday.server.config.faraday_server.agent_registration_secret is None:
        save_new_agent_creation_token_secret()

    login_failed_message = ("Invalid username or password", 'error')

    app.config.update({
        'SECURITY_BACKWARDS_COMPAT_AUTH_TOKEN':
        True,
        'SECURITY_PASSWORD_SINGLE_HASH':
        True,
        'WTF_CSRF_ENABLED':
        False,
        'SECURITY_USER_IDENTITY_ATTRIBUTES': [{
            'username': {
                'mapper': uia_username_mapper
            }
        }],
        'SECURITY_POST_LOGIN_VIEW':
        '/_api/session',
        'SECURITY_POST_CHANGE_VIEW':
        '/_api/change',
        'SECURITY_RESET_PASSWORD_TEMPLATE':
        '/security/reset.html',
        'SECURITY_POST_RESET_VIEW':
        '/',
        'SECURITY_SEND_PASSWORD_RESET_EMAIL':
        True,
        # For testing porpouse
        'SECURITY_EMAIL_SENDER':
        "*****@*****.**",
        'SECURITY_CHANGEABLE':
        True,
        'SECURITY_SEND_PASSWORD_CHANGE_EMAIL':
        False,
        'SECURITY_MSG_USER_DOES_NOT_EXIST':
        login_failed_message,
        'SECURITY_TOKEN_AUTHENTICATION_HEADER':
        'Authorization',

        # The line bellow should not be necessary because of the
        # CustomLoginForm, but i'll include it anyway.
        'SECURITY_MSG_INVALID_PASSWORD':
        login_failed_message,
        'SESSION_TYPE':
        'filesystem',
        'SESSION_FILE_DIR':
        faraday.server.config.FARADAY_SERVER_SESSIONS_DIR,
        'SQLALCHEMY_TRACK_MODIFICATIONS':
        False,
        'SQLALCHEMY_RECORD_QUERIES':
        True,
        # app.config['SQLALCHEMY_ECHO'] = True
        'SECURITY_PASSWORD_SCHEMES': [
            'bcrypt',  # This should be the default value
            # 'des_crypt',
            # 'pbkdf2_sha256',
            # 'pbkdf2_sha512',
            # 'sha256_crypt',
            # 'sha512_crypt',
        ],
        'PERMANENT_SESSION_LIFETIME':
        datetime.timedelta(hours=int(
            faraday.server.config.faraday_server.session_timeout or 12)),
        'SESSION_COOKIE_NAME':
        'faraday_session_2',
        'SESSION_COOKIE_SAMESITE':
        'Lax',
    })

    store = FilesystemStore(app.config['SESSION_FILE_DIR'])
    prefixed_store = PrefixDecorator('sessions_', store)
    KVSessionExtension(prefixed_store, app)
    user_logged_in.connect(user_logged_in_succesfull, app)
    user_logged_out.connect(expire_session, app)

    storage_path = faraday.server.config.storage.path
    if not storage_path:
        logger.warn(
            'No storage section or path in the .faraday/config/server.ini. Setting the default value to .faraday/storage'
        )
        storage_path = setup_storage_path()

    if not DepotManager.get('default'):
        if testing:
            DepotManager.configure(
                'default',
                {
                    'depot.storage_path': '/tmp'  # nosec
                })
        else:
            DepotManager.configure('default',
                                   {'depot.storage_path': storage_path})

    check_testing_configuration(testing, app)

    try:
        app.config[
            'SQLALCHEMY_DATABASE_URI'] = db_connection_string or faraday.server.config.database.connection_string.strip(
                "'")
    except AttributeError:
        logger.info(
            'Missing [database] section on server.ini. Please configure the database before running the server.'
        )
    except NoOptionError:
        logger.info(
            'Missing connection_string on [database] section on server.ini. Please configure the database before running the server.'
        )

    from faraday.server.models import db  # pylint:disable=import-outside-toplevel
    db.init_app(app)
    # Session(app)

    # Setup Flask-Security
    app.user_datastore = SQLAlchemyUserDatastore(
        db, user_model=User,
        role_model=None)  # We won't use flask security roles feature

    from faraday.server.api.modules.agent import agent_creation_api  # pylint: disable=import-outside-toplevel

    app.limiter = Limiter(app, key_func=get_remote_address, default_limits=[])
    if not testing:
        app.limiter.limit(faraday.server.config.limiter_config.login_limit)(
            agent_creation_api)

    app.register_blueprint(agent_creation_api)

    Security(app, app.user_datastore, login_form=CustomLoginForm)
    # Make API endpoints require a login user by default. Based on
    # https://stackoverflow.com/questions/13428708/best-way-to-make-flask-logins-login-required-the-default

    app.view_functions['security.login'].is_public = True
    app.view_functions['security.logout'].is_public = True
    app.debug = faraday.server.config.is_debug_mode()
    minify_json_output(app)

    for handler in LOGGING_HANDLERS:
        app.logger.addHandler(handler)
    app.logger.propagate = False
    register_blueprints(app)
    register_handlers(app)

    app.view_functions[
        'agent_creation_api.AgentCreationView:post'].is_public = True
    app.view_functions[
        'agent_creation_api.AgentCreationV3View:post'].is_public = True

    return app
コード例 #24
0
# -*- coding: utf-8 -*-
from simplekv.memory import DictStore
from flask_kvsession import KVSessionExtension
from flask_wtf.csrf import CsrfProtect
from flask import abort

store = DictStore()
kvsession = KVSessionExtension(store)
csrf_protect = CsrfProtect()


@csrf_protect.error_handler
def csrf_error(reason):
    return abort(
        400, {
            'code':
            400,
            'message':
            'Request token missing or exprired. Please press F5 to refresh'
        })
コード例 #25
0
import sys
from docassemble.base.config import daconfig
from docassemble.webapp.app_object import app
from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore
import docassemble.base.config
docassemble.base.config.load(arguments=sys.argv)
import docassemble.base.util
import docassemble.webapp.daredis

store = RedisStore(docassemble.webapp.daredis.r_store)
kv_session = KVSessionExtension(store, app)
with app.app_context():
    kv_session.cleanup_sessions()
コード例 #26
0
def test_delayed_construction_with_default(vapp, store):
    ext = KVSessionExtension(store)
    ext.init_app(vapp)

    assert vapp.kvsession_store == store
コード例 #27
0

@json.error_handler
def error_handler(e):
    return json_response(status_=401, description='An error occured')


#------------------------------------
#	More Complex Intialization of Extensions
#------------------------------------

engine = create_engine(VWM.config['SQLALCHEMY_DATABASE_URI'])
metadata = MetaData(bind=engine)
session_store = SQLAlchemyStore(engine, metadata, 'kvsession_table')
metadata.create_all()
kvsession_extension = KVSessionExtension(session_store, VWM)

#----------------------------------------------------------------------------------
#	end initialize all required values
#----------------------------------------------------------------------------------

#------------------------------------------------------
#|||||||||||||||||||||||||||||||||||||||||||||||||||||
#routing blueprints starts now
VWM.register_blueprint(api_v1, url_prefix='/paywallet/v1')

#end of blueprint route
#||||||||||||||||||||||||||||||||||||||||||||||||||||||||
#----------------------------------------------------------

# @VWM.route("/start/<string:VWM>/<string:Key>")
コード例 #28
0
ファイル: app.py プロジェクト: OzzyTheGiant/electro
load_dotenv()
# get environment variables
configure_logging()
# configure loggers before starting app

app = Flask(__name__)
app.config.update(**config)

# Configure Session using standard web session files,
# more store types available in simplekv package
# Hash Decorator provides session id
session_store = HashDecorator(
    WebFilesystemStore(os.getenv("FLASK_SESSION_FILE_PATH"),
                       os.getenv("FLASK_SESSION_URL_PREFIX")))
KVSessionExtension(session_store, app)

# Add CSRFProtect extension to flask app
# NOTE: this extends flask_wtf.CSRFProtect class; see class definition for details
CSRFProtectionExtension(app)

# Create Api blueprint and add resources (routes)
api_blueprint = Blueprint('api', __name__)
api = ElectroAPI(api_blueprint, catch_all_404s=True)
# contains custom error handler
api.add_resource(BillResource, "/bills", "/bills/<int:id>", endpoint="bill")
api.add_resource(UserResource, "/login", "/logout", endpoint="login")

# Register blueprint to app
app.register_blueprint(api_blueprint, url_prefix="/api")
コード例 #29
0
ファイル: __init__.py プロジェクト: jirikuncar/renku-gateway
from quart_cors import cors

from .config import config, load_config

logging.basicConfig(level=logging.DEBUG)

app = Quart(__name__)

for key in config.keys():
    app.config[key] = config[key]

app = cors(app,
           allow_headers=['X-Requested-With'],
           allow_origin=app.config['ALLOW_ORIGIN'])

load_config()

if "pytest" in sys.modules:
    from mockredis import mock_strict_redis_client
    store = RedisStore(mock_strict_redis_client())
else:
    store = RedisStore(redis.StrictRedis(host=app.config['REDIS_HOST']))

prefixed_store = PrefixDecorator('sessions_', store)
KVSessionExtension(prefixed_store, app)

from .gateway import proxy
from .auth import web
from .auth.gitlab_auth import gitlab_login, gitlab_get_tokens, gitlab_logout
from .auth.jupyterhub_auth import jupyterhub_login, jupyterhub_get_tokens, jupyterhub_logout
コード例 #30
0
def _app(store):
    app = Flask(__name__)

    app.kvsession = KVSessionExtension(store, app)
    app.config['TESTING'] = True
    app.config['SECRET_KEY'] = 'devkey'

    @app.route('/')
    def index():
        return 'nothing to see here, move along'

    @app.route('/store-in-session/<key>/<value>/')
    def store(key, value):
        session[key] = value
        return 'stored %r at %r' % (value, key)

    @app.route('/store-datetime/')
    def store_datetime():
        t = datetime(2011, 8, 10, 15, 46, 00)
        session['datetime_key'] = t
        return 'ok'

    @app.route('/delete-from-session/<key>/')
    def delete(key):
        del session[key]
        return 'deleted %r' % key

    @app.route('/destroy-session/')
    def destroy():
        session.destroy()
        return 'session destroyed'

    @app.route('/make-session-permanent/')
    def make_permanent():
        session.permanent = True
        return 'made session permanent'

    @app.route('/dump-session/')
    def dump():
        return json.dumps(dict(session))

    @app.route('/dump-datetime/')
    def dump_datetime():
        return str(session['datetime_key'])

    @app.route('/regenerate-session/')
    def regenerate():
        session.regenerate()
        return 'session regenerated'

    @app.route('/is-kvsession/')
    def is_kvsession():
        return str(isinstance(session._get_current_object(), KVSession))

    @app.route('/is-new-session/')
    def is_new_session():
        return str(session.new)

    @app.route('/is-modified-session/')
    def is_modified_session():
        return str(session.modified)

    @app.route('/destroy-immediately/')
    def destroy_immediately():
        # from issue
        # 1. Set a session.
        # works implicitly
        # 2. Update session with keys.
        session['foo'] = 'bar'
        # 3. Destroy.
        session.destroy()
        # 4. Check if destroy worked.
        # ????
        # 5. PROFIT
        return 'PROFIT'

    return app
コード例 #31
0
import os
from flask_kvsession import KVSessionExtension
from flask_kvsession import SessionID
from flask import current_app
from simplekv.memory.redisstore import RedisStore
from simplekv.db.sql import SQLAlchemyStore
from sqlalchemy import create_engine, MetaData
from simplekv.decorator import PrefixDecorator

if os.environ.get('IS_PROD', None):
    store = RedisStore(
        redis.StrictRedis(host=os.environ.get('redis_host', None),
                          port=os.environ.get('redis_port', None),
                          db=os.environ.get('db', None),
                          password=os.environ.get('redis_password')))
    prefix_store = PrefixDecorator('session_', store)
    s = KVSessionExtension(prefix_store, current_app)
else:
    if os.environ.get('IS_PROD'):
        engine = create_engine(os.environ.get('CLEARDB_DATABASE_URL'))
    else:
        from techmarketplace import Configuration
        engine = create_engine(
            'mysql+mysqlconnector://{0}:{1}@localhost/projectdb'.format(
                Configuration.dbuser, Configuration.dbpw))
    metadata = MetaData(bind=engine)
    store = SQLAlchemyStore(engine, metadata, 'session')
    # metadata.create_all()
    prefix_store = PrefixDecorator('session_', store)
    kvsession_extension = KVSessionExtension(prefix_store, current_app)
コード例 #32
0
ファイル: __init__.py プロジェクト: dgyuri92/oauth_app
from . import default_config
from .model import db, CsrfToken

# Flask setup
app = Flask(__name__)

# Load custom configuration
app.config.from_object(default_config)
app.config.from_pyfile("app.cfg", silent=True)

# Database setup
db.init_app(app)

# Session setup
try:
    os.makedirs(app.config['DEFAULT_SESSION_DIRECTORY'])
except FileExistsError:
    pass

# Using signed cookies here on the client side (itsdangerous)
session_manager = KVSessionExtension(FilesystemStore(app.config['DEFAULT_SESSION_DIRECTORY']), app)

# Create database and make sure to clean up expired sessions
with app.app_context():
    db.create_all()
    try:
        session_manager.cleanup_sessions()
    except:
        pass
コード例 #33
0
db = SQLAlchemy(app)
SQLAlchemy.health = health

from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore

redis_url = urlparse.urlparse(app.config.get('REDIS_URL'))

redis_server = redis.StrictRedis(
        host=redis_url.hostname,
        port=redis_url.port,
        password=redis_url.password
)

store = RedisStore(redis_server)
kv_store = KVSessionExtension(store, app)

Health(app, checks=[db.health])

# Audit, error handling and after_request headers all handled by lrutils
Audit(app)
ErrorHandler(app)
app.after_request(eh_after_request)

if not app.debug:
    app.logger.addHandler(logging.StreamHandler())
    app.logger.setLevel(logging.INFO)

if app.config.get('BASIC_AUTH_USERNAME'):
    app.config['BASIC_AUTH_FORCE'] = True
    basic_auth = BasicAuth(app)
コード例 #34
0
ファイル: __init__.py プロジェクト: alvinwan/Puhjiii
# database connection
app.config['MONGODB_SETTINGS'] = {'DB': config.DB}
app.config['SECRET_KEY'] = config.SECRET_KEY
app.debug = config.DEBUG

# initialize MongoEngine with app
db = MongoEngine()
db.init_app(app)
store = MongoStore(
	getattr(db.connection, config.DB), 
	config.SESSION_STORE)
session = KeyValueStore()

# Substitute client-side with server-side sessions
kv_session = KVSessionExtension()
kv_session.init_app(app, store)

# initialize Flask-Login with app
login_manager = LoginManager()
login_manager.init_app(app)

# initialize encryption mechanism
bcrypt = Bcrypt()
bcrypt.init_app(app)

from server.auth.views import mod_auth
from server.nest.views import mod_nest
from server.public.views import mod_public
from server.nest.libs import Plugin