def create_app(armazenamento=None):
    app = Flask(__name__, static_folder=static_folder)
    app.config.update({
        'SECRET_KEY': 'MySecretIsMyPasswordBlaBla',
        'TESTING': True,
        'DEBUG': True,
        'SQLALCHEMY_DATABASE_URI': openid_db,
        'OIDC_CLIENT_SECRETS': 'client_secrets.json',
        'OIDC_ID_TOKEN_COOKIE_SECURE': False,
        'OIDC_REQUIRE_VERIFIED_EMAIL': False,
        'OIDC_OPENID_REALM': uri + '/oidc_callback'
    })

    CORS(app)
    Compress(app)
    print("app criado.")

    from db import create_db
    db = create_db()
    db.init_app(app)

    oidc = OpenIDConnect(app, armazenamento)
    add_routes(app, oidc)

    return app
Beispiel #2
0
def create_app(config_obj=None):
    app = Flask(__name__)
    if config_obj:
        app.config.from_object(config_obj)
    else:
        load_config(app)
    if app.config[
            'PRODUCTION'] and app.secret_key == 'replace-me-with-something-random':
        raise Warning(
            "You need to change the app.secret_key value for production")

    # register error handlers
    for code in default_exceptions.iterkeys():
        app.register_error_handler(code, json_error)
    app.register_error_handler(ConnectionError, json_error)
    app.register_error_handler(Timeout, json_error)

    populate_db_config(app)
    if app.config['AUTH_METHOD'] == 'OIDC':
        app.oidc = OpenIDConnect(app)
    # initialize db
    db.init_app(app)
    # initialize db migrations
    migrations_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                  'migrations')
    Migrate(app, db, directory=migrations_dir)
    # initialize logging
    init_logging(app)
    # register blueprints
    app.register_blueprint(api_v1, url_prefix="/api/v1.0")
    app.add_url_rule('/healthcheck', view_func=healthcheck)
    register_event_handlers(app)
    return app
Beispiel #3
0
def create_app(config, oidc_overrides=None):
    global oidc

    app = Flask(__name__)
    app.config.update(config)
    if oidc_overrides is None:
        oidc_overrides = {}
    oidc = OpenIDConnect(app, **oidc_overrides)
    app.route('/')(oidc.check(index))
    app.route('/at')(oidc.check(get_at))
    app.route('/rt')(oidc.check(get_rt))
    # Check standalone usage
    rendered = oidc.accept_token(True, ['openid'])(api)
    app.route('/api', methods=['GET', 'POST'])(rendered)

    # Check combination with an external API renderer like Flask-RESTful
    unrendered = oidc.accept_token(True, ['openid'],
                                   render_errors=False)(raw_api)

    def externally_rendered_api(*args, **kwds):
        inner_response = unrendered(*args, **kwds)
        if isinstance(inner_response, tuple):
            raw_response, response_code, headers = inner_response
            rendered_response = json.dumps(
                raw_response), response_code, headers
        else:
            rendered_response = json.dumps(inner_response)
        return rendered_response

    app.route('/external_api', methods=['GET',
                                        'POST'])(externally_rendered_api)
    return app
Beispiel #4
0
def create_app(config, oidc_overrides=None):
    app = Flask(__name__)
    app.config.update(config)
    if oidc_overrides is None:
        oidc_overrides = {}
    oidc = OpenIDConnect(app, **oidc_overrides)
    app.route('/')(oidc.check(index))
    return app
Beispiel #5
0
def configure_openid(app):
    """Set up OpenID, OpenIDConnect, and the module's Flask app reference"""
    global APP
    app.oid = OpenID(app)
    try:
        app.oidc = OpenIDConnect(app, credentials_store=flask.session)
    except Exception as exc:
        # Handle running with only anonymous API access enabled
        app.logger.debug(str(exc))
        app.oidc = None
    app.route("/oidc_callback")(register_oidc_client)
    APP = app
Beispiel #6
0
    def __init__(self,
                 connectors,
                 name=None,
                 server=None,
                 app_url=None,
                 app_client_id=None,
                 app_client_secret=None,
                 oidc_client_secrets_path=None,
                 message_url_pattern='api/messages',
                 url_base_pathname='/',
                 csrf_protect=True,
                 formatter=None):
        self.connectors = connectors
        self.formatter = formatter
        self.session = requests.Session()
        print(self.session)
        self.app_client_id = app_client_id or os.environ.get('APP_ID', '')
        self.app_client_secret = app_client_secret or \
            os.environ.get('APP_PASSWORD', '')
        self.auth_str = None

        # allow users to supply their own flask server
        if server is not None:
            self.server = server
        else:
            if name is None:
                name = 'botframework'
            self.server = Flask(name)
            self.server.config['DEBUG'] = True

        self.oidc_client_secrets_path = oidc_client_secrets_path
        self.server.config.update(self._config())
        self.oidc = OpenIDConnect(self.server)

        self.message_url_pattern = message_url_pattern
        self.url_base_pathname = url_base_pathname
        print('Self Object: ')
        print(self)
        # list of dependencies
        self.callback_map = {}

        # gzip
        Compress(self.server)

        # urls
        # This is kind of funky but should work
        view_func = self.oidc.accept_token()(self.handle_messages)

        self.server.add_url_rule('{}{}'.format(url_base_pathname,
                                               message_url_pattern),
                                 view_func=view_func,
                                 methods=['post'])
Beispiel #7
0
def get_oidc():
    """
    Connect to okta
    """
    if 'oidc' not in g:
        print('okta: get_oidc call')
        g.oidc = OpenIDConnect(current_app)
        g.okta_client = UsersClient(
            "https://dev-833144.okta.com",
            "00xJ6vTQkI8LzIQcPXf7Ehw75GrdAVDdqA2tvQFxFx")
        # fixing global oidc problem for decorator in rooms
        oidc = g.oidc
    return g.oidc
Beispiel #8
0
def create_server():
    """Create the main Flask server of the dashboard, including
    authentication
    """
    server = Flask(__name__)

    config_update = config_prepare(server.logger)

    server.config.update(config_update)

    oidc = OpenIDConnect(server)

    @server.route("/")
    def index():
        if oidc.user_loggedin:
            return redirect(url_for("pages"))
        else:
            try:
                return render_template("index.html")
            except TemplateNotFound:
                abort(404)

    @server.route("/login")
    @oidc.require_login
    def login():
        return redirect(url_for("pages"))

    @server.route("/logout", methods=["POST"])
    def logout():
        oidc.logout()
        return redirect(url_for("index"))

    @server.route("/pages")
    @oidc.require_login
    def pages():
        return redirect("/pages/summary", 302)

    def _oidc_error(message="Not Authorized", code=None):
        try:
            return render_template("index.html", alert=message)
        except TemplateNotFound:
            abort(404)

    oidc._oidc_error = _oidc_error

    @server.errorhandler(404)
    def page_not_found(e):
        # note that we set the 404 status explicitly
        return render_template("404.html"), 404

    return server, oidc
