Exemplo n.º 1
0
def register_at(app: Flask):

    from flexmeasures.auth.error_handling import (
        unauthenticated_handler,
        unauthenticated_handler_e,
    )  # noqa: F401
    from flexmeasures.auth.error_handling import (
        unauthorized_handler,
        unauthorized_handler_e,
    )  # noqa: F401
    from flexmeasures.data.models.user import User, Role, remember_login  # noqa: F401

    # Setup Flask-Security-Too for user authentication & authorization
    user_datastore = SQLAlchemySessionUserDatastore(db.session, User, Role)
    app.security = Security(app, user_datastore)

    # Register custom auth problem handlers.
    # Note how we are switching authorization and authentication - read more about this in error_handling.py!
    # Flask-Security-Too seems to handle it the intended way:
    # https://flask-security-too.readthedocs.io/en/stable/api.html#flask_security.Security.unauthn_handler
    # is defaulting to 401.
    app.security.unauthn_handler(unauthenticated_handler)
    app.register_error_handler(Unauthorized, unauthenticated_handler_e)
    app.security.unauthz_handler(unauthorized_handler)
    app.register_error_handler(Forbidden, unauthorized_handler_e)

    # add our custom handler for a user login event
    user_logged_in.connect(remember_login)
Exemplo n.º 2
0
    def init_app(self, app, assets=None, **kwargs):
        """Initialize application object."""
        self.init_config(app.config)

        # Initialize extensions
        self.menu_ext.init_app(app)
        self.menu = app.extensions['menu']
        self.breadcrumbs.init_app(app)

        app.register_blueprint(blueprint)

        # Configure Jinja2 environment.
        app.jinja_env.add_extension('jinja2.ext.do')
        app.jinja_env.lstrip_blocks = True
        app.jinja_env.trim_blocks = True

        # Register errors handlers.
        app.register_error_handler(401, unauthorized)
        app.register_error_handler(403, insufficient_permissions)
        app.register_error_handler(404, page_not_found)
        app.register_error_handler(500, internal_error)

        user_logged_in.connect(load_user_collections, app)

        # Save reference to self on object
        app.extensions['inspire-theme'] = self
Exemplo n.º 3
0
    def init_app(self, app, assets=None, **kwargs):
        """Initialize application object."""
        self.init_config(app.config)

        # Initialize extensions
        self.menu_ext.init_app(app)
        self.menu = app.extensions['menu']
        self.breadcrumbs.init_app(app)

        app.register_blueprint(blueprint)

        # Configure Jinja2 environment.
        app.jinja_env.add_extension('jinja2.ext.do')
        app.jinja_env.lstrip_blocks = True
        app.jinja_env.trim_blocks = True

        # Register errors handlers.
        app.register_error_handler(401, unauthorized)
        app.register_error_handler(403, insufficient_permissions)
        app.register_error_handler(404, page_not_found)
        app.register_error_handler(500, internal_error)

        user_logged_in.connect(load_user_collections, app)

        # Save reference to self on object
        app.extensions['inspire-theme'] = self
Exemplo n.º 4
0
def init_app(app):
    from redash.authentication import (
        saml_auth,
        remote_user_auth,
        ldap_auth,
    )

    from redash.authentication.google_oauth import create_google_oauth_blueprint

    login_manager.init_app(app)
    login_manager.anonymous_user = models.AnonymousUser
    login_manager.REMEMBER_COOKIE_DURATION = settings.REMEMBER_COOKIE_DURATION

    @app.before_request
    def extend_session():
        session.permanent = True
        app.permanent_session_lifetime = timedelta(
            seconds=settings.SESSION_EXPIRY_TIME)

    from redash.security import csrf

    # Authlib's flask oauth client requires a Flask app to initialize
    for blueprint in [
            create_google_oauth_blueprint(app),
            saml_auth.blueprint,
            remote_user_auth.blueprint,
            ldap_auth.blueprint,
    ]:
        csrf.exempt(blueprint)
        app.register_blueprint(blueprint)

    user_logged_in.connect(log_user_logged_in)
    login_manager.request_loader(request_loader)
