def __init__(self, app=None, provider=None): self.principal = Principal(use_sessions=False) self.require = PermissionFactory() self.app = app if self.app: # pragma: no cover self.init_app(app, provider)
def create_app(config_name): dash = Flask(__name__) dash.config.from_object(config[config_name]) config[config_name].init_app(dash) AdminLTE.init_app(dash) mail.init_app(dash) moment.init_app(dash) db.init_app(dash) login_manager.init_app(dash) Principal.init_app(dash) toolbar.init_app(dash) # special helper functions @dash.context_processor def my_utility_processor(): from .models import Provider def all_providers(): """ returns all providers """ return Provider.query.all() return dict(all_providers=all_providers) # attach routes and custom error pages here # main application from dash.main import main as main_blueprint dash.register_blueprint(main_blueprint) # auth application from .auth import auth as auth_blueprint dash.register_blueprint(auth_blueprint, url_prefix='/auth') # user profile application from .profile import profile as profile_blueprint dash.register_blueprint(profile_blueprint, url_prefix='/profile') # server application from .server import server as server_blueprint dash.register_blueprint(server_blueprint, url_prefix='/server') # image application from .image import image as image_blueprint dash.register_blueprint(image_blueprint, url_prefix='/image') # security application from .security import security as security_blueprint dash.register_blueprint(security_blueprint, url_prefix='/security') # network application from .network import network as network_blueprint dash.register_blueprint(network_blueprint, url_prefix='/network') # admin application from .admin import admin as admin_blueprint dash.register_blueprint(admin_blueprint, url_prefix='/admin') return dash
def _get_principal(self, app: FlaskUnchained) -> Principal: """ Get an initialized instance of Flask Principal's. :class:~flask_principal.Principal`. """ principal = Principal(app, use_sessions=False) principal.identity_loader(self._identity_loader) return principal
def create_app(): app = Flask(__name__) app.config.from_object(config.DevelopmentConfig) # adds jinja2 support for break and continue in loops app.jinja_env.add_extension('jinja2.ext.loopcontrols') with app.app_context(): from apluslms_shepherd.auth.models import write_user_to_db, login_manager from apluslms_shepherd.views import main_bp from apluslms_shepherd.auth.views import auth_bp from apluslms_shepherd.courses.views import course_bp from apluslms_shepherd.build.views import build_log_bp from apluslms_shepherd.webhooks.views import webhooks_bp from apluslms_shepherd.groups.views import groups_bp from apluslms_shepherd.repos.views import repo_bp login_manager.init_app(app=app) db.init_app(app=app) migrate = Migrate(app, db, render_as_batch=True) lti_login_authenticated.connect(write_user_to_db) # Flask-Principal: --- Setup ------------------------------------ principals = Principal(app) principals.init_app(app) # ----------------------------------------------------------------- app.register_blueprint(main_bp) app.register_blueprint(build_log_bp) app.register_blueprint(course_bp) app.register_blueprint(lti) app.register_blueprint(auth_bp) app.register_blueprint(webhooks_bp) app.register_blueprint(groups_bp) app.register_blueprint(repo_bp) # Add info to the Identity instance @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): # Set the identity user object identity.user = current_user # Add the UserNeed to the identity if hasattr(current_user, 'id'): identity.provides.add(UserNeed(current_user.id)) # Update the identity with the role that the user provides if hasattr(current_user, 'roles'): for role in current_user.roles.split(','): identity.provides.add(RoleNeed(role)) app.logger.info(identity) # Handle HTTP 403 error @app.errorhandler(403) def access_forbidden(e): session['redirected_from'] = request.url flash('Access Forbidden') return redirect('/') return app
def init_app(app): # Setup LoginManager login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'security.login' # Setup Principal principals = Principal(app) app.register_blueprint(bp) # User auth frontend @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): identity.user = current_user if current_user.is_authenticated: identity.provides.add(UserNeed(current_user.id)) for group in current_user.securitygroups: for need in group.needs: identity.provides.add((need.type_, need.name)) @login_manager.user_loader def load_user(userid): return Users.objects().get(id=userid)
def create_app(): app.wsgi_app = ReverseProxied(app.wsgi_app) # For python2 convert path to unicode if sys.version_info < (3, 0): app.static_folder = app.static_folder.decode('utf-8') app.root_path = app.root_path.decode('utf-8') app.instance_path = app.instance_path .decode('utf-8') cache_buster.init_cache_busting(app) log.info('Starting Calibre Web...') Principal(app) lm.init_app(app) app.secret_key = os.getenv('SECRET_KEY', 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT') web_server.init_app(app, config) db.setup_db(config) babel.init_app(app) _BABEL_TRANSLATIONS.update(str(item) for item in babel.list_translations()) _BABEL_TRANSLATIONS.add('en') if services.ldap: services.ldap.init_app(app, config) if services.goodreads_support: services.goodreads_support.connect(config.config_goodreads_api_key, config.config_goodreads_api_secret, config.config_use_goodreads) return app
def init_app(self, app, storage=None, cache=None): """ Initialize the engine. :param app: The app to use :type app: Object :param storage: The blog storage instance that implements the :type storage: Object :param cache: (Optional) A Flask-Cache object to enable caching :type cache: Object ``Storage`` class interface. """ self.app = app self.config = self.app.config self.storage = storage or self.storage self.cache = cache or self.cache self._register_plugins(self.app, self.config) from .views import create_blueprint blog_app = create_blueprint(__name__, self) # external urls blueprint_created.send(self.app, engine=self, blueprint=blog_app) self.app.register_blueprint( blog_app, url_prefix=self.config.get("BLOGGING_URL_PREFIX")) self.app.extensions["FLASK_BLOGGING_ENGINE"] = self # duplicate self.app.extensions["blogging"] = self self.principal = Principal(self.app) engine_initialised.send(self.app, engine=self) self.ffu = FlaskFileUpload(app)
def create_app(): app.wsgi_app = ReverseProxied(app.wsgi_app) # For python2 convert path to unicode if sys.version_info < (3, 0): app.static_folder = app.static_folder.decode('utf-8') app.root_path = app.root_path.decode('utf-8') app.instance_path = app.instance_path.decode('utf-8') if os.environ.get('FLASK_DEBUG'): cache_buster.init_cache_busting(app) log.info('Starting Calibre Web...') if sys.version_info < (3, 0): log.info('Python2 is EOL since end of 2019, this version of Calibre-Web is no longer supporting Python2 please consider upgrading to Python3') print('Python2 is EOL since end of 2019, this version of Calibre-Web is no longer supporting Python2 please consider upgrading to Python3') Principal(app) lm.init_app(app) app.secret_key = os.getenv('SECRET_KEY', config_sql.get_flask_session_key(ub.session)) web_server.init_app(app, config) babel.init_app(app) _BABEL_TRANSLATIONS.update(str(item) for item in babel.list_translations()) _BABEL_TRANSLATIONS.add('en') if services.ldap: services.ldap.init_app(app, config) if services.goodreads_support: services.goodreads_support.connect(config.config_goodreads_api_key, config.config_goodreads_api_secret, config.config_use_goodreads) return app
def create_app(config=None): app = flask.Flask(__name__) app.config.from_object('config') if config is not None: app.config.update(**config) db.init_app(app) api.init_app(app) influx_db.init_app(app) menu.init_app(app) security.init_app(app, users) principal = Principal() principal.init_app(app) init_signals(app) configure_uploads(app, logos) app.register_blueprint(bp) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): if not isinstance(identity, AnonymousIdentity): identity.provides.add(UserNeed(identity.id)) for role in current_user.roles: identity.provides.add(RoleNeed(role.name)) @principal.identity_loader def read_identity_from_flask_login(): if current_user.is_authenticated: return Identity(current_user.id) return AnonymousIdentity() @app.after_request def set_cid_cookie(response): if 'cid' not in flask.request.cookies: cid = str(uuid.uuid4()) expires = datetime.datetime.now() + datetime.timedelta(days=365*2) response.set_cookie('cid', cid, expires=expires) return response return app
def create_app(): if sys.version_info < (3, 0): log.info( '*** Python2 is EOL since end of 2019, this version of Calibre-Web is no longer supporting Python2, please update your installation to Python3 ***' ) print( '*** Python2 is EOL since end of 2019, this version of Calibre-Web is no longer supporting Python2, please update your installation to Python3 ***' ) web_server.stop(True) sys.exit(5) if not lxml_present: log.info( '*** "lxml" is needed for calibre-web to run. Please install it using pip: "pip install lxml" ***' ) print( '*** "lxml" is needed for calibre-web to run. Please install it using pip: "pip install lxml" ***' ) web_server.stop(True) sys.exit(6) if not wtf_present: log.info( '*** "flask-WTF" is needed for calibre-web to run. Please install it using pip: "pip install flask-WTF" ***' ) print( '*** "flask-WTF" is needed for calibre-web to run. Please install it using pip: "pip install flask-WTF" ***' ) web_server.stop(True) sys.exit(7) for res in dependency_check() + dependency_check(True): log.info( '*** "{}" version does not fit the requirements. Should: {}, Found: {}, please consider installing required version ***' .format(res['name'], res['target'], res['found'])) app.wsgi_app = ReverseProxied(app.wsgi_app) if os.environ.get('FLASK_DEBUG'): cache_buster.init_cache_busting(app) log.info('Starting Calibre Web...') Principal(app) lm.init_app(app) app.secret_key = os.getenv('SECRET_KEY', config_sql.get_flask_session_key(ub.session)) web_server.init_app(app, config) babel.init_app(app) _BABEL_TRANSLATIONS.update(str(item) for item in babel.list_translations()) _BABEL_TRANSLATIONS.add('en') if services.ldap: services.ldap.init_app(app, config) if services.goodreads_support: services.goodreads_support.connect(config.config_goodreads_api_key, config.config_goodreads_api_secret, config.config_use_goodreads) return app
def app(request): """Flask application fixture.""" instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update( TESTING=True, SECRET_KEY='SECRET_KEY', ADMIN_LOGIN_ENDPOINT='login', SQLALCHEMY_TRACK_MODIFICATIONS=True, ) Babel(app) InvenioDB(app) Principal(app) LoginManager(app) # Install login and access loading. @app.login_manager.user_loader def load_user(user_id): return TestUser.get(user_id) @app.route('/login/') def login(): from flask import current_app from flask import request as flask_request user = TestUser.get(flask_request.args.get('user', 1)) login_user(user) identity_changed.send(current_app._get_current_object(), identity=Identity(user.id)) return "Logged In" @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): identity.user = current_user identity.provides.add(UserNeed(current_user.id)) if current_user.id == 1: identity.provides.add(action_admin_access) # Register admin view InvenioAdmin(app, permission_factory=lambda x: Permission(action_admin_access)) app.extensions['invenio-admin'].register_view(TestModelView, TestModel) # Create database with app.app_context(): if not database_exists(str(db.engine.url)): create_database(str(db.engine.url)) db.drop_all() db.create_all() def teardown(): with app.app_context(): drop_database(str(db.engine.url)) shutil.rmtree(instance_path) request.addfinalizer(teardown) return app
def configure_identity(app): Principal(app) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): # Set the identity user object identity.user = current_user # Add the UserNeed to the identity if hasattr(current_user, 'provides'): identity.provides.update(current_user.provides)
def configure_identity(app): Principal(app) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): g.user = User.query.from_identity(identity) @app.before_request def authenticate(): g.user = getattr(g.identity, 'user', None)
def create_app(config): """Initializes the public application Flask object. :param config: Configuration ADT :type config: Config :returns: Flask app object """ # init app app = Flask(__name__) app.config.from_object(config) # init logging logger.init_app(app) # init authorization Principal(app) # init CORS if 'CORS_ORIGIN' in app.config: CORS(app, supports_credentials=True, resources={r"/*": { "origins": app.config['CORS_ORIGIN'] }}) # init database db.init_app(app) # init Marshmallow ma.init_app(app) # add support for URI versioning via web server app.wsgi_app = ReverseProxied(app.wsgi_app) # register error handlers errors.register(app) # register modules health_check.register(app) locations.register(app) app_keys.register(app) roles.register(app) administrators.register(app) terms_of_services.register(app) users.register(app) user_profiles.register(app) logins.register(app) password_resets.register(app) notifications.register(app) user_account.register(app) return app
def configure_extensions(application): """ Configure Flask and other extensions used by the app args: application: the flask app """ from database import User # FOrce redirect to login page if unauthenticated and requesting authd page login_manager = LoginManager() login_manager.login_view = '/auth/login' login_manager.init_app(application) # Load user @login_manager.user_loader def load_user(user_id): user = User.filter_by(user_id=user_id).first() return user # Set up flask-principal principal = Principal(application) # Set up identitiy loader. This loads roles for a newly logged in user # https://pythonhosted.org/Flask-Principal/#user-information-providers @identity_loaded.connect_via(application) def on_ident_loaded(sender, identity): identity.user = current_user # Add UserNeed to our identity if hasattr(current_user, 'user_id'): identity.provides.add(UserNeed(current_user.user_id)) # Our User model provides for roles. This updates the identity with roles # for this user if hasattr(current_user, 'user_groups'): for group in current_user.user_groups: for role in group.roles: identity.provides.add(RoleNeed(role.name)) identity.provides.add(RoleNeed("authenticated")) # This is basically a hack to combat the session-reload issue when a session is forgotten # eg: the browser window is closed. This will destroy the session, thus our ident_loader # has no session to reload, despite still being logged in via flask-logins cookie # To combat this, we add a new identity_loader which will only run when a session expires # # Ref: https://stackoverflow.com/questions/24487449/flask-principal-flask-login-remember-me-and-identity-loaded @principal.identity_loader def load_ident_when_session_expires(): if hasattr(current_user, 'user_id'): return Identity(current_user.user_id)
def register_principal(app): princi = Principal(app) @princi.identity_loader def load_identity(): return Identity('yuan') @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): identity.user = g.user if not g.user: return identity.provides.add(UserNeed(g.user.id))
def __init__(self, ctx): """Create a vantage6-server application.""" self.ctx = ctx # initialize, configure Flask self.app = Flask(APPNAME, root_path=os.path.dirname(__file__)) self.configure_flask() # Setup SQLAlchemy and Marshmallow for marshalling/serializing self.ma = Marshmallow(self.app) # Setup the Flask-JWT-Extended extension (JWT: JSON Web Token) self.jwt = JWTManager(self.app) self.configure_jwt() # Setup Principal, granular API access manegement self.principal = Principal(self.app, use_sessions=False) # Enable cross-origin resource sharing self.cors = CORS(self.app) # SWAGGER documentation self.swagger = Swagger(self.app, template=swagger_template) # Setup the Flask-Mail client self.mail = MailService(self.app, Mail(self.app)) # Setup websocket channel try: self.socketio = SocketIO(self.app, async_mode='gevent_uwsgi') except Exception: self.socketio = SocketIO(self.app) # FIXME: temporary fix to get socket object into the namespace class DefaultSocketNamespace.socket = self.socketio self.socketio.on_namespace(DefaultSocketNamespace("/tasks")) # setup the permission manager for the API endpoints self.permissions = PermissionManager() # Api - REST JSON-rpc self.api = Api(self.app) self.configure_api() self.load_resources() # make specific log settings (muting etc) self.configure_logging() # set the serv self.__version__ = __version__
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) Principal(app) db.init_app(app) db.app = app with app.app_context(): db.create_all() login_manager.init_app(app) from .models import User, Post, UserRole, Comment, Tag, posts_tags, Role from .modelview import MyAdminIndexView, MyViewAll, MyView, MyViewpost flask_whooshalchemyplus.init_app(app) admin = Admin(app, template_mode='bootstrap3', index_view=MyAdminIndexView()) admin.add_view(MyView(User, db.session)) admin.add_view(MyViewpost(Post, db.session)) admin.add_view(MyViewAll(Comment, db.session)) admin.add_view(MyViewAll(Tag, db.session)) @app.errorhandler(404) def page_not_fond(error): return render_template('base/404.html'), 404 # Add identity to current user @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): # Set the identity user object identity.user = current_user # Add the UserNeed to the identity if hasattr(current_user, 'id'): identity.provides.add(UserNeed(current_user.id)) # Assuming the User model has a list of roles, update the # identity with the roles that the user provides if hasattr(current_user, 'roles'): for role in current_user.roles: identity.provides.add(RoleNeed(role.role_name)) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .momentjs import momentjs app.jinja_env.globals['momentjs'] = momentjs return app
def configure_flask_principal(app): principals = Principal(app) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): identity.user = current_user if hasattr(current_user, 'id'): identity.provides.add(UserNeed(current_user.id)) if hasattr(current_user, 'roles'): for role in current_user.roles: identity.provides.add(RoleNeed(role))
def init_services(): db = MongoClient().pli mail = Mail(application) principals = Principal(application) gridfs_ = gridfs.GridFS(db) Bootstrap(application) application.url_map.strict_slashes = False application.config["db"] = db application.config["mail"] = mail application.config["signer"] = URLSafeSerializer( application.config["SECRET_KEY"]) application.config["principals"] = principals application.config["gridfs"] = gridfs_
def create_app(): app = Flask(__name__) CORS(app) app.run(host='0.0.0.0') app.config['SECRET_KEY'] = '9OLWxNauth_blueprintD4o83j4K4iuopO' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite' db.init_app(app) principals = Principal(app) login_manager = LoginManager() login_manager.login_view = 'auth.login' login_manager.init_app(app) from .models import User @login_manager.user_loader def load_user(user_id): # since the user_id is just the primary key of our user table, use it in the query for the user return User.query.get(user_id) @principals.identity_loader def read_identity_from_flask_login(): if current_user.is_authenticated: return Identity(current_user.id) return AnonymousIdentity() @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): if not isinstance(identity, AnonymousIdentity): identity.provides.update(current_user.provides) from .BlockchainAPINode import api as api_blueprint app.register_blueprint(api_blueprint) # blueprint for auth routes in our app from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) # blueprint for non-auth parts of app from .main import main as main_blueprint app.register_blueprint(main_blueprint) with app.app_context(): db.create_all() return app
def create_app(test_config=None): app = Flask(__name__, instance_relative_config=True) app.ma = Marshmallow(app) try: os.makedirs(app.instance_path) except OSError: pass # Getting config options - this should eventually be in it's own class FLASK_SECRET_KEY = config('FLASK_SECRET_KEY') pss_db_type = config('pss_db_type', default='postgres') pss_db_name = config( 'pss_db_name') if test_config is None else test_config['pss_db_name'] pss_db_username = config('db_username') pss_db_password = config('db_password') # The CORS module is needed because the backend runs on port 8000 # and the html/javascript is retreived from port 80/443. The CORS # module makes sure the browser/native app doesn't puke with cross site # scripting errors when ajax requests are made. CORS( app, allow_headers=['Content-Type', 'Accept'], vary_header=False, #send_wildcard=False, supports_credentials=True) app.db_helper = DbHelper(pss_db_type, pss_db_username, pss_db_password, pss_db_name) db_handle = app.db_helper.create_db_handle(app) LoginManager().init_app(app) principals = Principal(app) principal_identity_funcs.generate_pss_user_loader(app) principal_identity_funcs.generate_pss_user_identity_loaded(app) app.register_blueprint(blueprints.event_bp) app.json_encoder = CustomJSONEncoder app.before_request(generate_extract_request_data(app)) app.error_handler_spec[None] = {} for code in default_exceptions: app.register_error_handler(code, make_json_error) app.config['DEBUG'] = True app.config['SECRET_KEY'] = FLASK_SECRET_KEY return app
def create_app(app_name, config_obj, api_prefix='/api/v1'): """ Generates and configures the main application.""" # Launching application app = Flask(app_name) # So the engine would recognize the root package with app.app_context(): # Load Configuration app.config.from_object(config_obj) # Loading assets assets = Environment(app) assets.from_yaml('assets.yaml') app.assets = assets # Initializing bcrypt password encryption bcrypt = Bcrypt(app) app.bcrypt = bcrypt # Initializing Database db = SQLAlchemy(app) app.db = db # Initializing login manager login_manager = LoginManager() login_manager.login_view = app.config.get('LOGIN_VIEW', '.login') login_manager.session_protection = 'strong' login_manager.init_app(app) app.login_manager = login_manager # Initializing principal manager app.principal = Principal(app) # Initializing Alembic alembic = Alembic() alembic.init_app(app) app.alembic = alembic api = Api(app, prefix=api_prefix) app.api = api # include an api_registry to the application app.api_registry = [ ] # a simple list holding the values to be registered return app
def app(base_app, es, database): """Invenio application with database and Elasticsearch. Scope: module See also :py:data:`base_app` for an Invenio application fixture that does not initialize database and Elasticsearch. """ Security(base_app) InvenioAccess(base_app) LoginManager(base_app) Principal(base_app) login_manager = LoginManager() login_manager.init_app(base_app) yield base_app
def register(self, app, *args, **kwargs): " Activate loginmanager and principal. " if not self._login_manager or self.app != app: self._login_manager = LoginManager() self._login_manager.user_callback = self.user_loader self._login_manager.setup_app(app) self._login_manager.login_view = 'urls.index' self._login_manager.login_message = u'You need to be signed in for this page.' self.app = app if not self._principal: self._principal = Principal(app) identity_loaded.connect(self.identity_loaded) super(UserManager, self).register(app, *args, **kwargs)
def create_app(self): app = super(PrincipalTestCase, self).create_app() app.test_client_class = AuthorizedApiClient self.principal = Principal(app) self.sa = sa = SQLAlchemy(app) class User(sa.Model): id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.String()) class BookStore(sa.Model): id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.String()) owner_id = sa.Column(sa.Integer, sa.ForeignKey(User.id)) owner = sa.relationship(User, backref=backref('stores', lazy='dynamic')) class Book(sa.Model): id = sa.Column(sa.Integer, primary_key=True) title = sa.Column(sa.String(), nullable=False) author_id = sa.Column(sa.Integer, sa.ForeignKey(User.id)) author = sa.relationship(User, backref=backref('books', lazy='dynamic')) class BookSigning(sa.Model): id = sa.Column(sa.Integer, primary_key=True) book_id = sa.Column(sa.Integer, sa.ForeignKey(Book.id), nullable=False) store_id = sa.Column(sa.Integer, sa.ForeignKey(BookStore.id), nullable=False) book = sa.relationship(Book) store = sa.relationship(BookStore) sa.create_all() for model in (BookStore, User, Book, BookSigning): setattr(self, model.__tablename__.upper(), model) return app
def get_generic_app(name): app = Flask(name) app.json_encoder = CustomJSONEncoder #app.config['UPLOAD_FOLDER']='/var/www/html/pics' app.config['UPLOAD_FOLDER'] = os.getenv('UPLOAD_FOLDER', None) app.config['DEBUG'] = True td_config.assign_loaded_configs_to_app(app) principals = Principal(app) app.my_principals = principals app.register_error_handler(BadRequest, lambda e: 'bad request!') CORS( app, headers=['Content-Type', 'Accept'], send_wildcard=False, supports_credentials=True, ) return app
def AccessToken(app): try: if not app.secret_key: app.secret_key = os.environ['FLASK_SECRET_KEY'] except KeyError: print("app.secret_key or FLASK_SECRET_KEY environ variable should be defined") # add _require_access_token decorator into /<repo>/* urls app.add_url_rule("/invitation", "invitation", view_func=_InvitationView.as_view('invitation')) # A hack to move /invitation url rule before /<repo> url rule invt_rule = app.url_map._rules.pop() app.url_map._rules.insert(0, invt_rule) app.url_map._remap = True app.url_map.update() Principal(app) app.before_request(_on_before_request_access_token) identity_loaded.connect_via(app)(_on_identity_loaded)
def app(appconfig, initialized_db): """ Used by pytest-flask plugin to inject a custom app instance for testing. """ app = Flask(__name__) login_manager = LoginManager(app) @app.errorhandler(model.DataModelException) def handle_dme(ex): response = jsonify({"message": str(ex)}) response.status_code = 400 return response @login_manager.user_loader def load_user(user_uuid): return LoginWrappedDBUser(user_uuid) @identity_loaded.connect_via(app) def on_identity_loaded_for_test(sender, identity): on_identity_loaded(sender, identity) Principal(app, use_sessions=False) app.url_map.converters["regex"] = RegexConverter app.url_map.converters["apirepopath"] = APIRepositoryPathConverter app.url_map.converters["repopath"] = RepositoryPathConverter app.url_map.converters[ "repopathredirect"] = RepositoryPathRedirectConverter app.url_map.converters[ "v1createrepopath"] = V1CreateRepositoryPathConverter app.register_blueprint(api_bp, url_prefix="/api") app.register_blueprint(appr_bp, url_prefix="/cnr") app.register_blueprint(web, url_prefix="/") app.register_blueprint(v1_bp, url_prefix="/v1") app.register_blueprint(v2_bp, url_prefix="/v2") app.register_blueprint(webhooks, url_prefix="/webhooks") app.config.update(appconfig) Userfiles(app) Mail(app) return app
def app(base_app): """Flask application fixture.""" base_app._internal_jsonschemas = InvenioJSONSchemas(base_app) InvenioREST(base_app) InvenioRecordsREST(base_app) InvenioRecords(base_app) InvenioPIDStore(base_app) base_app.url_map.converters['pid'] = PIDConverter SampleExt(base_app) OARepoMappingIncludesExt(base_app) LoginManager(base_app) Permission(base_app) InvenioAccess(base_app) Principal(base_app) OARepoValidate(base_app) Actions(base_app) base_app.register_blueprint( invenio_records_rest.views.create_blueprint_from_app(base_app)) login_manager = LoginManager() login_manager.init_app(base_app) login_manager.login_view = 'login' @login_manager.user_loader def basic_user_loader(user_id): user_obj = User.query.get(int(user_id)) return user_obj @base_app.route('/test/login/<int:id>', methods=['GET', 'POST']) def test_login(id): print("test: logging user with id", id) response = make_response() user = User.query.get(id) login_user(user) set_identity(user) return response app_loaded.send(None, app=base_app) with base_app.app_context(): yield base_app
def __init__(self, repo, db_uri=None, debug=None, config=None, **kwargs): Flask.__init__(self, __name__, template_folder='templates', static_folder='static') # Add unique identifier for this application isinstance self.uuid = str(uuid.uuid4()) if 'KNOWLEDGE_REPO_MASTER_UUID' not in os.environ: os.environ['KNOWLEDGE_REPO_MASTER_UUID'] = self.uuid # Preload default configuration self.config.from_object('knowledge_repo.app.config_defaults') # Load configuration from file or provided object if config: if isinstance(config, str): config = imp.load_source('knowledge_server_config', os.path.abspath(config)) self.config.from_object(config) # Add configuration passed in as keyword arguments self.config.update(kwargs) # Prepare repository, and add it to the app if hasattr(config, 'prepare_repo'): repo = config.prepare_repo(repo) self.repository = repo assert isinstance(self.repository, knowledge_repo.KnowledgeRepository), "Invalid repository object provided." # Set debug mode from kwargs or else maintain current setting if debug is not None: self.config['DEBUG'] = debug # Set the secret key for this instance (creating one if one does not exist already) self.config['SECRET_KEY'] = self.config['SECRET_KEY'] or str(uuid.uuid4()) # Configure database if db_uri: self.config['SQLALCHEMY_DATABASE_URI'] = db_uri logger.debug(u"Using database: {}".format(self.config['SQLALCHEMY_DATABASE_URI'])) # Register database schema with flask app sqlalchemy_db.init_app(self) # Set up database migration information # Registers Migrate plugin in self.extensions['migrate'] Migrate(self, self.db) # Try to create the database if it does not already exist # Existence is determined by whether there is an existing alembic migration revision db_auto_create = self.config.get('DB_AUTO_CREATE', True) db_auto_upgrade = self.config.get('DB_AUTO_UPGRADE', True) if db_auto_create and self.db_revision is None: self.db_init() elif db_auto_upgrade: self.db_upgrade() # Initialise login manager to keep track of user sessions LoginManager().init_app(self) self.login_manager.login_view = 'auth.login' self.login_manager.anonymous_user = AnonymousKnowledgeUser @self.login_manager.user_loader def load_user(user_id): return User(identifier=user_id) # Attempt login via http headers if self.config.get('AUTH_USE_REQUEST_HEADERS'): @self.login_manager.request_loader def load_user_from_request(request): user_attributes = current_app.config.get('AUTH_MAP_REQUEST_HEADERS')(request.headers) if isinstance(user_attributes, dict) and user_attributes.get('identifier', None): user = User(identifier=user_attributes['identifier']) user.can_logout = False for attribute in ['avatar_uri', 'email', 'name']: if user_attributes.get(attribute): setattr(user, attribute, user_attributes[attribute]) user = prepare_user(user, session_start=False) return user elif self.config.get('AUTH_USER_IDENTIFIER_REQUEST_HEADER'): logger.warning("AUTH_USER_IDENTIFIER* configuration keys are deprecated and will be removed in v0.9.0 .") @self.login_manager.request_loader def load_user_from_request(request): identifier = request.headers.get(current_app.config['AUTH_USER_IDENTIFIER_REQUEST_HEADER']) if identifier: if current_app.config['AUTH_USER_IDENTIFIER_REQUEST_HEADER_MAPPING']: identifier = current_app.config['AUTH_USER_IDENTIFIER_REQUEST_HEADER_MAPPING'](identifier) user = User(identifier=identifier) user.can_logout = False user = prepare_user(user, session_start=False) return user # Intialise access policies self.principal = Principal(self) # Add AnonymousIdentity fallback so that on_identity_loaded is called for # anonymous users too. self.principal.identity_loaders.append(lambda: AnonymousIdentity()) # Synchronise user permissions with data model @user_loaded_from_request.connect def on_user_loaded_from_request(sender, user): self.principal.set_identity(Identity(user.id)) @identity_loaded.connect_via(self) def on_identity_loaded(sender, identity): populate_identity_roles(identity, user=current_user) @self.errorhandler(PermissionDenied) def handle_insufficient_permissions(error): session['requested_url'] = request.url return render_template('permission_denied.html'), 403 # Add mail object if configuration is supplied if self.config.get('MAIL_SERVER'): self.config['mail'] = Mail(self) # Register routes to be served self.register_blueprint(routes.posts.blueprint) self.register_blueprint(routes.health.blueprint) self.register_blueprint(routes.index.blueprint) self.register_blueprint(routes.tags.blueprint) self.register_blueprint(routes.vote.blueprint) self.register_blueprint(routes.comment.blueprint) self.register_blueprint(routes.stats.blueprint) self.register_blueprint(routes.editor.blueprint) self.register_blueprint(routes.groups.blueprint) self.register_blueprint(routes.auth.blueprint) KnowledgeAuthProvider.register_auth_provider_blueprints(self) if self.config['DEBUG']: self.register_blueprint(routes.debug.blueprint) # Register error handler @self.errorhandler(500) def show_traceback(self): """ If LOCAL MODE: show the stack trace on a server error otherwise show a nice error template to the users """ if current_app.config.get("DEBUG"): return render_template('traceback.html', info=traceback.format_exc()), 500 else: return render_template('error.html') @self.before_first_request def ensure_excluded_tags_exist(): # For every tag in the excluded tags, create the tag object if it doesn't exist excluded_tags = current_app.config['EXCLUDED_TAGS'] for tag in excluded_tags: Tag(name=tag) db_session.commit() # Set up indexing timers set_up_indexing_timers(self) @self.before_request def open_repository_session(): if not request.path.startswith('/static'): current_repo.session_begin() @self.after_request def close_repository_session(response): if not request.path.startswith('/static'): current_repo.session_end() return response @self.context_processor def webediting_enabled(): # TODO: Link this more to KnowledgeRepository capability and # configuration rather than a specific name. return {"webeditor_enabled": 'webposts' in current_repo.uris} @self.context_processor def inject_version(): version = knowledge_repo.__version__ version_revision = None if '_' in knowledge_repo.__version__: version, version_revision = version.split('_') return dict(version=version, version_revision=version_revision, last_index=time_since_index(human_readable=True), last_index_check=time_since_index_check(human_readable=True)) @self.template_global() def modify_query(**new_values): args = request.args.copy() for key, value in new_values.items(): args[key] = value return u'{}?{}'.format(request.path, url_encode(args)) @self.template_global() def pagination_pages(current_page, page_count, max_pages=5, extremes=True): page_min = int(max(1, current_page - math.floor(1.0 * max_pages // 2))) page_max = int(min(page_count, current_page + math.floor(1.0 * max_pages / 2))) to_acquire = max_pages - (page_max - page_min + 1) while to_acquire > 0 and page_min > 1: page_min -= 1 to_acquire -= 1 while to_acquire > 0 and page_max < page_count: page_max += 1 to_acquire -= 1 pages = list(range(page_min, page_max + 1)) if extremes: if 1 not in pages: pages[0] = 1 if page_count not in pages: pages[-1] = page_count return pages @self.template_filter('format_date') def format_date(date): """ This will be a Jinja filter that string formats a datetime object. If we can't correctly format, we just return the object. :type date: Datetime :return: A string of the format of YYYY-MM-DD :rtype: String """ try: return datetime.strftime(date, '%Y-%m-%d') except: return date
def mkapp(with_factory=False): app = Flask(__name__) app.secret_key = 'notverysecret' app.debug = True if with_factory: p = Principal() p.init_app(app) else: p = Principal(app) identity_loaded.connect(_on_principal_init) @app.route('/') def index(): with admin_permission.require(): pass return Response('hello') @app.route('/a') @admin_permission.require() def a(): return Response('hello') @app.route('/b') @anon_permission.require() def b(): return Response('hello') @app.route('/c') def c(): with anon_permission.require(): raise ReraiseException @app.route('/d') @anon_permission.require() def d(): raise ReraiseException @app.route('/e') def e(): i = mkadmin() identity_changed.send(app, identity=i) with admin_permission.require(): return Response('hello') @app.route('/f') def f(): i = mkadmin() identity_changed.send(app, identity=i) with admin_or_editor.require(): return Response('hello') @app.route('/g') @admin_permission.require() @editor_permission.require() def g(): return Response('hello') @app.route('/h') def h(): i = Identity('james') identity_changed.send(app, identity=i) with admin_permission.require(): with editor_permission.require(): pass @app.route('/j') def j(): i = Identity('james') identity_changed.send(app, identity=i) with admin_permission.require(403): with editor_permission.require(403): pass @app.route('/k') @admin_permission.require(403) def k(): return Response('hello') @app.route('/l') def l(): s = [] if not admin_or_editor: s.append("not admin") i = Identity('ali') identity_changed.send(app, identity=i) if admin_or_editor: s.append("now admin") return Response('\n'.join(s)) @app.route("/m") def m(): with admin_denied.require(): pass return Response("OK") @app.route("/n") def n(): i = mkadmin() identity_changed.send(app, identity=i) with admin_denied.require(): pass return Response("OK") @app.route("/o") def o(): admin_or_editor.test() return Response("OK") @app.route("/p") def p(): admin_or_editor.test(404) return Response("OK") return app
def register_principal(app): principal = Principal() principal.init_app(app)
def _get_principal(app): p = Principal(app, use_sessions=False) p.identity_loader(_identity_loader) return p
################ #### config #### ################ app = Flask(__name__) bcrypt = Bcrypt(app) login_manager = LoginManager() login_manager.init_app(app) app.config.from_object(os.environ['APP_SETTINGS']) db = SQLAlchemy(app) principals = Principal(app) principals._init_app(app) from project.users.views import users_blueprint from project.home.views import home_blueprint from project.home.views import guest_blueprint # register our blueprints app.register_blueprint(users_blueprint) app.register_blueprint(home_blueprint) app.register_blueprint(guest_blueprint) from models import User login_manager.login_view = "users.login"