def create_app():
    application = Flask(__name__)
    ma = Marshmallow(application)

    # Pull from config file
    application.config.from_object('config.Config')

    oidc = OpenIDConnect(application)

    # Initailize database
    db.init_app(application)  #<- This will get called in our models.py file
    migrate.init_app(application, db)  #<- Migration directory

    @application.route("/")
    def home():
        if oidc.user_loggedin:
            return "Hello autenticated user: %s" % oidc.user_getfield(
                'preferred_username')
        else:
            return 'This is the backend api to How R U. Please authenticate to access stuff: <a href="/login">Log in</a>'

    @application.route('/login')
    @oidc.require_login
    def login():
        return 'Welcome %s' % oidc.user_getfield('email')

    @application.route("/api/mydata")
    @oidc.accept_token(True, scopes_required=['openid'])
    def messages():
        #Grab sql records that match uid in oidc token info and badly mash into response :/
        conn = pymysql.connect(host,
                               user=user,
                               port=port,
                               passwd=password,
                               db=dbname)
        c = conn.cursor()
        c.execute('select * from testDB where user_id = "%s";' %
                  g.oidc_token_info['uid'])
        rows = c.fetchall()
        response = {
            'subject': '%s' % g.oidc_token_info['sub'],
            'unformatted data': '%s' % " ".join(map(str, rows))
        }

        return json.dumps(response)

    if __name__ == 'app':
        application.run(host="0.0.0.0", port=80, debug=True)
    return (application)
Beispiel #10
0
def create_app():
    global app, oidc, _logger
    app = Flask(__name__)

    # Load the configurations based on the 'FLASK_ENV' environment variable
    app.config.from_object(config)

    # setup session database
    db = SQLAlchemy(app)
    app.config["SESSION_SQLALCHEMY_TABLE"] = 'sessions'
    app.config["SESSION_SQLALCHEMY"] = db
    session = Session(app)
    session.app.session_interface.db.create_all()
    # Init the OpenIDConnect application instance
    # oidc.init_app(app)
    oidc = OpenIDConnect(app, SessionCredentialStore())

    # Initialize logger
    _logger = configure_logger(app)
    # Init the OpenIDConnect application instance
    oidc.init_app(app)

    # Registers the API URLs
    # Below import here is to prevent the circular imports
    from backend.apis import api as api_blueprint
    api_prefix = '/{}/api'.format(app.config.get('SERVICE_SLUG'))
    app.register_blueprint(api_blueprint, url_prefix=api_prefix)

    # Registers the Views URLs
    # This import here is to prevent the circular imports
    from backend.views import view as view_blueprint
    app.register_blueprint(view_blueprint)

    # Registers our swagger UI blueprint
    swagger_docs_prefix = '{}/{}'.format(api_prefix,
                                         app.config.get('SWAGGER_DOCS'))
    swagger_spec_prefix = '{}/{}'.format(api_prefix,
                                         app.config.get('SWAGGER_SPEC'))
    swaggerui_blueprint = get_swaggerui_blueprint(
        swagger_docs_prefix,
        swagger_spec_prefix,
        config={'app_name': app.config.get('SWAGGER_NAME')},
    )
    app.register_blueprint(swaggerui_blueprint, url_prefix=swagger_docs_prefix)

    return app
def create_app():
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(SECRET_KEY=os.urandom(16))

    from raspberry_monitor import config
    conf = config.Config()
    app.config.from_object(conf)

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    global oidc
    oidc = OpenIDConnect(app)
    from raspberry_monitor.endpoints import api
    api.init_app(app)
    configure_logging()

    if conf.BASIC_AUTH_FORCE:
        BasicAuth(app)
    return app
Beispiel #12
0
    def __init__(self, *args, **kwargs):
        super(FlaskOIDC, self).__init__(*args, **kwargs)

        # Setup Session Database
        _sql_db = SQLAlchemy(self)
        self.config["SESSION_SQLALCHEMY"] = _sql_db

        # Setup Session Store, that will hold the session information
        # in database. OIDC by default keep the sessions in memory
        _session = Session(self)
        _session.app.session_interface.db.create_all()

        # Initiate OpenIDConnect using the SQLAlchemy backed session store
        _oidc = OpenIDConnect(self, SessionCredentialStore())
        self.oidc = _oidc

        # Register the before request function that will make sure each
        # request is authenticated before processing
        self.before_request(self._before_request)

        @self.route('/login')
        def login():
            return redirect('/')

        @self.route('/logout')
        def logout():
            """
            The logout function that logs user out from Keycloak.
            :return: Redirects to the Keycloak login page
            """
            _oidc.logout()
            redirect_url = request.url_root.strip('/')
            keycloak_issuer = _oidc.client_secrets.get('issuer')
            keycloak_logout_url = '{}/protocol/openid-connect/logout'. \
                format(keycloak_issuer)

            return redirect('{}?redirect_uri={}'.format(
                keycloak_logout_url, redirect_url))
Beispiel #13
0
    def init_app(self, app):
        from . import views

        self.app = app

        app.config.setdefault('AUTH_METHOD', 'local')
        app.config.setdefault('AUTH_SUPERADMINS', ['admin'])
        app.config.setdefault(
            'AUTH_ROLE_GROUPS', {
                'admin': ['webmasters'],
                'content': ['webmasters'],
                'business': ['business'],
                'library': ['librarians'],
                'missioncontrol': ['missioncontrol'],
            })

        self.login_manager = LoginManager()
        self.login_manager.login_view = "auth.login"
        self.login_manager.init_app(app)
        self.login_manager.user_loader(load_user)

        if app.config['AUTH_METHOD'] == 'oidc':
            import flask_oidc
            flask_oidc.logger = app.logger

            with app.app_context():
                app.config.setdefault('OIDC_SCOPES',
                                      ['openid', 'profile', 'email'])
                app.config.update({
                    'OIDC_RESOURCE_SERVER_ONLY': True,
                    'OIDC_RESOURCE_CHECK_AUD': True,
                })

                from .views import oidc_callback
                app.before_request(self._before_request)
                bp.route('/oidc_callback')(oidc_callback)

            self.oidc = OpenIDConnect(app)
Beispiel #14
0
    def setUp(self):
        """Set a basic test environment.

        This simply starts recording a VCR on start-up and stops on tearDown.
        """
        mock_oidc = mock.patch(
            'anitya.authentication.oidc',
            OpenIDConnect(credentials_store=flask.session),
        )
        mock_oidc.start()
        self.addCleanup(mock_oidc.stop)
        mock_oid = mock.patch('anitya.authentication.oid', OpenID())
        mock_oid.start()
        self.addCleanup(mock_oid.stop)

        self.flask_app = app.create(config.config)

        cwd = os.path.dirname(os.path.realpath(__file__))
        my_vcr = vcr.VCR(
            cassette_library_dir=os.path.join(cwd, 'request-data/'), record_mode='once')
        self.vcr = my_vcr.use_cassette(self.id())
        self.vcr.__enter__()
        self.addCleanup(self.vcr.__exit__, None, None, None)
Beispiel #15
0
    def _init_auth(self) -> AuthenticationHandler:
        """Initalizes the AuthenticationHandler
        
        Returns:
            AuthenticationHandler -- The instantiated AuthenticationHandler object
        """

        oidc_config = {
            "SECRET_KEY":
            environ.get("SECRET_KEY"),
            "OIDC_CLIENT_SECRETS":
            environ.get("OIDC_CLIENT_SECRETS"),
            "OIDC_OPENID_REALM":
            environ.get("OIDC_OPENID_REALM"),
            'OIDC_ID_TOKEN_COOKIE_SECURE':
            environ.get("OIDC_ID_TOKEN_COOKIE_SECURE") == "true"
        }

        self._service.config.update(oidc_config)

        oicd = OpenIDConnect()
        oicd.init_app(self._service)

        return AuthenticationHandler(self._res, self._rpc, oicd)
Beispiel #16
0
from os import environ