Exemplo n.º 5
0
def setup_authentication(app):
    from redash.authentication import google_oauth, saml_auth, remote_user_auth, ldap_auth, mobifun_oauth

    login_manager.init_app(app)
    oauth.init_app(app)
    login_manager.anonymous_user = models.AnonymousUser

    app.secret_key = settings.COOKIE_SECRET
    app.register_blueprint(google_oauth.blueprint)
    app.register_blueprint(saml_auth.blueprint)
    app.register_blueprint(remote_user_auth.blueprint)
    app.register_blueprint(ldap_auth.blueprint)
    app.register_blueprint(mobifun_oauth.blueprint)

    user_logged_in.connect(log_user_logged_in)

    if settings.AUTH_TYPE == 'hmac':
        login_manager.request_loader(hmac_load_user_from_request)
    elif settings.AUTH_TYPE == 'api_key':
        login_manager.request_loader(api_key_load_user_from_request)
    else:
        logger.warning(
            "Unknown authentication type ({}). Using default (HMAC).".format(
                settings.AUTH_TYPE))
        login_manager.request_loader(hmac_load_user_from_request)
Exemplo n.º 6
0
    def _enable_logger_activity(self, app):
        """
        Enable session activity.

        :param app: The flask application.
        """
        user_logged_in.connect(login_listener, app)
        user_logged_out.connect(logout_listener, app)
Exemplo n.º 7
0
 def _enable_session_activity(self, app):
     """Enable session activity."""
     user_logged_in.connect(login_listener, app)
     user_logged_out.connect(logout_listener, app)
     from .views.settings import blueprint
     from .views.security import security, revoke_session
     blueprint.route('/security/', methods=['GET'])(security)
     blueprint.route('/sessions/revoke/', methods=['POST'])(revoke_session)
Exemplo n.º 8
0
    def _enable_session_activity(self, app):
        """Enable session activity."""
        user_logged_in.connect(login_listener, app)
        user_logged_in.connect(csrf_token_reset, app)
        user_logged_out.connect(logout_listener, app)
        user_logged_out.connect(csrf_token_reset, app)
        from .views.security import revoke_session, security
        from .views.settings import blueprint

        blueprint.route("/security/", methods=["GET"])(security)
        blueprint.route("/sessions/revoke/", methods=["POST"])(revoke_session)
Exemplo n.º 9
0
 def init_app(self, app):
   login_manager.init_app(app)
   login_manager.login_view = 'login.login_form'
   Service.init_app(self, app)
   self.login_url_prefix = app.config.get('LOGIN_URL', '/user')
   app.before_request(self.do_access_control)
   app.before_request(self.update_user_session_data)
   user_logged_in.connect(self.user_logged_in, sender=app)
   user_logged_out.connect(self.user_logged_out, sender=app)
   app.register_blueprint(login_views, url_prefix=self.login_url_prefix)
   with app.app_context():
     actions.register(*_ACTIONS)
Exemplo n.º 10
0
 def init_app(self, app):
     login_manager.init_app(app)
     login_manager.login_view = 'login.login_form'
     Service.init_app(self, app)
     self.login_url_prefix = app.config.get('LOGIN_URL', '/user')
     app.before_request(self.do_access_control)
     app.before_request(self.update_user_session_data)
     user_logged_in.connect(self.user_logged_in, sender=app)
     user_logged_out.connect(self.user_logged_out, sender=app)
     app.register_blueprint(login_views, url_prefix=self.login_url_prefix)
     with app.app_context():
         actions.register(*_ACTIONS)
Exemplo n.º 11
0
def setup_login_manager(app):
    """
    Configure the LoginManager for the provided app.
    """
    login_manager = LoginManager()
    login_manager.login_view = 'auth.login_user'
    login_manager.login_message = 'Resource access not authorized.'
    login_manager.login_message_category = 'error'
    login_manager.anonymous_user = AnonymousUser
    login_manager.init_app(app)
    login_manager.user_loader(load_user)
    user_logged_in.connect(on_login, app)
Exemplo n.º 12
0
def setup_login_manager(app):
    """
    Configure the LoginManager for the provided app.
    """
    login_manager = LoginManager()
    login_manager.login_view = 'auth.login_user'
    login_manager.login_message = 'Resource access not authorized.'
    login_manager.login_message_category = 'error'
    login_manager.anonymous_user = AnonymousUser
    login_manager.init_app(app)
    login_manager.user_loader(load_user)
    user_logged_in.connect(on_login, app)
