def create_app(): app = flask.Flask(__name__) app.config.from_object('config') init_db(app) api.init_app(app) security = Security() security.init_app(app, users) principals = Principal() principals.init_app(app) configure_uploads(app, logos) from app.views import menu, bp menu.init_app(app) app.register_blueprint(bp) if False: login_manager = LoginManager(app) @login_manager.request_loader def load_user_from_request(request): if request.authorization: email, password = request.authorization.username, request.authorization.password user = User.query.filter_by(email=unicode(email)).first() if user is not None: if verify_password(password, user.password): return user @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)) @principals.identity_loader def read_identity_from_flask_login(): if current_user.is_authenticated(): return Identity(current_user.id) return AnonymousIdentity() return app
def configure_identity(app): Principal(app) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): g.user = User.query.from_identity(identity)
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) # extenral 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)
def init_identity(app): Principal(app) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): g.user = User.query.gen_identity(identity)
def init_app(self, app, datastore): """Initializes the Flask-Security extension for the specified application and datastore implentation. :param app: The application. :param datastore: An instance of a user datastore. """ if app is None or datastore is None: return # TODO: change blueprint name blueprint = Blueprint('auth', __name__) configured = {} for key, value in default_config.items(): configured[key] = app.config.get(key, value) app.config.update(configured) config = app.config # setup the login manager extension login_manager = LoginManager() login_manager.anonymous_user = AnonymousUser login_manager.login_view = config[LOGIN_VIEW_KEY] login_manager.setup_app(app) app.login_manager = login_manager Provider = get_class_from_config(AUTH_PROVIDER_KEY, config) Form = get_class_from_config(LOGIN_FORM_KEY, config) pw_hash = config[PASSWORD_HASH_KEY] app.pwd_context = CryptContext(schemes=[pw_hash], default=pw_hash) app.auth_provider = Provider(Form) app.principal = Principal(app) from flask.ext import security as s s.User, s.Role = datastore.get_models() setattr(app, config[USER_DATASTORE_KEY], datastore) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): if hasattr(current_user, 'id'): identity.provides.add(UserNeed(current_user.id)) for role in current_user.roles: identity.provides.add(RoleNeed(role.name)) identity.user = current_user @login_manager.user_loader def load_user(user_id): try: return datastore.with_id(user_id) except Exception, e: logger.error('Error getting user: %s' % e) return None
def configure_identity(app): Principal(app) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): identity.user = current_user if hasattr(current_user, 'roles'): for role in current_user.roles: identity.provides.add(RoleNeed(role.rolename))
def initialise_app(app, configclass): # Load the default configuration app.config.from_object(configclass) # Load the configuration from the instance folder try: app.config.from_pyfile('config.py') except: print 'No instance config file' if app.config['USE_PROXY']: app.wsgi_app = ProxyFix(app.wsgi_app) toolbar = DebugToolbarExtension(app) db.init_app(app) mail.init_app(app) assets = Environment(app) assets.register(bundles) from .models import User, Feed, Entry, Author, Role user_datastore = SQLAlchemyUserDatastore(db, User, Role) app.security = Security(app, user_datastore) wtf.add_helpers(app) admin = Admin(app, 'Admin', index_view=SecuredAdminIndexView()) admin.add_view(SecuredModelView(User, db.session)) admin.add_view(SecuredModelView(Feed, db.session)) admin.add_view(SecuredModelView(Entry, db.session)) admin.add_view(SecuredModelView(Author, db.session)) app.register_blueprint(frontend_blueprint) identity_loaded.connect_via(app)(on_identity_loaded) add_errorhandlers(app) Principal(app) if not app.debug: import logging from .utils.loggers import add_logger_filehandler, add_logger_external add_logger_filehandler(app) if app.config['LOG_ADDRESS']: add_logger_external(app) app.logger.setLevel(logging.INFO) app.logger.info(u'{0} startup'.format(app.config['PROJECT_NAME'])) return app
def init_app(app, url_prefix='/auth'): app.register_blueprint(bp, url_prefix=url_prefix) Principal(app) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): identity.user = current_user if not current_user.is_anonymous(): identity.provides.add(UserNeed(current_user.id)) if hasattr(current_user, 'role'): identity.provides.add(RoleNeed(current_user.role)) login_manager.init_app(app)
def init_app(acl, app, mtjacl_sessions=True, permission_denied_handler=handle_permission_denied, *a, **kw): # Not using the default session. principal = Principal(app, use_sessions=False, *a, **kw) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): if not isinstance(identity, AclIdentity): # Not doing anything on identities we don't care for. return # the identity is actually the raw token access_token = identity.access_token if access_token is None: user = anonymous else: user = acl.getUserFromAccessToken(access_token) # cache this value. g.mtj_user = user if user is anonymous: return roles = acl.getUserRoles(user) # TODO figure out how to do lazy loading of roles. for role in roles: identity.provides.add(RoleNeed(role)) identity.id = user.login if mtjacl_sessions: principal.identity_loader(acl_session_identity_loader) principal.identity_saver(acl_session_identity_saver) app.config['MTJ_ACL'] = acl if callable(permission_denied_handler): app.errorhandler(PermissionDenied)(permission_denied_handler) app.before_request(_on_before_request(acl))
def configure_identity(app): principal = Principal(app) @identity_loaded.connect_via(app) # @identity_changed.connect_via(app) def on_identity_loaded(sender, identity): print 'received from', str(sender) identity.user = g.user if hasattr(g.user, 'id'): identity.provides.add(UserNeed(g.user.id)) if hasattr(g.user, 'roles'): for role in g.user.roles: print role.name identity.provides.add(RoleNeed(role.name))
def create_app(self): app = Flask(__name__) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' # absolute path gets around annoying cwd difference here & in fixtures db_uri = "sqlite:///" + os.getcwd() + "/tests.db" app.config['SQLALCHEMY_DATABASE_URI'] = db_uri principals = Principal(app) from models import db db.init_app(app) self.db = db self.sync = Minisync(self.db) return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) login_manager.init_app(app) Principal(app) from .mod_auth import mod_auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') from .mod_index import mod_index as index_blueprint app.register_blueprint(index_blueprint) return app
def create_app(config={}): app = Flask(__name__, instance_relative_config=True) if not config: app.config.from_pyfile('settings.py') else: app.config.update(config) db.init_app(app) app.register_blueprint(views) app.secret_key = app.config['PRIVATE_KEY'] if app.config.get('SENTRY_DSN'): from raven.contrib.flask import Sentry Sentry(app) @app.errorhandler(403) def permission_denied(error): return render_template("denied.html"), 403 @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): if identity.id: user = User.query.get(identity.id) if user and user.is_admin: identity.provides.add(RoleNeed('admin')) login_manager = LoginManager() @login_manager.user_loader def load_user(userid): try: return User.query.get(userid) except: return None login_manager.setup_app(app) Principal(app) admin = Admin(app) admin.add_view(AdminModelView(User, db.session)) admin.add_view(AdminModelView(Project, db.session)) return app
def configure_extensions(app): # config Flask-SQLAlchemy db.app = app db.init_app(app) # config Flask-Login login.init_app(app) # config Flask-Principal principal = Principal(app) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): for permission in Permission.query.all(): for group in permission.groups: if hasattr(current_user, 'groups') and group in current_user.groups: identity.provides.add(AuthorizeNeed(permission.handler))
login_manager = LoginManager() login_manager.init_app(flask_framework) login_manager.login_view = 'login' login_manager.login_message = lazy_gettext( 'Please log in to access this page.') # OpenID service openID_service = OpenID(flask_framework, os.path.join(basedir, 'tmp')) mail = Mail(flask_framework) babel = Babel(flask_framework) ''' Flask - Principal ''' from flask.ext.principal import Principal, Permission, RoleNeed # load the extension principals = Principal(flask_framework) # Create a permission with a single Need, in this case a RoleNeed. comptroller_permission = Permission(RoleNeed('COMPT')) administrator_permission = Permission(RoleNeed('ADMIN')) ''' Exexcution Profiles ''' if not flask_framework.debug and MAIL_SERVER != '': import logging from logging.handlers import SMTPHandler credentials = None if MAIL_USERNAME or MAIL_PASSWORD: credentials = (MAIL_USERNAME, MAIL_PASSWORD) mail_handler = SMTPHandler( (MAIL_SERVER, MAIL_PORT), 'no-reply@' + MAIL_SERVER, [DEFAULT_MAIL_SENDER], 'microblog failure', credentials) mail_handler.setLevel(logging.ERROR)
app.config['LDAP_USER_LOGIN_ATTR'] = 'mail' # The Username to bind to LDAP with app.config['LDAP_BIND_USER_DN'] = None app.config['LDAP_GROUP_OBJECT_FILTER'] = '(objectclass=groupOfNames)' # The Password to bind to LDAP with app.config['LDAP_BIND_USER_PASSWORD'] = None app.config['LDAP_PORT'] = 10389 app.config['LDAP_HOST'] = 'localhost' mongo = PyMongo(app) csrf = CSRFProtect(app) login_manager = LoginManager(app) # Setup a Flask-Login Manager ldap_manager = LDAP3LoginManager(app) # Setup a LDAP3 Login Manager. Principal(app) # Create a dictionary to store the users in when they authenticate # This example stores users in memory. ldap_users = {} # Declare an Object Model for the user, and make it comply with the # flask-login UserMixin mixin. class User(UserMixin): def __init__(self, dn, username, data): self.dn = dn self.username = username self.data = data def __repr__(self):
identity_changed, identity_loaded, Permission, RoleNeed, UserNeed) from flask_restful import abort from sqlalchemy import exc from steerclear import login_manager, app from steerclear.utils import cas from steerclear.utils.permissions import (admin_permission, student_permission, AccessRideNeed) from forms import * from models import * # setup login blueprint login_bp = Blueprint('login', __name__) # setup flask-principal principal = Principal() principal.init_app(app) """ create_roles ------------ Function called before app processes first request. Creates the admin and student Roles if they do not already exist """ @app.before_first_request def create_roles(): # create student Role if Role.query.filter_by(name='student').first() is None: role = Role(name='student', description='Student Role')
from flask import flash, redirect, url_for, session from flask.ext.bcrypt import Bcrypt from flask.ext.openid import OpenID from flask_oauth import OAuth from flask.ext.login import LoginManager from flask.ext.principal import Principal, Permission, RoleNeed from flask.ext.restful import Api bcrypt = Bcrypt() oid = OpenID() oauth = OAuth() principals = Principal() admin_permission = Permission(RoleNeed('admin')) poster_permission = Permission(RoleNeed('poster')) default_permission = Permission(RoleNeed('default')) login_manager = LoginManager() login_manager.login_view = "main.login" login_manager.session_protection = "strong" login_manager.login_message = "Please login to access this page" login_manager.login_message_category = "info" rest_api = Api() @login_manager.user_loader def load_user(userid): from models import User return User.query.get(userid)
app.url_map.strict_slashes = False app.logger.addHandler(handler) db = SQLAlchemy(app) babel = Babel(app) oauth = OAuth() google = oauth.remote_app( 'google', base_url='https://www.google.com/accounts/', authorize_url='https://accounts.google.com/o/oauth2/auth', request_token_url=None, request_token_params={ 'scope': 'openid profile email', 'response_type': 'code' }, access_token_url='https://accounts.google.com/o/oauth2/token', access_token_method='POST', access_token_params={'grant_type': 'authorization_code'}, consumer_key=app.config['GOOGLE_CLIENT_ID'], consumer_secret=app.config['GOOGLE_CLIENT_SECRET'] ) principal = Principal(app) lm = LoginManager(app) import jeto.core import jeto.controllers from jeto.models import * from jeto.services import *
from app import GisApp, db from flask.ext.principal import Principal, Permission, ActionNeed, identity_loaded, UserNeed, identity_changed, Identity, AnonymousIdentity principals = Principal(GisApp) permissions = {} action_permissions = GisApp.config.get('ACTION_PERMISSIONS') for action_permission in action_permissions: permissions[action_permission] = Permission(ActionNeed(action_permission)) locals().update(permissions)
def init_login(): login_manager = LoginManager() login_manager.login_view = "/login/" login_manager.init_app(app) @login_manager.user_loader def load_user(user_id): from lightningwolf_smp.models import User return db.session.query(User).get(user_id) init_login() # Flask-Principal Principal(app, skip_static=True) # Needs admin_need = RoleNeed('admin') user_need = RoleNeed('user') # Permissions user_permission = Permission(user_need) user_permission.description = "User permission" admin_permission = Permission(admin_need) admin_permission.description = "Admin permission" app_needs = {'admin': admin_need, 'user': user_need} app_permissions = {'user': user_permission, 'admin': admin_permission}
def _get_principal(app): p = Principal(app, use_sessions=False) p.identity_loader(_identity_loader) return p
def create_app(app_name, config_obj, with_api=True): """ Generates and configures the main shop application. All additional """ # Launching application app = Flask(app_name) # So the engine would recognize the root package # Load Configuration app.config.from_object(config_obj) # Loading assets assets = Environment(app) assets.from_yaml('assets.yaml') app.assets = assets # Initialize Mail app.mail = Mail(app) # Initializing login manager login_manager = LoginManager() login_manager.login_view = app.config.get('LOGIN_VIEW', 'main.index') # login_manager.login_message = 'You need to be logged in to access this page' login_manager.session_protection = 'strong' login_manager.setup_app(app) app.login_manager = login_manager # Initializing principal manager app.principal = Principal(app) # Initializing bcrypt password encryption bcrypt = Bcrypt(app) app.bcrypt = bcrypt # Initializing Database db = SQLAlchemy(app) app.db = db # Initializing Migrate migrate = Migrate(app, db, "from fitted.models import *") app.migrate = migrate photos = UploadSet('photos', IMAGES) archives = UploadSet('archives', ARCHIVES) configure_uploads(app, (photos, archives)) patch_request_class(app, 2 * 1024 * 1024) # Patches to 2MB file uploads max. app.photos = photos app.archives = archives # Integrate Elasticsearch es_config = app.config.get("ES_CONFIG", []) app.es = Elasticsearch(es_config) # Integrate sms with Twilio app.sms = TwilioRestClient(app.config.get("TWILIO_API_SID"), app.config.get("TWILIO_API_TOKEN")) # Redis store for session management # The process running Flask needs write access to this directory: # store = RedisStore(redis.StrictRedis()) # # this will replace the app's session handling # KVSessionExtension(store, app) # configure sentry # if not app.config.get("DEBUG", False): # sentry = Sentry(app) # app.sentry = sentry # inject celery into the app app.celery = make_celery(app) # injecting mongodb support # app.mongo = PyMongo(app) # flask s3 integration app.s3 = FlaskS3(app) # Facebook & Twitter Integration app.facebook = oauth.remote_app('facebook', app_key='FACEBOOK') oauth.init_app(app) # Initializing the restful API if with_api: api = restful.Api(app, prefix='/api/v1') app.api = api # Initialize Logging if not app.debug: import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler( "/var/log/fitted/%s.log" % app.config.get("LOGFILE_NAME", app_name), maxBytes=500 * 1024) file_handler.setLevel(logging.WARNING) from logging import Formatter file_handler.setFormatter( Formatter('%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]')) app.logger.addHandler(file_handler) #include an api_registry to the application app.api_registry = [] #a simple list holding the values to be registered return app
from .. import app from .models import Role blueprint_name = 'auth' bp = Blueprint(blueprint_name, __name__, static_folder='static', static_url_path='/' + blueprint_name + '/static', template_folder='templates') roles = {} def register_role(model, dashboard_view_context_func): if not issubclass(model, Role): raise TypeError("Can only register subclasses of auth.models.Role!") # Allow roles to be overriden by later registrations roles[model.role_name()] = {'model': model, 'dashboard': dashboard_view_context_func} login_manager = LoginManager() with app.app_context(): login_manager.init_app(current_app) # Must be initialized after LoginManager # Don't use sessions as goal is to have the Flask end be a stateless API # Skip static as it shouldn't have anything sensitive principal = Principal(current_app, use_sessions=False, skip_static=True) # For some bizarre reason this isn't getting set properly, even though there is no 'LOGIN_REQUIRED' config variable, so do it manually login_manager._login_disabled = False from . import views
# -*- coding: utf-8 -*- from flask import session from flask.ext.principal import Principal from flask.ext.principal import Permission, RoleNeed, Identity from amc.models import UserModel # 这里设成False让默认的session格式来获取当前identity信息功能disable # 然后利用identity_loader从flask-login的session获取自定义的identity principal = Principal(use_sessions=False) panel_permission = Permission(RoleNeed('panel')) @principal.identity_loader def current_user_identity(): if not session.get('user_id'): return None user_id = session['user_id'] identity = Identity(user_id) user = UserModel.query.get(user_id) if user and user.is_admin: identity.provides.add(RoleNeed('panel')) return identity
def create_app(): app = flask.Flask(__name__) app.config.from_object("config") init_db(app) api.init_app(app) security = Security() security.init_app(app, users) principals = Principal() principals.init_app(app) configure_uploads(app, logos) from app.views import menu, bp from app.signals import init_signals init_signals(app) menu.init_app(app) app.register_blueprint(bp) if False: login_manager = LoginManager(app) @login_manager.request_loader def load_user_from_request(request): if request.authorization: email, password = request.authorization.username, request.authorization.password user = User.query.filter_by(email=unicode(email)).first() if user is not None: if verify_password(password, user.password): return user @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)) @principals.identity_loader def read_identity_from_flask_login(): if current_user.is_authenticated(): return Identity(current_user.id) return AnonymousIdentity() @app.after_request def somefunc(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
from flask import (render_template, flash, session, request, url_for, redirect, current_app) from flask.ext.babel import gettext from flask.ext.login import LoginManager, logout_user, \ login_required, current_user from flask.ext.principal import (Principal, AnonymousIdentity, UserNeed, identity_changed, identity_loaded, session_identity_loader) from bootstrap import conf from web.views.common import admin_role, api_role, login_user_bundle from web.controllers import UserController from web.forms import SignupForm, SigninForm from rauth import OAuth1Service, OAuth2Service Principal(current_app) # Create a permission with a single Need, in this case a RoleNeed. login_manager = LoginManager() login_manager.init_app(current_app) login_manager.login_view = 'login' logger = logging.getLogger(__name__) @identity_loaded.connect_via(current_app._get_current_object()) def on_identity_loaded(sender, identity): # Set the identity user object identity.user = current_user # Add the UserNeed to the identity
def get_principals(app): p = Principal(app) p.identity_loader(load_identity) return p
from flask.ext.login import LoginManager from flask.ext.principal import Principal, Permission, RoleNeed from flask.ext.restful import Api from wfdb.models import User login_manager = LoginManager() login_manager.login_view = "main.login" principal = Principal() admin_permission = Permission(RoleNeed('admin')) default_permission = Permission(RoleNeed('default')) rest_api = Api() @login_manager.user_loader def load_user(userid): return User.query.get(userid)
from flask import Flask, render_template from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager, current_user from flask.ext.principal import (Principal, Permission, identity_loaded, RoleNeed, UserNeed) app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) login_manager = LoginManager() login_manager.setup_app(app) principals = Principal(app) admin_permission = Permission(RoleNeed('admin')) from app.users.models import Users def comma_format(value): return "{:,.0f}".format(value) app.jinja_env.filters['comma_format'] = comma_format @login_manager.user_loader def load_user(userid): return Users.by_id(userid)
'flask_debugtoolbar.panels.profiler.ProfilerDebugPanel', # Add the MongoDB panel 'flask_debugtoolbar_mongo.panel.MongoDebugPanel', ] app.secret_key = 'secureKey' app.config["SECRET_KEY"] = "secureKey" app.debug=True db = MongoEngine(app) tool = DebugToolbarExtension(app) thumb = Thumbnail(app) principals = Principal(app) normal_role = RoleNeed('normal') normal_permission = Permission(normal_role) admin_role = RoleNeed('admin') admin_permission = Permission(admin_role) principals._init_app(app) # # User Information providers # @identity_loaded.connect_via(app) # def on_identity_loaded(sender, identity): # user = Usuario.objects.get(perfil=identity) lm = LoginManager() lm.login_view = "login" lm.login_message = u"Es necesario que este registrado para acceder."
app.config['SQLALCHEMY_DATABASE_URI']='mysql://root:@127.0.0.1/flask' db.init_app(app) #with app.test_request_context(): # load_db(db) login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def user_loader(username): return user.query.filter_by(username=username).first() principal = Principal() principal.init_app(app) administrator_permission = Permission(RoleNeed('administrator')) team_member_permission = Permission(RoleNeed('team member')) project_manager_permission = Permission(RoleNeed('project manager')) client_permission = Permission(RoleNeed('client')) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): identity.user = current_user if hasattr(current_user, 'rolename'): identity.provides.add(RoleNeed(current_user.rolename)) class UserSchema(Schema):
from libraries.graphLib.graphe_tbc import GraphTBC #Create Flask app server = Flask(__name__) # Import Config server.config.from_pyfile('../server.config') # SQLAlchemy db = SQLAlchemy(server) # Celery celery = make_celery(server) # Graphe G = GraphTBC() from project.libraries.celeryLib.tasks import * # FlaskLogin login_manager = LoginManager(server) # FlaskPrincipal Principal(server) # FlaskGCM clientGCM = FlaskGCM(server) # FlaskAPNS clientAPNS = FlaskAPNS(server)