from flask import Blueprint, redirect, url_for
from flask_oidc import OpenIDConnect
from okta import UsersClient


bp = Blueprint("auth", __name__, url_prefix="/")
oidc = OpenIDConnect()
okta_client = UsersClient("https://dev-407714.okta.com/", "token")


@bp.route("/login")
@oidc.require_login
def login():
    """
    Force the user to login, then redirect them to the dashboard.
    """
    return redirect(url_for("blog.dashboard"))


@bp.route("/logout")
def logout():
    """
    Log the user out of their account.
    """
    oidc.logout()
    return redirect(url_for("blog.index"))
Beispiel #17
0
from boxsdk import JWTAuth
import requests
import config
import json

app = Flask(__name__)
app.config.update({
    'SECRET_KEY': config.okta_client_secret,
    'OIDC_CLIENT_SECRETS': './client_secrets.json',
    'OIDC_DEBUG': True,
    'OIDC_ID_TOKEN_COOKIE_SECURE': False,
    'OIDC_SCOPES': ["openid", "profile"],
    'OIDC_CALLBACK_ROUTE': config.okta_callback_route
})

oidc = OpenIDConnect(app)
okta_client = UsersClient(config.okta_org_url, config.okta_auth_token)


# Fetch Okta user record if logged in
@app.before_request
def before_request():
    if oidc.user_loggedin:
        g.user = okta_client.get_user(oidc.user_getfield('sub'))
    else:
        g.user = None


# Main application route
@app.route('/')
def start():
Beispiel #18
0
 def __init__(self, appbuilder):
     super(OIDCSecurityManagerMixin, self).__init__(appbuilder)
     if self.auth_type == AUTH_OID:
         self.oid = OpenIDConnect(self.appbuilder.get_app)
         self.authoidview = AuthOIDCView
Beispiel #19
0
def init_oidc():
    oidc = OpenIDConnect(current_app)
    return oidc