Exemplo n.º 13
0
def init_app(app):
    from redash.authentication import google_oauth, saml_auth, remote_user_auth, ldap_auth

    login_manager.init_app(app)
    login_manager.anonymous_user = models.AnonymousUser

    app.register_blueprint(google_oauth.blueprint)
    app.register_blueprint(saml_auth.blueprint)
    app.register_blueprint(remote_user_auth.blueprint)
    app.register_blueprint(ldap_auth.blueprint)

    user_logged_in.connect(log_user_logged_in)
    login_manager.request_loader(request_loader)
Exemplo n.º 14
0
def init_app(app):
    from redash.authentication import google_oauth, saml_auth, remote_user_auth, ldap_auth

    login_manager.init_app(app)
    login_manager.anonymous_user = models.AnonymousUser

    app.register_blueprint(google_oauth.blueprint)
    app.register_blueprint(saml_auth.blueprint)
    app.register_blueprint(remote_user_auth.blueprint)
    app.register_blueprint(ldap_auth.blueprint)

    user_logged_in.connect(log_user_logged_in)
    login_manager.request_loader(request_loader)
Exemplo n.º 15
0
    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:
            if app.testing and \
                    os.environ.get('CI', 'false') == 'false':
                from simplekv.memory import DictStore

                sessionstore = DictStore()
            else:
                import redis
                from simplekv.memory.redisstore import RedisStore

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

        user_logged_in.connect(login_listener, app)

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

        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
            )

        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
Exemplo n.º 16
0
def create_app():
    app = Flask(__name__)
    from .views import main as main__blueprint
    app.config['SECRET_KEY'] = 'hehe'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
    app.register_blueprint(main__blueprint)
    db.init_app(app)
    bootstrap.init_app(app)
    login_manager.init_app(app)
    user_logged_in.connect(track_login, app)

    # @user_logged_in.connect_via(app)
    # def record(sender, **extra):
    #     print "====================================="
    return app
Exemplo n.º 17
0
    def setUp(self):
        super().setUp()

        self.flask_app = self._create_app()
        self.client = self.flask_app.test_client()
        self._ctx = self.flask_app.test_request_context()
        self._ctx.push()

        self.json_mod = json
        self.templates = []
        self.current_user = None
        template_rendered.connect(self._add_template)
        if HAVE_FLASK_LOGIN:
            user_logged_in.connect(self._signal_login)
            user_logged_out.connect(self._signal_logout)
Exemplo n.º 18
0
    def setUp(self):
        super().setUp()
        
        self.flask_app = self._create_app()
        self.client = self.flask_app.test_client()
        self._ctx = self.flask_app.test_request_context()
        self._ctx.push()

        self.json_mod = json
        self.templates = []
        self.current_user = None
        template_rendered.connect(self._add_template)
        if HAVE_FLASK_LOGIN:
            user_logged_in.connect(self._signal_login)
            user_logged_out.connect(self._signal_logout)
Exemplo n.º 19
0
    def init_app(self, app: Flask) -> None:
        login_manager.init_app(app)
        login_manager.login_view = "login.login_form"

        super().init_app(app)

        self.login_url_prefix = app.config.get("LOGIN_URL", "/user")

        app.before_request(self.do_access_control)
        app.before_request(self.update_user_session_data)
        user_logged_in.connect(self.user_logged_in, sender=app)
        user_logged_out.connect(self.user_logged_out, sender=app)

        app.register_blueprint(login_views, url_prefix=self.login_url_prefix)

        with app.app_context():
            actions.register(*_ACTIONS)
Exemplo n.º 20
0
def setup_authentication(app):
    login_manager.init_app(app)
    login_manager.anonymous_user = models.AnonymousUser

    app.secret_key = settings.COOKIE_SECRET
    app.register_blueprint(google_oauth.blueprint)
    app.register_blueprint(saml_auth.blueprint)

    user_logged_in.connect(log_user_logged_in)

    if settings.AUTH_TYPE == 'hmac':
        login_manager.request_loader(hmac_load_user_from_request)
    elif settings.AUTH_TYPE == 'api_key':
        login_manager.request_loader(api_key_load_user_from_request)
    else:
        logger.warning("Unknown authentication type ({}). Using default (HMAC).".format(settings.AUTH_TYPE))
        login_manager.request_loader(hmac_load_user_from_request)
