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
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
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'])
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(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
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
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 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
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
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
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)
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)
def _get_token_info(self, token): """ Request the token information from the introspection API endpoint. This wraps the original method to provide a form of caching to avoid calling the introspection API endpoint twice if other code needs the decoded JWT. :param str token: the access token to get information about :return: the token information :rtype: dict """ if not self._token_info.get(token): self._token_info[token] = OpenIDConnect._get_token_info(self, token) return self._token_info[token]
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
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))
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)
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)
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
# 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:
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
'CORS_HEADERS':'Content-Type', 'DEBUG': True, 'OIDC_CLIENT_SECRETS': 'client_secrets.json', 'OIDC_ID_TOKEN_COOKIE_SECURE': False, 'OIDC_REQUIRE_VERIFIED_EMAIL': False, 'OIDC_USER_INFO_ENABLED': True, 'OIDC_OPENID_REALM': 'flask-app', 'OIDC_SCOPES': ['openid', 'email', 'profile'], 'OIDC_INTROSPECTION_AUTH_METHOD': 'client_secret_post' }) # 'OVERWRITE_REDIRECT_URI': 'http://*****:*****@app.route('/makedata') @oidc.require_login def MakeDataApi(): name = request.args.get('name', 'hamed') number = request.args.get('number', '123456') method = request.args.get('method', 'POST') timeout = request.args.get('timeout', 10) key = str(uuid4()) # print(key)
from flask_oidc import OpenIDConnect from flask_sqlalchemy import SQLAlchemy login = OpenIDConnect() db = SQLAlchemy()
class BotFramework(object): 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): self.connectors = connectors self.session = requests.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 self.store = 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 # 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']) def _config(self): if self.oidc_client_secrets_path is None: f = tempfile.NamedTemporaryFile(mode='w', delete=False) oidc_client_secrets = { "web": { "client_id": self.app_client_id, "client_secret": self.app_client_secret, "redirect_uris": ["https://localhost:8080/oidc_callback"], "token_uri": "https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token", "token_introspection_uri": "https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token", "auth_uri": "https://login.botframework.com/v1/.well-known/openidconfiguration", "userinfo_uri": "https://login.botframework.com/v1/.well-known/openidconfiguration", "issuer": "https://api.botframework.com", "grant_type": "client_credentials", "scope": "https://api.botframework.com/.default" } } f.write(json.dumps(oidc_client_secrets)) client_secrets_path = f.name else: client_secrets_path = self.oidc_client_secrets_path # TODO: Add config details here for flask app return { 'OIDC_CLIENT_SECRETS': client_secrets_path, 'OIDC_SCOPES': ["https://api.botframework.com/.default", "openid"], 'OIDC_RESOURCE_SERVER_ONLY': True, 'OIDC_INTROSPECTION_AUTH_METHOD': 'bearer' } def set_store_type(self, store_type): self.store_type = store_type def handle_messages(self): if flask.request.method == "POST": # User message to bot data = flask.request.json self.receive(data) return Response(mimetype='application/json', status=202) return jsonify({'message': "Invalid request method"}), 405, { 'Content-Type': 'application/json' } def run_server(self, port=6379, debug=False, threaded=True, **flask_run_options): self.server.run(port=port, debug=debug, **flask_run_options) def receive(self, data, *args, **kwargs): if data["type"] == "conversationUpdate": # Add the members to the conversation self.begin_dialog(data) else: # The bot responds to the user, looking at kwargs in # case of added intent intent = None if 'intent' in kwargs: intent = kwargs['intent'] self.respond_to_client(data, intent=intent) def begin_dialog(self, data): self.members_added = data["membersAdded"] member_added = self.members_added[0]["name"] from_id = data["from"]["id"] general_id = data["id"] sender_id = data["recipient"]["id"] message = '' for member in self.members_added: message += '{} added!'.format(member["name"]) self.send(data["serviceUrl"], data["channelId"], general_id, { "id": sender_id, "name": member_added }, {"id": from_id}, message, "message", data["conversation"]) def process_message(self, complete_data, intent=None, conn_itr=None, *args, **kwargs): message = complete_data["text"] message = message.rstrip(".! \n\t") # Structure message in dict for handling by connector # (TODO: manage entire message stack) data = {} data['message'] = message if conn_itr is None: conn_itr = self.connectors.__iter__() # One connector response feeds into the next in this recursive function def resp(conndata, conn_current=None, cb=None): try: if conn_current is not None: conn_prev, conn_current = conn_current, next(conn_itr) else: conn_prev, conn_current = None, next(conn_itr) conndata = conn_current.respond(message) # Call this function recursively to pass through steps return resp(conndata, conn_current) except StopIteration as e: # End of steps reached return conndata # Final data data = resp(data) if data is None: response_message = "I didn't catch that. One more time?" else: response_message = data user_id = complete_data["from"]["id"] channel_id = complete_data["channelId"] if self.store is None: self.store = self.create_store(complete_data, self.get_auth_str()) self.store.save_user_data(channel_id, user_id, [message, response_message]) #memory.append([message, response_message]) return response_message def get_auth_str(self): # Authentication: retrieving token from MSA service to help # verify to BF Connector service url = "https://login.microsoftonline.com/botframework.com/"\ "oauth2/v2.0/token" data = { "grant_type": "client_credentials", "client_id": self.app_client_id, "client_secret": self.app_client_secret, "scope": "https://api.botframework.com/.default" } response = requests.post(url, data) resp_data = response.json() try: self.auth_str = "{} {}".format(resp_data["token_type"], resp_data["access_token"]) except KeyError: print("Can't create auth string: {}".format(resp_data)) self.auth_str = "" def create_store(self, data, auth_str): self.store = InMemory(data, auth_str, self.session) if self.store_type != 'None': self.store = SessionStore.factory(self.store_type, data, auth_str, self.session) return self.store def send(self, service_url, channel_id, reply_to_id, from_data, recipient_data, message, message_type, conversation): if not self.auth_str: self.get_auth_str() url = service_url + \ "/v3/conversations/{}/activities/{}".format(conversation["id"], reply_to_id) requests.post( url=url, json={ "type": message_type, "text": message, "locale": "en-US", "from": from_data, "timestamp": datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f%zZ"), "localTimestamp": datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f%zZ"), "replyToId": reply_to_id, "channelId": channel_id, "recipient": recipient_data, "conversation": conversation }, headers={ "Authorization": self.auth_str, "Content-Type": "application/json" }) def get_user_memory(self, data): """ This method saves conversation data to UserMemory stores and returns the UserMemory object. """ user_id = data["from"]["id"] channel_id = data["channelId"] base_url = data["serviceUrl"] if not self.auth_str: self.get_auth_str() user_mem = UserMemory(self.session, user_id, channel_id, self.auth_str, base_url=base_url) return user_mem def respond_to_client(self, data, *args, **kwargs): member_added = self.members_added[0]["name"] general_id = data["id"] message = data["text"] sender_id = data["recipient"]["id"] #memory = self.get_user_memory(data) # If there's a LUIS intent involved send off to LUISBot method intent = kwargs['intent'] result = self.process_message(complete_data=data, intent=intent) self.send(data["serviceUrl"], data["channelId"], general_id, { "id": sender_id, "name": member_added }, {"id": data["from"]['id']}, result, "message", data["conversation"])
# 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
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)
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')}" )
from flask import Flask, render_template, g, redirect, url_for from flask_oidc import OpenIDConnect from okta import UsersClient # Create an instance of the Flask class that is the WSGI application. # The first argument is the name of the application module or package, # typically __name__ when using a single module. app = Flask(__name__) app.debug = True app.config["OIDC_CLIENT_SECRETS"] = "exclude/client_secrets.json" app.config["OIDC_COOKIE_SECURE"] = False #allows you to test out user login and registration in development without using SSL. If you were going to run your site publicly, you would remove this option and use SSL on your site. app.config["OIDC_CALLBACK_ROUTE"] = "/oidc/callback" app.config["OIDC_SCOPES"] = ["openid", "email", "profile"] app.config["SECRET_KEY"] = "aa" oidc = OpenIDConnect(app) oidc.init_app(app) okta_client = UsersClient("https://dev-711513.oktapreview.com", "00-96K0PI5EgQUBFwFDwoBn9JObfyu4p6wfmFdlxjO") @app.before_request def before_request(): if oidc.user_loggedin: g.user = okta_client.get_user(oidc.user_getfield("sub")) else: g.user = None # Flask route decorators map / and /hello to the hello function.
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"))
def __init__(self, *args, **kwargs): """Initialize the EstuaryOIDC class.""" # Contains a cache of the token information returned by the introspection API endpoint self._token_info = {} OpenIDConnect.__init__(self, *args, **kwargs)
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():
def __init__(self, appbuilder): super().__init__(appbuilder) if self.auth_type == AUTH_OID: self.oid = OpenIDConnect(self.appbuilder.get_app) self.authoidview = KeycloakAuthOIDCView