Beispiel #20
0
def create_app(app_name=None):
    # Configuration settings
    import config
    if not app_name:
        app_name = config.APP_NAME

    # Check if app is created for CLI operations or Web
    cli_mode = False
    if app_name.endswith('-cli'):
        cli_mode = True

    # Only enable password related functionality in server mode.
    if config.SERVER_MODE is True:
        # Some times we need to access these config params where application
        # context is not available (we can't use current_app.config in those
        # cases even with current_app.app_context())
        # So update these params in config itself.
        # And also these updated config values will picked up by application
        # since we are updating config before the application instance is
        # created.

        config.SECURITY_RECOVERABLE = True
        config.SECURITY_CHANGEABLE = True
        # Now we'll open change password page in alertify dialog
        # we don't want it to redirect to main page after password
        # change operation so we will open the same password change page again.
        config.SECURITY_POST_CHANGE_VIEW = 'browser.change_password'
    """Create the Flask application, startup logging and dynamically load
    additional modules (blueprints) that are found in this directory."""
    app = PgAdmin(__name__, static_url_path='/static')
    # Removes unwanted whitespace from render_template function
    app.jinja_env.trim_blocks = True
    app.config.from_object(config)
    app.config.update(dict(PROPAGATE_EXCEPTIONS=True))

    ##########################################################################
    # Setup logging and log the application startup
    ##########################################################################

    # We won't care about errors in the logging system, we are more
    # interested in application errors.
    logging.raiseExceptions = False

    # Add SQL level logging, and set the base logging level
    logging.addLevelName(25, 'SQL')
    app.logger.setLevel(logging.DEBUG)
    app.logger.handlers = []

    # We also need to update the handler on the webserver in order to see
    # request. Setting the level prevents werkzeug from setting up it's own
    # stream handler thus ensuring all the logging goes through the pgAdmin
    # logger.
    logger = logging.getLogger('werkzeug')
    logger.setLevel(config.CONSOLE_LOG_LEVEL)

    # Set SQLITE_PATH to TEST_SQLITE_PATH while running test cases
    if ('PGADMIN_TESTING_MODE' in os.environ
            and os.environ['PGADMIN_TESTING_MODE'] == '1'):
        config.SQLITE_PATH = config.TEST_SQLITE_PATH
        config.MASTER_PASSWORD_REQUIRED = False
        config.UPGRADE_CHECK_ENABLED = False

    if not cli_mode:
        # Ensure the various working directories exist
        from pgadmin.setup import create_app_data_directory
        create_app_data_directory(config)

        # File logging
        fh = logging.FileHandler(config.LOG_FILE, encoding='utf-8')
        fh.setLevel(config.FILE_LOG_LEVEL)
        fh.setFormatter(logging.Formatter(config.FILE_LOG_FORMAT))
        app.logger.addHandler(fh)
        logger.addHandler(fh)

    # Console logging
    ch = logging.StreamHandler()
    ch.setLevel(config.CONSOLE_LOG_LEVEL)
    ch.setFormatter(logging.Formatter(config.CONSOLE_LOG_FORMAT))
    app.logger.addHandler(ch)
    logger.addHandler(ch)

    # Log the startup
    app.logger.info('########################################################')
    app.logger.info('Starting %s v%s...', config.APP_NAME, config.APP_VERSION)
    app.logger.info('########################################################')
    app.logger.debug("Python syspath: %s", sys.path)

    ##########################################################################
    # Setup i18n
    ##########################################################################

    # Initialise i18n
    babel = Babel(app)

    app.logger.debug('Available translations: %s' % babel.list_translations())

    @babel.localeselector
    def get_locale():
        """Get the language for the user."""
        language = 'en'
        if config.SERVER_MODE is False:
            # Get the user language preference from the miscellaneous module
            if current_user.is_authenticated:
                user_id = current_user.id
            else:
                user = user_datastore.get_user(config.DESKTOP_USER)
                if user is not None:
                    user_id = user.id
            user_language = Preferences.raw_value('misc', 'user_language',
                                                  'user_language', user_id)
            if user_language is not None:
                language = user_language
        else:
            # If language is available in get request then return the same
            # otherwise check the session or cookie
            data = request.form
            if 'language' in data:
                language = data['language'] or language
                setattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(session, 'PGADMIN_LANGUAGE'):
                language = getattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(request.cookies, 'PGADMIN_LANGUAGE'):
                language = getattr(request.cookies, 'PGADMIN_LANGUAGE',
                                   language)

        return language

    ##########################################################################
    # Setup authentication
    ##########################################################################

    app.config['SQLALCHEMY_DATABASE_URI'] = u'sqlite:///{0}?timeout={1}' \
        .format(config.SQLITE_PATH.replace(u'\\', u'/'),
                getattr(config, 'SQLITE_TIMEOUT', 500)
                )

    # Create database connection object and mailer
    db.init_app(app)

    ##########################################################################
    # Upgrade the schema (if required)
    ##########################################################################
    with app.app_context():
        # Run migration for the first time i.e. create database
        from config import SQLITE_PATH
        from pgadmin.setup import db_upgrade

        # If version not available, user must have aborted. Tables are not
        # created and so its an empty db
        if not os.path.exists(SQLITE_PATH) or get_version() == -1:
            # If running in cli mode then don't try to upgrade, just raise
            # the exception
            if not cli_mode:
                db_upgrade(app)
            else:
                if not os.path.exists(SQLITE_PATH):
                    raise FileNotFoundError('SQLite database file "' +
                                            SQLITE_PATH + '" does not exists.')
                raise Exception('Specified SQLite database file is not valid.')
        else:
            schema_version = get_version()

            # Run migration if current schema version is greater than the
            # schema version stored in version table
            if CURRENT_SCHEMA_VERSION >= schema_version:
                db_upgrade(app)

            # Update schema version to the latest
            if CURRENT_SCHEMA_VERSION > schema_version:
                set_version(CURRENT_SCHEMA_VERSION)
                db.session.commit()

        if os.name != 'nt':
            os.chmod(config.SQLITE_PATH, 0o600)

    Mail(app)

    # Don't bother paths when running in cli mode
    if not cli_mode:
        import pgadmin.utils.paths as paths
        paths.init_app(app)

    # Setup Flask-Security
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(None, user_datastore)

    ##########################################################################
    # Setup security
    ##########################################################################
    with app.app_context():
        config.CSRF_SESSION_KEY = Keys.query.filter_by(
            name='CSRF_SESSION_KEY').first().value
        config.SECRET_KEY = Keys.query.filter_by(
            name='SECRET_KEY').first().value
        config.SECURITY_PASSWORD_SALT = Keys.query.filter_by(
            name='SECURITY_PASSWORD_SALT').first().value

    # Update the app.config with proper security keyes for signing CSRF data,
    # signing cookies, and the SALT for hashing the passwords.
    app.config.update(
        dict({
            'CSRF_SESSION_KEY': config.CSRF_SESSION_KEY,
            'SECRET_KEY': config.SECRET_KEY,
            'SECURITY_PASSWORD_SALT': config.SECURITY_PASSWORD_SALT,
            'SESSION_COOKIE_DOMAIN': config.SESSION_COOKIE_DOMAIN,
            # CSRF Token expiration till session expires
            'WTF_CSRF_TIME_LIMIT': getattr(config, 'CSRF_TIME_LIMIT', None),
            'WTF_CSRF_METHODS': ['GET', 'POST', 'PUT', 'DELETE'],
        }))

    security.init_app(app, user_datastore)

    from flask_oidc import OpenIDConnect
    app.login_manager.oidc = OpenIDConnect(app)

    # register custom unauthorised handler.
    app.login_manager.unauthorized_handler(pga_unauthorised)

    # Set the permanent session lifetime to the specified value in config file.
    app.permanent_session_lifetime = timedelta(
        days=config.SESSION_EXPIRATION_TIME)

    if not cli_mode:
        app.session_interface = create_session_interface(
            app, config.SESSION_SKIP_PATHS)

    # Make the Session more secure against XSS & CSRF when running in web mode
    if config.SERVER_MODE and config.ENHANCED_COOKIE_PROTECTION:
        paranoid = Paranoid(app)
        paranoid.redirect_view = 'browser.index'

    ##########################################################################
    # Load all available server drivers
    ##########################################################################
    driver.init_app(app)
    authenticate.init_app(app)

    ##########################################################################
    # Register language to the preferences after login
    ##########################################################################
    @user_logged_in.connect_via(app)
    def register_language(sender, user):
        # After logged in, set the language in the preferences if we get from
        # the login page
        data = request.form
        if 'language' in data:
            language = data['language']

            # Set the user language preference
            misc_preference = Preferences.module('misc')
            user_languages = misc_preference.preference('user_language')

            if user_languages and language:
                language = user_languages.set(language)

    ##########################################################################
    # Register any local servers we can discover
    ##########################################################################
    @user_logged_in.connect_via(app)
    def on_user_logged_in(sender, user):
        # Keep hold of the user ID
        user_id = user.id

        # Get the first server group for the user
        servergroup_id = 1
        servergroups = ServerGroup.query.filter_by(
            user_id=user_id).order_by("id")

        if servergroups.count() > 0:
            servergroup = servergroups.first()
            servergroup_id = servergroup.id
        '''Add a server to the config database'''
        def add_server(user_id, servergroup_id, name, superuser, port,
                       discovery_id, comment):
            # Create a server object if needed, and store it.
            servers = Server.query.filter_by(
                user_id=user_id, discovery_id=svr_discovery_id).order_by("id")

            if servers.count() > 0:
                return

            svr = Server(user_id=user_id,
                         servergroup_id=servergroup_id,
                         name=name,
                         host='localhost',
                         port=port,
                         maintenance_db='postgres',
                         username=superuser,
                         ssl_mode='prefer',
                         comment=svr_comment,
                         discovery_id=discovery_id)

            db.session.add(svr)
            db.session.commit()

        # Figure out what servers are present
        if winreg is not None:
            arch_keys = set()
            proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()

            try:
                proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()
            except Exception:
                proc_arch64 = None

            if proc_arch == 'x86' and not proc_arch64:
                arch_keys.add(0)
            elif proc_arch == 'x86' or proc_arch == 'amd64':
                arch_keys.add(winreg.KEY_WOW64_32KEY)
                arch_keys.add(winreg.KEY_WOW64_64KEY)

            for arch_key in arch_keys:
                for server_type in ('PostgreSQL', 'EnterpriseDB'):
                    try:
                        root_key = winreg.OpenKey(
                            winreg.HKEY_LOCAL_MACHINE,
                            "SOFTWARE\\" + server_type + "\\Services", 0,
                            winreg.KEY_READ | arch_key)
                        for i in xrange(0, winreg.QueryInfoKey(root_key)[0]):
                            inst_id = winreg.EnumKey(root_key, i)
                            inst_key = winreg.OpenKey(root_key, inst_id)

                            svr_name = winreg.QueryValueEx(
                                inst_key, 'Display Name')[0]
                            svr_superuser = winreg.QueryValueEx(
                                inst_key, 'Database Superuser')[0]
                            svr_port = winreg.QueryValueEx(inst_key, 'Port')[0]
                            svr_discovery_id = inst_id
                            svr_comment = gettext(
                                "Auto-detected {0} installation with the data "
                                "directory at {1}").format(
                                    winreg.QueryValueEx(
                                        inst_key, 'Display Name')[0],
                                    winreg.QueryValueEx(
                                        inst_key, 'Data Directory')[0])

                            add_server(user_id, servergroup_id, svr_name,
                                       svr_superuser, svr_port,
                                       svr_discovery_id, svr_comment)

                            inst_key.Close()
                    except Exception:
                        pass
        else:
            # We use the postgres-winreg.ini file on non-Windows
            from configparser import ConfigParser

            registry = ConfigParser()

        try:
            registry.read('/etc/postgres-reg.ini')
            sections = registry.sections()

            # Loop the sections, and get the data from any that are PG or PPAS
            for section in sections:
                if (section.startswith('PostgreSQL/')
                        or section.startswith('EnterpriseDB/')):
                    svr_name = registry.get(section, 'Description')
                    svr_superuser = registry.get(section, 'Superuser')

                    # getint function throws exception if value is blank.
                    # Ex: Port=
                    # In such case we should handle the exception and continue
                    # to read the next section of the config file.
                    try:
                        svr_port = registry.getint(section, 'Port')
                    except ValueError:
                        continue

                    svr_discovery_id = section
                    description = registry.get(section, 'Description')
                    data_directory = registry.get(section, 'DataDirectory')
                    if hasattr(str, 'decode'):
                        description = description.decode('utf-8')
                        data_directory = data_directory.decode('utf-8')
                    svr_comment = gettext(
                        u"Auto-detected {0} installation "
                        u"with the data directory at {1}").format(
                            description, data_directory)
                    add_server(user_id, servergroup_id, svr_name,
                               svr_superuser, svr_port, svr_discovery_id,
                               svr_comment)

        except Exception:
            pass

    @user_logged_in.connect_via(app)
    @user_logged_out.connect_via(app)
    def force_session_write(app, user):
        session.force_write = True

    @user_logged_in.connect_via(app)
    def store_crypt_key(app, user):
        # in desktop mode, master password is used to encrypt/decrypt
        # and is stored in the keyManager memory
        if config.SERVER_MODE and 'password' in request.form:
            current_app.keyManager.set(request.form['password'])

    @user_logged_out.connect_via(app)
    def current_user_cleanup(app, user):
        from config import PG_DEFAULT_DRIVER
        from pgadmin.utils.driver import get_driver
        from flask import current_app

        # remove key
        current_app.keyManager.reset()

        for mdl in current_app.logout_hooks:
            try:
                mdl.on_logout(user)
            except Exception as e:
                current_app.logger.exception(e)

        _driver = get_driver(PG_DEFAULT_DRIVER)
        _driver.gc_own()

    ##########################################################################
    # Load plugin modules
    ##########################################################################
    for module in app.find_submodules('pgadmin'):
        app.logger.info('Registering blueprint module: %s' % module)
        app.register_blueprint(module)
        app.register_logout_hook(module)

    ##########################################################################
    # Handle the desktop login
    ##########################################################################

    @app.before_request
    def before_request():
        """Login the default user if running in desktop mode"""

        # Check the auth key is valid, if it's set, and we're not in server
        # mode, and it's not a help file request.
        if not config.SERVER_MODE and app.PGADMIN_INT_KEY != '' and (
            ('key' not in request.args
             or request.args['key'] != app.PGADMIN_INT_KEY) and
                request.cookies.get('PGADMIN_INT_KEY') != app.PGADMIN_INT_KEY
                and request.endpoint != 'help.static'):
            abort(401)

        if not config.SERVER_MODE and not current_user.is_authenticated:
            user = user_datastore.get_user(config.DESKTOP_USER)
            # Throw an error if we failed to find the desktop user, to give
            # the sysadmin a hint. We'll continue to try to login anyway as
            # that'll through a nice 500 error for us.
            if user is None:
                app.logger.error(
                    'The desktop user %s was not found in the configuration '
                    'database.' % config.DESKTOP_USER)
                abort(401)
            login_user(user)

        # if the server is restarted the in memory key will be lost
        # but the user session may still be active. Logout the user
        # to get the key again when login
        if config.SERVER_MODE and current_user.is_authenticated and \
            (current_app.keyManager.get() is None and not hasattr(current_app.login_manager, 'oidc')) and \
                request.endpoint not in ('security.login', 'security.logout'):
            logout_user()

    @app.after_request
    def after_request(response):
        if 'key' in request.args:
            domain = dict()
            if config.COOKIE_DEFAULT_DOMAIN and \
                    config.COOKIE_DEFAULT_DOMAIN != 'localhost':
                domain['domain'] = config.COOKIE_DEFAULT_DOMAIN
            response.set_cookie('PGADMIN_INT_KEY',
                                value=request.args['key'],
                                path=config.COOKIE_DEFAULT_PATH,
                                **domain)

        # X-Frame-Options for security
        if config.X_FRAME_OPTIONS != "" and \
                config.X_FRAME_OPTIONS.lower() != "deny":
            response.headers["X-Frame-Options"] = config.X_FRAME_OPTIONS

        return response

    ##########################################################################
    # Cache busting
    ##########################################################################

    # Version number to be added to all static file url requests
    # This is used by url_for function when generating urls
    # This will solve caching issues when application is upgrading
    # This is called - Cache Busting
    @app.url_defaults
    def add_internal_version(endpoint, values):
        extensions = config.APP_VERSION_EXTN

        # Add the internal version only if it is set
        if config.APP_VERSION_PARAM is not None and \
           config.APP_VERSION_PARAM != '':
            # If there is a filename, add the version
            if 'filename' in values \
               and values['filename'].endswith(extensions):
                values[config.APP_VERSION_PARAM] = config.APP_VERSION_INT
            else:
                # Sometimes there may be direct endpoint for some files
                # There will be only one rule for such endpoints
                urls = [url for url in app.url_map.iter_rules(endpoint)]
                if len(urls) == 1 and urls[0].rule.endswith(extensions):
                    values[config.APP_VERSION_PARAM] = \
                        config.APP_VERSION_INT

    # Strip away internal version param before sending further to app as it was
    # required for cache busting only
    @app.url_value_preprocessor
    def strip_version_number(endpoint, values):
        if values and config.APP_VERSION_PARAM in values:
            values.pop(config.APP_VERSION_PARAM)

    ##########################################################################
    # Minify output. Not required in desktop mode
    ##########################################################################
    if not config.DEBUG and config.SERVER_MODE:
        from flask_compress import Compress
        Compress(app)

    from pgadmin.misc.themes import Themes
    Themes(app)

    @app.context_processor
    def inject_blueprint():
        """
        Inject a reference to the current blueprint, if any.
        """

        return {
            'current_app': current_app,
            'current_blueprint': current_blueprint,
        }

    @app.errorhandler(Exception)
    def all_exception_handler(e):
        current_app.logger.error(e, exc_info=True)
        return internal_server_error(errormsg=str(e))

    # Exclude HTTPexception from above handler (all_exception_handler)
    # HTTPException are user defined exceptions and those should be returned
    # as is
    @app.errorhandler(HTTPException)
    def http_exception_handler(e):
        current_app.logger.error(e, exc_info=True)
        return e

    # Intialize the key manager
    app.keyManager = KeyManager()

    ##########################################################################
    # Protection against CSRF attacks
    ##########################################################################
    with app.app_context():
        pgCSRFProtect.init_app(app)

    ##########################################################################
    # All done!
    ##########################################################################
    return app