Exemplo n.º 21
0
def configure_auth(app: Flask, db: SQLAlchemy):

    # Setup Flask-Security-Too for user authentication & authorization
    user_datastore = SQLAlchemySessionUserDatastore(db.session, User, Role)
    app.security = Security(app, user_datastore)

    # Register custom auth problem handlers.
    # Note how we are switching authorization and authentication now!
    # Flask-Security-Too seems to handle it the intendend way:
    # https://flask-security-too.readthedocs.io/en/stable/api.html#flask_security.Security.unauthn_handler
    # is defaulting to 401.
    app.security.unauthn_handler(unauthenticated_handler)
    app.register_error_handler(Unauthorized, unauthenticated_handler_e)
    app.security.unauthz_handler(unauthorized_handler)
    app.register_error_handler(Forbidden, unauthorized_handler_e)

    # add our custom handler for a user login event
    user_logged_in.connect(remember_login)
Exemplo n.º 22
0
def init_app(app):
    from redash.authentication import (
        google_oauth,
        saml_auth,
        remote_user_auth,
        ldap_auth,
    )

    login_manager.init_app(app)
    login_manager.anonymous_user = models.AnonymousUser

    from redash.security import csrf
    for auth in [google_oauth, saml_auth, remote_user_auth, ldap_auth]:
        blueprint = auth.blueprint
        csrf.exempt(blueprint)
        app.register_blueprint(blueprint)

    user_logged_in.connect(log_user_logged_in)
    login_manager.request_loader(request_loader)
Exemplo n.º 23
0
    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