Beispiel #21
0
# Only import flask_fas_openid if it is needed
if APP.config.get('PAGURE_AUTH', None) in ['fas', 'openid']:
    from flask_fas_openid import FAS
    FAS = FAS(APP)

    @FAS.postlogin
    def set_user_fas(return_url):
        ''' After login method. '''
        set_user()
        return flask.redirect(return_url)


if APP.config.get('PAGURE_AUTH', None) == 'oidc':
    from flask_oidc import OpenIDConnect
    oidc = OpenIDConnect(APP)

    @APP.before_request
    def fas_user_from_oidc():
        if oidc.user_loggedin and 'oidc_logintime' in flask.session:
            email_key, fulln_key, usern_key, ssh_key, groups_key = [
                APP.config['OIDC_PAGURE_EMAIL'],
                APP.config['OIDC_PAGURE_FULLNAME'],
                APP.config['OIDC_PAGURE_USERNAME'],
                APP.config['OIDC_PAGURE_SSH_KEY'],
                APP.config['OIDC_PAGURE_GROUPS'],
            ]
            info = oidc.user_getinfo(
                [email_key, fulln_key, usern_key, ssh_key, groups_key])
            username = info.get(usern_key)
            if not username:
Beispiel #22
0
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
"""
Helper module for configuring OpenID Connect based authentication
"""
from functools import wraps
import logging

import flask
from flask_openid import OpenID
from flask_oidc import OpenIDConnect

_log = logging.getLogger(__name__)

oid = OpenID()
oidc = OpenIDConnect(credentials_store=flask.session)


####################################
# Set up core OpenID Connect support
####################################

def configure_openid(app):
    """Set up OpenID, OpenIDConnect, and the module's Flask app reference"""
    global oidc
    global oid
    oid.init_app(app)
    try:
        oidc.init_app(app)
    except Exception as exc:
        # Handle running with only anonymous API access enabled
Beispiel #23
0
from flask_oidc import OpenIDConnect
from flask_sqlalchemy import SQLAlchemy

login = OpenIDConnect()

db = SQLAlchemy()
Beispiel #24
0
def create_app(entirety_config, client_secret):
    """Main function to create Flask app"""
    app = Flask(__name__,
                static_folder='../static',
                template_folder='../templates')

    app.config.update({
        'SECRET_KEY': 'SomethingNotEntirelySecret',
        'TESTING': True,
        'DEBUG': True,
        'OIDC_CLIENT_SECRETS': client_secret,
        'OIDC_ID_TOKEN_COOKIE_SECURE': False,
        'OIDC_REQUIRE_VERIFIED_EMAIL': False,
        'OIDC_USER_INFO_ENABLED': True,
        'OIDC_OPENID_REALM': 'n5geh',
        'OIDC_SCOPES': ['openid', 'email', 'profile'],
        'OIDC_INTROSPECTION_AUTH_METHOD': 'client_secret_post',
        'FIWARE': entirety_config['fiware'],
        'DEVICE_IDM': entirety_config['device_idm'],
        'DATAMODEL': entirety_config['datamodel'],
        'IDM': entirety_config['idm']
    })

    oidc = OpenIDConnect(
        app)  # OpenIDConnect provides security mechanism for API

    datamodel = Datamodel(config=app.config['DATAMODEL'])

    orion = Orion(config=app.config['FIWARE'])

    iotagent = IoTAgent(config=app.config['FIWARE'])

    quantumleap = QuantumLeap(config=app.config['FIWARE'])

    idm = IDM(config=app.config['DEVICE_IDM'])

    formservice = FormService()

    # General routes
    @app.errorhandler(404)
    def not_found(e):
        """Render not found page"""
        return render_template("404.html")

    @app.before_request
    def before_request():
        """Add user details to each request"""
        if oidc.user_loggedin:
            info = oidc.user_getinfo([
                'preferred_username', 'email', 'sub', 'given_name',
                'family_name'
            ])
            g.user = info.get('preferred_username')
            g.fullname = '{} {}'.format(info.get('given_name'),
                                        info.get('family_name'))
            g.account_url = app.config['IDM']['account_url']
        else:
            g.user = None
            g.fullname = None

    @app.route('/')
    def index():
        """Default web page"""
        return redirect('/dashboard')

    @app.route('/dashboard')
    @oidc.require_login
    def dashboard():
        """Dashboard web page"""
        data = {}
        data['orion_version'] = orion.get_version()
        data['iot_agent_version'] = iotagent.get_version()
        data['idm_is_active'] = idm.is_active()
        data['quantumleap_version'] = quantumleap.get_version()
        data['classes'] = datamodel.get_classes()
        data['subscription_number'] = len(orion.get_subscriptions())

        count = 0
        if data['orion_version'] != '':
            for c in data['classes']:
                count += len(orion.get_entities(c))
        data['registered_classes'] = count
        data['all_classes'] = len(datamodel.classes_file_list)
        return render_template('dashboard.html', d=data)

    @app.route('/about')
    @oidc.require_login
    def about():
        """Render About page"""
        page_name = 'About'
        page_content = 'Device Wizard is a service for registering device within N5GEH cloud platform.'
        return render_template('simple.html',
                               page_name=page_name,
                               page_content=page_content)

    @app.route('/help')
    @oidc.require_login
    def help():
        """Render Help page"""
        page_name = 'Help'
        page_content = 'This is a help page to explain how user can register a device in a N5GEH platform.'
        return render_template('simple.html',
                               page_name=page_name,
                               page_content=page_content)

    @app.route('/logout')
    def logout():
        """Performs logout by removing the session cookie."""
        oidc.logout()
        return redirect(app.config['IDM']['logout_link'])

    # Orion routes
    def select_type(device_types,
                    fiware_service,
                    render_page='select_type.html'):
        """Render Select type of device page for Orion and IoT Agent"""
        choices = []
        for t in device_types:
            tt = t.split('.')
            choices.append((
                t,
                tt[0],
            ))
        form = TypesForm()
        form.types.choices = choices
        return render_template(render_page,
                               form=form,
                               fiware_service=fiware_service)

    def wrong_device_type(device_type, url, service):
        """Render error page with wrong device type"""
        page_name = 'Wrong device type'
        page_content = 'Could not found template for this <span class="text-warning">{}services</span> device type. Please select one from <a href="{}">+ {} page</a>.'.format(
            device_type, url, service)
        return render_template('simple.html',
                               page_name=page_name,
                               page_content=page_content)

    def check_orion(func):
        """Check if Orion is available"""
        @wraps(func)
        def decorated_function(*args, **kwargs):
            if orion.get_version() == '':
                page_name, page_content = (
                    'Orion LD',
                    'Could not connect to the Orion LD. URL: {}'.format(
                        orion.url),
                )
                return render_template('simple.html',
                                       page_name=page_name,
                                       page_content=page_content)
            return func(*args, **kwargs)

        return decorated_function

    def check_keycloak(func):
        """Check if Keycloak is available"""
        @wraps(func)
        def decorated_function(*args, **kwargs):
            if not idm.is_active():
                page_name, page_content = (
                    'Keycloack',
                    'Could not connect to the Keycloack IDM. URL: {}'.format(
                        idm.config['server']),
                )
                return render_template('simple.html',
                                       page_name=page_name,
                                       page_content=page_content)
            return func(*args, **kwargs)

        return decorated_function

    def check_iotagent(func):
        """Check if IoT Agent is available"""
        @wraps(func)
        def decorated_function(*args, **kwargs):
            if iotagent.get_version() == '':
                page_name, page_content = (
                    'IoT Agent',
                    'Could not connect to the IoT Agent. URL: {}'.format(
                        iotagent.url),
                )
                return render_template('simple.html',
                                       page_name=page_name,
                                       page_content=page_content)
            return func(*args, **kwargs)

        return decorated_function

    def check_quantumleap(func):
        """Check if QuantumLeap is available"""
        @wraps(func)
        def decorated_function(*args, **kwargs):
            if quantumleap.get_version() == '':
                page_name, page_content = (
                    'QuantumLeap',
                    'Could not connect to the QuantumLeap. URL: {}'.format(
                        quantumleap.url),
                )
                return render_template('simple.html',
                                       page_name=page_name,
                                       page_content=page_content)
            return func(*args, **kwargs)

        return decorated_function

    @app.route('/orion/device', methods=['GET', 'POST'])
    @oidc.require_login
    @check_orion
    @check_keycloak
    def orion_device():
        """Render Device Wizard page"""
        device_type = request.args.get('types')
        if device_type is None:
            return select_type(datamodel.device_types, 'Orion LD')

        if device_type not in datamodel.device_types:
            return wrong_device_type(device_type, '/orion/device', 'Orion LD')

        form, properties_dict = formservice.create_form_template(
            device_type, orion, datamodel)

        if request.method == 'POST':
            form = form(request.form)
            if form.validate():
                params = {}
                for fieldname, value in form.data.items():
                    if fieldname.endswith('_datetime'):
                        params[fieldname] = value.isoformat() + 'Z'
                    else:
                        params[fieldname] = value

                entity = datamodel.create_entity(device_type, params)
                result = orion.create_entity(entity)

                id_key = properties_dict['id'][2]
                device_type = formservice.get_device_type(device_type)
                idm.create_entity(
                    'urn:ngsi-ld:{}:{}'.format(device_type, params[id_key]),
                    device_type)

                if result['status']:
                    page_name = 'Success'
                    page_content = 'Entity successfully created. Go to <a href="/orion/devices">Orion LD devices page</a>.'
                    return render_template('simple.html',
                                           page_name=page_name,
                                           page_content=page_content)
                else:
                    page_name = 'Failed'
                    page_content = 'Could not create entity. <a href="" onclick="windows.back()">Go Back</a> <br/>Reason: <span class="text-danger">{}</span>'.format(
                        result['error'])
                    return render_template('simple.html',
                                           page_name=page_name,
                                           page_content=page_content)

        return render_template('form_generator.html',
                               form=form(),
                               action='Register',
                               fiware_service='Orion LD')

    @app.route('/orion/edit_device', methods=['GET', 'POST'])
    @oidc.require_login
    @check_orion
    def orion_edit_device():
        """Edit device properties"""
        device_id = request.args.get('id')
        device_type = request.args.get('type')

        form = formservice.create_form_entity(device_id, device_type, orion,
                                              datamodel)

        if request.method == 'POST':
            filled_form = form(request.form)
            if filled_form.validate():
                result = orion.update_entity(
                    device_id,
                    formservice.create_entity_update(filled_form.data.items()))
                if result['status']:
                    page_name = 'Success'
                    page_content = 'Entity successfully updated. Go to <a href="/orion/device">+ Orion LD page</a>.'
                    return render_template('simple.html',
                                           page_name=page_name,
                                           page_content=page_content)
                else:
                    page_name = 'Failed'
                    page_content = 'Could not update entity. <a href="" onclick="windows.back()">Go Back</a> <br/>Reason: <span class="text-danger">{}</span>'.format(
                        result['error'])
                    return render_template('simple.html',
                                           page_name=page_name,
                                           page_content=page_content)

        return render_template('form_generator.html',
                               form=form(),
                               action='Update',
                               fiware_service='Orion LD')

    @app.route('/orion/devices', methods=['GET', 'POST'])
    @oidc.require_login
    @check_orion
    @check_keycloak
    def get_orion_devices():
        """Render list of Orion devices page"""
        device_type = request.args.get('types')
        if device_type is None:
            return select_type(datamodel.device_types,
                               'Orion LD',
                               render_page='orion/devices.html')

        if device_type not in datamodel.device_types:
            return wrong_device_type(device_type, '/orion/device', 'Orion LD')

        device_type = device_type.split(".")[0]
        devices = orion.get_entities(device_type)
        for device in devices:
            device['mqtt_topic'] = idm.create_topic(device['id'], device_type)
            device['mqtt_user'] = device['id'].lower()
        return render_template('orion/devices_to_json.html',
                               devices=devices,
                               device_type=device_type)

    @app.route('/orion/subscriptions', methods=['GET', 'POST'])
    @oidc.require_login
    @check_orion
    def get_orion_subscriptions():
        """Render Orion subscrpitions page"""
        return render_template('orion/subscriptions.html')

    @app.route('/orion/subscriptions_to_json', methods=['GET', 'POST'])
    @oidc.require_login
    def get_orion_subscriptions_json():
        """Render Orion subscriptions as JSON"""
        subscriptions = orion.get_subscriptions()
        return render_template('orion/subscriptions_to_json.html',
                               subscriptions=subscriptions)

    @app.route('/orion/delete', methods=['GET'])
    @oidc.require_login
    @check_orion
    @check_keycloak
    def orion_delete():
        """Delete device from Orion"""
        device_id = request.args.get('device_id')
        orion.delete_entity(device_id)
        idm.delete_entity(device_id)
        return "true"

    @app.route('/orion/init_subscriptions', methods=['GET'])
    @oidc.require_login
    @check_orion
    @check_quantumleap
    def orion_init_subscription():
        """Init QuantumLeap subscriptions in Orion for the Datamodel"""
        devices_types = datamodel.iotdevice_types
        for devices_type in devices_types:
            try:
                result = orion.create_subscription(devices_type)
            except Exception as e:
                pass
        page_name = 'Success'
        page_content = 'Subscriptions successfully registered. Go to <a href="/iotagent/device">+ IoT Agent device</a>.'
        return render_template('simple.html',
                               page_name=page_name,
                               page_content=page_content)

    @app.route('/orion/delete_subscription', methods=['GET'])
    @oidc.require_login
    @check_orion
    def orion_delete_subscription():
        """Delete subscription from Orion"""
        subcription_id = request.args.get('subscription_id')
        r = orion.delete_subscription(subcription_id)
        return "true"

    @app.route('/orion/register_classes', methods=['GET'])
    @oidc.require_login
    @check_orion
    def orion_register_classes():
        """Register properties classes for the Datamodel"""
        classes = datamodel.get_classes_files()
        for cls in classes:
            if os.path.isfile(cls):
                data = open(cls, 'rt').read()
                try:
                    result = orion.create_entity(data)
                except Exception as e:
                    pass
        page_name = 'Success'
        page_content = 'Classes successfully registered. Go to <a href="/iotagent/device">+ IoT Agent device</a>.'
        return render_template('simple.html',
                               page_name=page_name,
                               page_content=page_content)

    # IoT Agent routes
    @app.route('/iotagent/device', methods=['GET', 'POST'])
    @oidc.require_login
    @check_orion
    @check_keycloak
    @check_iotagent
    def iotagent_device():
        """Render page for IoT Agent device"""
        device_type = request.args.get('types')
        if device_type is None:
            return select_type(datamodel.iotdevice_types, 'IoT Agent')

        if device_type not in datamodel.iotdevice_types:
            return wrong_device_type(device_type, '/iotagent/device',
                                     'IoT Agent')

        form = formservice.create_form_json(device_type, orion, datamodel)

        if request.method == 'POST':
            form = form(request.form)
            if form.validate():
                params = {}
                for fieldname, value in form.data.items():
                    if fieldname.endswith('_datetime'):
                        params[fieldname] = value.isoformat() + 'Z'
                    else:
                        params[fieldname] = value

                services = iotagent.get_services()
                apikey = IDM.create_apikey(device_type)
                is_service_exist = False
                for service in services['services']:
                    if service['apikey'] == apikey:
                        is_service_exist = True
                if not is_service_exist:
                    iotagent.create_service(apikey, device_type)

                device = formservice.create_iotdevice(device_type, params,
                                                      datamodel)

                result = iotagent.create_device(device)

                idm.create_entity(device['entity_name'], device['entity_type'])

                if result['status']:
                    page_name = 'Success'
                    page_content = 'Entity successfully registered. Go to <a href="/iotagent/devices">IoT Agent registered devices page</a>.'
                    return render_template('simple.html',
                                           page_name=page_name,
                                           page_content=page_content)
                else:
                    page_name = 'Failed'
                    page_content = 'Could not register entity. <a href="" onclick="windows.back()">Go Back</a> <br/>Reason: <span class="text-danger">{}</span>'.format(
                        result['error'])
                    return render_template('simple.html',
                                           page_name=page_name,
                                           page_content=page_content)

        return render_template('form_generator.html',
                               form=form(),
                               action='Register',
                               fiware_service='IoT Agent')

    @app.route('/iotagent/devices', methods=['GET', 'POST'])
    @oidc.require_login
    @check_iotagent
    @check_keycloak
    def get_iotagent_devices():
        """Render IoT Agent devices"""
        return render_template('iotagent/devices.html')

    @app.route('/iotagent/devices_to_json', methods=['GET', 'POST'])
    @oidc.require_login
    def get_iotagent_devices_json():
        """Render IoT Agent devices as JSON"""
        devices = iotagent.get_entities()
        for device in devices['devices']:
            device['mqtt_topic'] = idm.create_topic(device['entity_name'],
                                                    device['entity_type'])
            device['mqtt_user'] = device['entity_name'].lower()
        return render_template('iotagent/devices_to_json.html',
                               devices=devices)

    @app.route('/iotagent/services', methods=['GET', 'POST'])
    @oidc.require_login
    @check_iotagent
    def get_iotagent_services():
        """Render IoT Agent services"""
        return render_template('iotagent/services.html')

    @app.route('/iotagent/services_to_json', methods=['GET', 'POST'])
    @oidc.require_login
    def get_iotagent_services_json():
        """Render IoT Agent services as JSON"""
        services = iotagent.get_services()
        return render_template('iotagent/services_to_json.html',
                               services=services)

    @app.route('/iotagent/delete_service', methods=['GET'])
    @oidc.require_login
    @check_orion
    def iotagent_delete_service():
        """Delete service from IoT Agent"""
        apikey = request.args.get('apikey')
        resource = request.args.get('resource')
        iotagent.delete_service(apikey, resource)
        return "true"

    @app.route('/iotagent/delete_device', methods=['GET'])
    @oidc.require_login
    @check_iotagent
    @check_keycloak
    def iotagent_delete_device():
        """Delete device from IoT Agent"""
        device_id = request.args.get('device_id')
        iotagent.delete_entity(device_id)
        idm.delete_entity(device_id)
        return "true"

    return app