Exemplo n.º 24
0
def create_app(db_connection_string=None, testing=None):
    app = Flask(__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_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_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
    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_api.AgentCreationView:post'].is_public = True

    return app
Exemplo n.º 25
0
 def init_app(self, app, *args, **kwargs):
     super(Sentry, self).init_app(app, *args, **kwargs)
     user_logged_in.connect(self._on_user_logged_in, sender=app)
Exemplo n.º 26
0
# Logging
#
def log_session_start(app, user):
  session = LoginSession.new()
  db.session.add(session)
  db.session.commit()


def log_session_end(app, user):
  session = LoginSession.query.get_active_for(user)
  if session:
    session.ended_at = datetime.utcnow()
    db.session.commit()


user_logged_in.connect(log_session_start)
user_logged_out.connect(log_session_end)


# login redirect utilities
#  from http://flask.pocoo.org/snippets/62/
def is_safe_url(target):
  ref_url = urlparse(request.host_url)
  test_url = urlparse(urljoin(request.url_root, target))
  return test_url.scheme in ('http', 'https') and \
      ref_url.netloc == test_url.netloc


def check_for_redirect(target):
  target = urljoin(request.url_root, target)
  url = urlparse(target)
Exemplo n.º 27
0
        session.rollback()
        log.exception(ex)


def check_user_session(user_id, session_key):
    try:
        return bool(
            session.query(User_Sessions).filter(
                User_Sessions.user_id == user_id,
                User_Sessions.session_key == session_key).one_or_none())
    except (exc.OperationalError, exc.InvalidRequestError):
        session.rollback()
        log.exception(e)


user_logged_in.connect(signal_store_user_session)


def store_ids(result):
    ids = list()
    for element in result:
        ids.append(element.id)
    searched_ids[current_user.id] = ids


def store_combo_ids(result):
    ids = list()
    for element in result:
        ids.append(element[0].id)
    searched_ids[current_user.id] = ids
Exemplo n.º 28
0
def create(config=None):
    """
    Create and configure a Flask application object.

    Args:
        config (dict): The configuration to use when creating the application.
            If no configuration is provided, :data:`anitya.config.config` is
            used.

    Returns:
        flask.Flask: The configured Flask application.
    """
    app = flask.Flask(__name__)

    if config is None:
        config = anitya_config
    app.config.update(config)
    initialize_db(config)

    app.register_blueprint(social_auth)
    if len(social_models.UserSocialAuth.__table_args__) == 0:
        # This is a bit of a hack - this initialization call sets up the SQLAlchemy
        # models with our own models and multiple calls to this function will cause
        # SQLAlchemy to fail with sqlalchemy.exc.InvalidRequestError. Only calling it
        # when there are no table arguments should ensure we only call it one time.
        #
        # Be aware that altering the configuration values this function uses, namely
        # the SOCIAL_AUTH_USER_MODEL, after the first time ``create`` has been called
        # will *not* cause the new configuration to be used for subsequent calls to
        # ``create``.
        social_models.init_social(app, Session)

    login_manager = LoginManager()
    login_manager.user_loader(authentication.load_user_from_session)
    login_manager.request_loader(authentication.load_user_from_request)
    login_manager.login_view = "/login/"
    login_manager.init_app(app)

    # Register the v2 API resources
    app.api = Api(app)
    app.api.add_resource(api_v2.ProjectsResource, "/api/v2/projects/")
    app.api.add_resource(api_v2.PackagesResource, "/api/v2/packages/")

    # Register all the view blueprints
    app.register_blueprint(ui.ui_blueprint)
    app.register_blueprint(api.api_blueprint)

    app.before_request(global_user)
    app.teardown_request(shutdown_session)
    app.register_error_handler(IntegrityError, integrity_error_handler)
    app.register_error_handler(AuthException, auth_error_handler)

    app.context_processor(inject_variable)

    # subscribe to signals
    user_logged_in.connect(when_user_log_in, app)

    if app.config.get("EMAIL_ERRORS"):
        # If email logging is configured, set up the anitya logger with an email
        # handler for any ERROR-level logs.
        _anitya_log = logging.getLogger("anitya")
        _anitya_log.addHandler(
            anitya.mail_logging.get_mail_handler(
                smtp_server=app.config.get("SMTP_SERVER"),
                mail_admin=app.config.get("ADMIN_EMAIL"),
            )
        )

    return app
def setup_sqreen_audit(app):
    from application.audit.auditor import record_login
    from flask_login import user_logged_in

    user_logged_in.connect(record_login, app)
Exemplo n.º 30
0
Arquivo: app.py Projeto: odra/anitya
def create(config=None):
    """
    Create and configure a Flask application object.

    Args:
        config (dict): The configuration to use when creating the application.
            If no configuration is provided, :data:`anitya.config.config` is
            used.

    Returns:
        flask.Flask: The configured Flask application.
    """
    app = flask.Flask(__name__)

    if config is None:
        config = anitya_config
    app.config.update(config)
    initialize_db(config)

    app.register_blueprint(social_auth)
    if len(social_models.UserSocialAuth.__table_args__) == 0:
        # This is a bit of a hack - this initialization call sets up the SQLAlchemy
        # models with our own models and multiple calls to this function will cause
        # SQLAlchemy to fail with sqlalchemy.exc.InvalidRequestError. Only calling it
        # when there are no table arguments should ensure we only call it one time.
        #
        # Be aware that altering the configuration values this function uses, namely
        # the SOCIAL_AUTH_USER_MODEL, after the first time ``create`` has been called
        # will *not* cause the new configuration to be used for subsequent calls to
        # ``create``.
        social_models.init_social(app, Session)

    login_manager = LoginManager()
    login_manager.user_loader(authentication.load_user_from_session)
    login_manager.request_loader(authentication.load_user_from_request)
    login_manager.login_view = '/login/'
    login_manager.init_app(app)

    # Register the v2 API resources
    app.api = Api(app)
    app.api.add_resource(api_v2.ProjectsResource, '/api/v2/projects/')
    app.api.add_resource(api_v2.PackagesResource, '/api/v2/packages/')

    # Register all the view blueprints
    app.register_blueprint(ui.ui_blueprint)
    app.register_blueprint(api.api_blueprint)

    app.before_request(global_user)
    app.teardown_request(shutdown_session)
    app.register_error_handler(IntegrityError, integrity_error_handler)
    app.register_error_handler(AuthException, auth_error_handler)

    app.context_processor(inject_variable)

    # subscribe to signals
    user_logged_in.connect(when_user_log_in, app)

    if app.config.get('EMAIL_ERRORS'):
        # If email logging is configured, set up the anitya logger with an email
        # handler for any ERROR-level logs.
        _anitya_log = logging.getLogger('anitya')
        _anitya_log.addHandler(anitya.mail_logging.get_mail_handler(
            smtp_server=app.config.get('SMTP_SERVER'),
            mail_admin=app.config.get('ADMIN_EMAIL')
        ))

    return app
Exemplo n.º 31
0
def setup_event_handlers():
    from flask_login import user_logged_in

    from app.event_handlers import on_user_logged_in

    user_logged_in.connect(on_user_logged_in)
Exemplo n.º 32
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.

        :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)

        # Create sessionstore
        if sessionstore is None:
            if app.testing and \
                    os.environ.get('CI', 'false') == 'false':
                from simplekv.memory import DictStore

                sessionstore = DictStore()
            else:
                import redis
                from simplekv.memory.redisstore import RedisStore

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

        user_logged_in.connect(login_listener, 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)
        self.kvsession_extension = KVSessionExtension(sessionstore, app)

        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
            )

        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__)

        app.extensions['invenio-accounts'] = self