Beispiel #25
0
limiter = Limiter(key_func=get_remote_address)

cache_supported_backends = {
    None: __cache_module.NullCache,
    'memcached': __cache_module.MemcachedCache,
    'redis': __cache_module.RedisCache
}

__cache_uri = os.environ.get('CACHE_SERVICE')

if __cache_uri:
    try:
        # example __cache_uri is 'redis:dev_redis_1:6379'
        [__cache_type, __url, __port] = __cache_uri.split(':')
    except ValueError:
        raise ImproperlyConfigured('CACHE_SERVICE is wrongly formatted. Use "redis:dev_redis_1:6379" as example.')
    if __cache_type == 'redis':
        cache = __cache_module.RedisCache(host=__url, port=__port, default_timeout=os.environ.get('CACHE_TIMEOUT'))
    elif __cache_type == 'memcached':
        cache = __cache_module.MemcachedCache(
            servers=["{url}:{port}".format(url=__url, port=__port)],
            default_timeout=os.environ.get('CACHE_TIMEOUT')
        )
    else:
        raise ImproperlyConfigured('Unknown cache service, only Memcached and Redis are supported at the moment.')
else:
    cache = __cache_module.NullCache

credentials_store = SqliteDict('flask_oidc.db', autocommit=True)
openid_connect = OpenIDConnect(credentials_store=credentials_store)
Beispiel #26
0
    socketio.init_app(application,
                      async_mode='eventlet',
                      message_queue=application.config['ACTIVE_MQ_URL'],
                      path='/api/v1/socket.io')