Exemplo n.º 33
0
# Logging
#
def log_session_start(app, user):
    session = LoginSession.new()
    db.session.add(session)
    db.session.commit()


def log_session_end(app, user):
    session = LoginSession.query.get_active_for(user)
    if session:
        session.ended_at = datetime.utcnow()
        db.session.commit()


user_logged_in.connect(log_session_start)
user_logged_out.connect(log_session_end)


# login redirect utilities
#  from http://flask.pocoo.org/snippets/62/
def is_safe_url(target):
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.url_root, target))
    return test_url.scheme in ('http', 'https') and \
        ref_url.netloc == test_url.netloc


def check_for_redirect(target):
    target = urljoin(request.url_root, target)
    url = urlparse(target)
Exemplo n.º 34
0
 def setUp(self):
     self.clean_db()
     self.current_user = None
     user_logged_in.connect(self._signal_login)
     user_logged_out.connect(self._signal_logout)
Exemplo n.º 35
0
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})
    app.config['SQLALCHEMY_ECHO'] = 'FARADAY_LOG_QUERY' in os.environ
    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=Role)

    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

    register_extensions(app)
    load_settings()

    return app
Exemplo n.º 36
0
def connect(app):
    # connect sender and subscriber here.
    # In case sender is app, call this function after app is created.
    user_logged_in.connect(record_user_login_time, sender=app)
Exemplo n.º 37
0
        session['lang'] = reqlang
    else:
        reqlang = session.get('lang')
        if not reqlang:
            if current_user.is_authenticated:
                reqlang = current_user.language
                session['lang'] = reqlang
    return reqlang


from flask_login import user_logged_in, user_logged_out
from models import syslog


def log_user_logged_in(sender, user, **extra):
    syslog.log(type="user logged in")
    session['lang'] = current_user.language


def log_user_logged_out(sender, user, **extra):
    syslog.log(type="user logged out")


syslog.syslog_init()
syslog.log(type="application initialized")

user_logged_in.connect(log_user_logged_in, shareds.app)
user_logged_out.connect(log_user_logged_out, shareds.app)

import setups
Exemplo n.º 38
0
def init_signals(app):
    user_logged_in.connect(on_user_logged_in, app)
    user_logged_out.connect(on_user_logged_out, app)
    voucher_generated.connect(on_voucher_generated, app)
    voucher_logged_in.connect(on_voucher_logged_in, app)
Exemplo n.º 39
0
db = SQLAlchemy(app)
app.csrf = CSRFProtect(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'home.signin'

babel = Babel(app)


@babel.localeselector
def get_locale():
    return request.accept_languages.best_match(app.config['LANGUAGES'].keys())


def log_login(app, user):
    '''update the last login time of the user'''
    user.last_login_time = datetime.utcnow()
    db.session.commit()


user_logged_in.connect(log_login)
user_loaded_from_cookie.connect(log_login)

from app.views import *
app.register_blueprint(home, url_prefix='')
app.register_blueprint(course, url_prefix='/course')
app.register_blueprint(review, url_prefix='/review')
app.register_blueprint(api, url_prefix='/api')
app.register_blueprint(user, url_prefix='/user')
app.register_blueprint(teacher, url_prefix='/teacher')
Exemplo n.º 40
0
 def init_app(self, app, *args, **kwargs):
   super(Sentry, self).init_app(app, *args, **kwargs)
   user_logged_in.connect(self._on_user_logged_in, sender=app)
Exemplo n.º 41
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.

        :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)

        # Create sessionstore
        if sessionstore is None:
            if app.testing and \
                    os.environ.get('CI', 'false') == 'false':
                from simplekv.memory import DictStore

                sessionstore = DictStore()
            else:
                import redis
                from simplekv.memory.redisstore import RedisStore

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

        user_logged_in.connect(login_listener, 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)
        self.kvsession_extension = KVSessionExtension(sessionstore, app)

        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
            )

        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__)

        app.extensions['invenio-accounts'] = self