else:
    socketio.init_app(application, path='/api/v1/socket.io')

if application.config['CORS_ALLOWED_ORIGINS'] is not None:
    CORS(application,
         supports_credentials=True,
         origins=application.config['CORS_ALLOWED_ORIGINS'])

api = Api(application, prefix='/api/v1', doc='/api/v1/')

from flask_oidc import OpenIDConnect
oidc = OpenIDConnect(application)

#  Set up Flask Admin.
from app import admin
flask_admin = Admin(application,
                    name='Admin Console',
                    template_mode='bootstrap3',
                    index_view=admin.HomeView())
flask_admin.add_view(admin.ChannelModelView)
flask_admin.add_view(admin.CounterModelView)
flask_admin.add_view(admin.CSRModelView)
flask_admin.add_view(admin.CSRGAModelView)
flask_admin.add_view(admin.InvigilatorModelView)
flask_admin.add_view(admin.OfficeModelView)
flask_admin.add_view(admin.OfficeGAModelView)
flask_admin.add_view(admin.RoleModelView)
Beispiel #27
0
          description="Apis desarrollada para manejar Farma Salud")

flask_app.config.update({
    'SECRET_KEY': 'SomethingNotEntirelySecret',
    'TESTING': True,
    'DEBUG': True,
    'OIDC_CLIENT_SECRETS': 'conf/client_secrets.json',
    'OIDC_ID_TOKEN_COOKIE_SECURE': False,
    'OIDC_REQUIRE_VERIFIED_EMAIL': False,
    'OIDC_USER_INFO_ENABLED': True,
    'OIDC_OPENID_REALM': 'farmasalud',
    'OIDC_SCOPES': ['openid', 'email', 'profile'],
    'OIDC_INTROSPECTION_AUTH_METHOD': 'client_secret_post'
})

oidc = OpenIDConnect(flask_app)
#app.namespace()

sucursales = app.namespace('sucursales', description='Manejar Sucursales')
articulos = app.namespace('articulos', description='Manejar articulos')
inventory = app.namespace('inventory', description='Manejar articulos')
user = app.namespace('user', description='Manejar articulos')
login = app.namespace('login', description='login')
logout = app.namespace('logout', description='login')

with open(r'conf/efip_config.yaml') as file:
    config = yaml.load(file, Loader=yaml.FullLoader)

agregararticulo_model = app.model(
    'Modelo agregar articulo', {
        'nombre_del_articulo':
Beispiel #28
0
import flask
#from fedora.client import AuthError, AppError
from flask_oidc import OpenIDConnect
import munch

# Set up Flask application
app = flask.Flask(__name__)
# Application configuration (add secret key of your choice)
app.config["OIDC_CLIENT_SECRETS"] = "client_secrets.json"
app.config["SECRET_KEY"] = "secretkey"
app.config["OIDC_SCOPES"] = [
    'openid', 'email', 'profile', 'https://id.fedoraproject.org/scope/groups',
    'https://id.fedoraproject.org/scope/agreements'
]
# Set up FAS extension
OIDC = OpenIDConnect(app, credentials_store=flask.session)


@app.before_request
def before_request():
    """Set the flask session as permanent."""
    flask.session.permanent = True


@app.route("/logged_in")
@OIDC.require_login
def logged_in():

    return flask.Response(
        f"You are now logged in. Try to logout by going to http://localhost:5000/logout {OIDC.user_getfield('email')} {OIDC.user_getfield('zoneinfo')} {OIDC.user_getfield('preferred_username')}"
    )
Beispiel #29
0
 def __init__(self, appbuilder):
     super().__init__(appbuilder)
     if self.auth_type == AUTH_OID:
         self.oid = OpenIDConnect(self.appbuilder.get_app)
         self.authoidview = KeycloakAuthOIDCView
Beispiel #30
0
import json

import logging
logging.basicConfig()

config = {
    'OIDC_CLIENT_SECRETS': './client_secrets.json',
    'OIDC_ID_TOKEN_COOKIE_SECURE': False,
    'OIDC_VALID_ISSUERS': 'http://*****:*****@app.route('/userinfo')
@oidc.accept_token()
def my_api():
    #return json.dumps('Welcome %s' % oidc.oidc_token_info['sub'])
    return json.dumps(oidc._retrieve_userinfo())