Esempio n. 1
1
def unauthorized_redirect(app):
    lm = LoginManager()
    lm.login_view = "login"
    lm.setup_app(app)
    res = lm.unauthorized()
    assert res.headers["Location"] == "/login?next=%2F"
    assert LOGIN_MESSAGE in get_flashed_messages()
Esempio n. 2
0
def login_message(app):
    lm = LoginManager()
    lm.login_view = "login"
    lm.login_message = u"Log in or the owl will eat you."
    lm.setup_app(app)
    lm.unauthorized()
    assert u"Log in or the owl will eat you." in get_flashed_messages()
Esempio n. 3
0
def login_message(app):
    lm = LoginManager()
    lm.login_view = "login"
    lm.login_message = u"Log in or the owl will eat you."
    lm.setup_app(app)
    lm.unauthorized()
    assert u"Log in or the owl will eat you." in get_flashed_messages()
Esempio n. 4
0
class CApp(flask.Flask):
    """
    Main Crossco app. Made singleton to force one instance per server.
    """
    __metaclass__ = Singleton
    def __init__(self, import_name='', static_path=None, static_url_path=None,
                 static_folder='static', template_folder='templates',
                 instance_path=None, instance_relative_config=False):
        flask.Flask.__init__(self, import_name,
                                     static_path=static_path,
                                     static_url_path=static_url_path,
                                     static_folder=static_folder,
                                     template_folder=template_folder,
                                     instance_path=instance_path,
                                     instance_relative_config=instance_relative_config
                                     )
        self.config.update(config)
        self.db = flask.ext.sqlalchemy.SQLAlchemy(self)
        self.fb = OAuth().remote_app('facebook',
                base_url='https://graph.facebook.com/',
                request_token_url=None,
                access_token_url='/oauth/access_token',
                authorize_url='https://www.facebook.com/dialog/oauth',
                consumer_key=self.config['FACEBOOK_APP_ID'],
                consumer_secret=self.config['FACEBOOK_APP_SECRET'],
                request_token_params={'scope': 'email,manage_pages'})
        self.api_manager = APIManager(self, flask_sqlalchemy_db=self.db)
        self.login_manager = LoginManager()
        self.login_manager.setup_app(self)

    def run(self, host=None, port=None, debug=None, **options):
        self.db.create_all()
        flask.Flask.run(self, host, port, debug, **options)
Esempio n. 5
0
def unauthorized_redirect(app):
    lm = LoginManager()
    lm.login_view = "login"
    lm.setup_app(app)
    res = lm.unauthorized()
    assert res.headers["Location"] == "/login?next=%2F"
    assert LOGIN_MESSAGE in get_flashed_messages()
Esempio n. 6
0
File: run.py Progetto: DianQ/MyCode
def configure_login(app):
    lm = LoginManager()
    lm.setup_app(app)

    @lm.user_loader
    def load_user(userid):
        return UserDAO.get(userid)
Esempio n. 7
0
def create_app():
    global db

    app = Flask(__name__)

    app.config.from_object(wemedia.settings)

    db = DB(app)

    setup_blueprints(app)
    setup_logger(app)

    # 登录管理器
    login_manager = LoginManager()
    login_manager.setup_app(app)
    login_manager.login_view = 'Common.login'
    login_manager.login_message = u'请登录'

    @login_manager.user_loader
    def load_user(userid):
        from wemedia.common.models import User

        user = User.query.get(userid)

        return user

    return app
Esempio n. 8
0
File: app.py Progetto: lbx6z-2/youmu
def configure_extensions(app):
    # TODO config extensions

    # flask-sqlalchemy
    # db.init_app(app)

    # flask-mail
    # mail.init_app(app)

    # flask-cache
    # cache.init_app(app)

    # flask-babel
    # babel = Babel(app)

    # @babel.localeselector
    # def get_locale():
    #     accept_languages = app.config.get('ACCEPT_LANGUAGES')
    #     return request.accept_languages.best_match(accept_languages)

    # flask-login
    login_manager = LoginManager()

    @login_manager.user_loader
    def load_user(id):
        return UserService.load_user_by_id(id)

    login_manager.setup_app(app)
    def __init__(self, app, user_repository):
        self.user_repository = user_repository

        login_manager = LoginManager()
        login_manager.user_loader(self.user_repository.get_by_username)
        login_manager.setup_app(app)

        self.login_manager = login_manager
Esempio n. 10
0
def init_login_manager(app):
    login_manager = LoginManager()
    login_manager.login_view = "auth.login"
    login_manager.setup_app(app)

    @login_manager.user_loader
    def load_user(userid):
        return User(userid)
Esempio n. 11
0
    def __init__(self, app, user_repository):
        self.user_repository = user_repository

        login_manager = LoginManager()
        login_manager.user_loader(self.user_repository.get_by_username)
        login_manager.setup_app(app)

        self.login_manager = login_manager
Esempio n. 12
0
def setup_interactive(app):
    lm = LoginManager()
    lm.login_view = "login"
    lm.user_loader(get_user)
    @lm.unauthorized_handler
    def unauth():
        return "UNAUTHORIZED!"
    lm.setup_app(app)
Esempio n. 13
0
    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
Esempio n. 14
0
    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
Esempio n. 15
0
def unauthorized_callback(app):
    lm = LoginManager()
    lm.login_view = "login"
    @lm.unauthorized_handler
    def unauth():
        return "UNAUTHORIZED!"
    lm.setup_app(app)
    assert lm.unauthorized() == "UNAUTHORIZED!"
    assert len(get_flashed_messages()) == 0
Esempio n. 16
0
def setup_authentication(app):
    login_manager = LoginManager()
    login_manager.setup_app(app)
    login_manager.login_view = '/login'
    user_service = UserService()
    
    @login_manager.user_loader
    def load_user(userId):
        user = user_service.get_user(user_id=userId)
        return user        
Esempio n. 17
0
def setup_interactive(app):
    lm = LoginManager()
    lm.login_view = "login"
    lm.user_loader(get_user)

    @lm.unauthorized_handler
    def unauth():
        return "UNAUTHORIZED!"

    lm.setup_app(app)
Esempio n. 18
0
def setup_authentication(app):
    login_manager = LoginManager()
    login_manager.setup_app(app)
    login_manager.login_view = '/login'
    user_service = UserService()

    @login_manager.user_loader
    def load_user(userId):
        user = user_service.get_user(user_id=userId)
        return user
Esempio n. 19
0
def create_app():
    app = Flask(__name__)

    # config
    if os.getenv('DEV') == 'yes':
        app.config.from_object('config.DevelopmentConfig')
        app.logger.info("Config: Development")
    elif os.getenv('TEST') == 'yes':
        app.config.from_object('config.TestConfig')
        app.logger.info("Config: Test")
    else:
        app.config.from_object('config.ProductionConfig')
        app.logger.info("Config: Production")

    db.init_app(app)

    ## register views
    from views import weight_pages
    app.register_blueprint(weight_pages)

    @app.context_processor
    def context_processor():
        """Add variables to context
        """
        if hasattr(current_user, '_user'):
            curuser = current_user._user
        else:
            # if user is not logged in
            curuser = ""

        return {'today': datetime.date.today,
                'user':curuser,
                }

    app.register_error_handler(401, error401)
    app.register_error_handler(404, error404)
    app.register_error_handler(500, error500)

    app.jinja_env.filters['year'] = format_year

    # flask-login
    login_manager = LoginManager()
    login_manager.setup_app(app)
    login_manager.login_view = ".login"
    
    @login_manager.user_loader
    def load_user(user):
        from models import User
        u1 = User.query.get(user)
        if u1:
            return DbUser(user)
        else:
            return None

    return app
Esempio n. 20
0
def unauthorized_callback(app):
    lm = LoginManager()
    lm.login_view = "login"

    @lm.unauthorized_handler
    def unauth():
        return "UNAUTHORIZED!"

    lm.setup_app(app)
    assert lm.unauthorized() == "UNAUTHORIZED!"
    assert len(get_flashed_messages()) == 0
Esempio n. 21
0
def logging_in(app):
    lm = LoginManager()
    lm.login_view = "login"
    lm.user_loader(get_user)
    lm.setup_app(app)
    app.preprocess_request()
    assert not current_user.is_authenticated()
    assert current_user.is_anonymous()
    with assert_fired(user_logged_in):
        login_user(notch)
    assert current_user.name == u"Notch"
    assert session["user_id"] == u"1"
Esempio n. 22
0
def logging_in(app):
    lm = LoginManager()
    lm.login_view = "login"
    lm.user_loader(get_user)
    lm.setup_app(app)
    app.preprocess_request()
    assert not current_user.is_authenticated()
    assert current_user.is_anonymous()
    with assert_fired(user_logged_in):
        login_user(notch)
    assert current_user.name == u"Notch"
    assert session["user_id"] == u"1"
Esempio n. 23
0
def configure(state):
    app = state.app
    
    login_manager = LoginManager()
    login_manager.setup_app(app)

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    @login_manager.unauthorized_handler
    def unauthorized():
        return redirect(url_for('users.login'))
Esempio n. 24
0
   def setup_login(self, app):
      login_manager = LoginManager()
      login_manager.login_view = BasicLoginView.PATH 
      login_manager.login_message = LoginViews.SUCCESSFUL_LOGIN_MSG 

      @login_manager.user_loader
      def load_user(userID):
         return user.User.get(userID)
      
      @login_manager.unauthorized_handler
      def unauthorized():
         return redirect(BasicLoginView.PATH) 
      login_manager.setup_app(app)
Esempio n. 25
0
    def init_app(self, app):        
        if app is None: return
        
        blueprint = Blueprint(AUTH_CONFIG_KEY.lower(), __name__)
        
        config = default_config.copy()
        try: config.update(app.config.get(AUTH_CONFIG_KEY, {}))
        except: pass
        app.config[AUTH_CONFIG_KEY] = config
        
        app.logger.debug("Auth Configuration: %s" % config)
        
        # setup the login manager extension
        login_manager = LoginManager()
        login_manager.anonymous_user = Anonymous
        login_manager.login_view = config[LOGIN_VIEW_KEY]
        login_manager.setup_app(app)
            
        # get some things form the config
        Provider = get_class_from_config(AUTH_PROVIDER_KEY, config)
        Encryptor = get_class_from_config(PASSWORD_ENCRYPTOR_KEY, config)
        Form = get_class_from_config(LOGIN_FORM_CLASS_KEY, config)
        
        # create the service and auth provider and add it to the app
        # so it can be referenced elsewhere
        app.login_manager = login_manager
        app.password_encryptor = Encryptor(config[SALT_KEY])
        app.auth_provider = Provider(Form)
        
        DEBUG_LOGIN = '******'
        DEBUG_XHR_LOGIN = '******'
        ERROR_LOGIN = '******'
        DEBUG_LOGOUT = 'User logged out, redirecting to: %s'
        FLASH_INACTIVE = 'Inactive user'
        
        @login_manager.user_loader
        def load_user(id):
            try: 
                user = user_service.get_user_with_id(id)
                # check if the password matches encryptor pattern
                if not current_app.password_encryptor.matches_encryption_pattern(user.password):
                    encrypted_password = current_app.password_encryptor.encrypt(user.password)
                    user.password = encrypted_password
                    user.save()

                return user
            except Exception, e:
                current_app.logger.error('Error getting user: %s' % e) 
                return None
Esempio n. 26
0
def configure_flasklogin(app):
    login_manager = LoginManager()
    login_manager.setup_app(app)

    @login_manager.user_loader
    def load_user(_id):
        db = connect_db()
        cur = db.user.find_one({'_id': ObjectId(_id)})
        user = User(cur)
        return user

    @login_manager.unauthorized_handler
    def unauthorized():
        flash(u'请先登录,3 秒钟内将转到登录页面……')
        return render_template('flash.html', target=url_for('login'))
Esempio n. 27
0
def configure_extensions(app):
    #from simplekv.memory import DictStore
    #from flask.ext.kvsession import KVSessionExtension
    #store = DictStore()
    ## this will replace the app's session handling
    #KVSessionExtension(store, app)
    mongo.init_app(app, "FUNFUNSAY")

    # cache
    cache.init_app(app)

    # babel
    #print "create babel object"
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        # if a user is logged in, use the locale from the user settings
        if current_user.is_authenticated():
            return current_user.locale
        # otherwise try to guess the language from the user accept
        # header the browser transmits.  We support de/fr/en in this
        # example.  The best match wins.
        return request.accept_languages.best_match(['zh_CN', 'en'])

    @babel.timezoneselector
    def get_timezone():
        if current_user.is_authenticated():
            return current_user.timezone
        return app.config['BABEL_DEFAULT_TIMEZONE']

    # login.
    from flask.ext.login import LoginManager
    login_manager = LoginManager()
    login_manager.session_protection = None  #@fixme!
    login_manager.login_view = 'homesite.login'
    login_manager.refresh_view = 'homesite.reauth'
    login_manager.login_message = _("Please log in to access this page.")

    @login_manager.user_loader
    def load_user(id):
        #print "####: loaduser ", id
        return User.load_user(id)

    login_manager.setup_app(app)

    from flask.ext.markdown import Markdown
    Markdown(app, safe_mode="escape")
Esempio n. 28
0
def configure_extensions(app):
    #from simplekv.memory import DictStore
    #from flask.ext.kvsession import KVSessionExtension
    #store = DictStore()
    ## this will replace the app's session handling
    #KVSessionExtension(store, app)
    mongo.init_app(app, "FUNFUNSAY")

    # cache
    cache.init_app(app)

    # babel
    #print "create babel object"
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        # if a user is logged in, use the locale from the user settings
        if current_user.is_authenticated():
            return current_user.locale
        # otherwise try to guess the language from the user accept
        # header the browser transmits.  We support de/fr/en in this
        # example.  The best match wins.
        return request.accept_languages.best_match(['zh_CN', 'en'])

    @babel.timezoneselector
    def get_timezone():
        if current_user.is_authenticated():
            return current_user.timezone
        return app.config['BABEL_DEFAULT_TIMEZONE']

    # login.
    from flask.ext.login import LoginManager
    login_manager = LoginManager()    
    login_manager.session_protection = None #@fixme!
    login_manager.login_view = 'homesite.login'
    login_manager.refresh_view = 'homesite.reauth'
    login_manager.login_message = _("Please log in to access this page.")

    @login_manager.user_loader
    def load_user(id):
        #print "####: loaduser ", id
        return User.load_user(id)
    login_manager.setup_app(app)

    from flask.ext.markdown import Markdown
    Markdown(app, safe_mode="escape")
Esempio n. 29
0
def configure_database(app):
	"Database configuration should be set here"
	# uncomment for sqlalchemy support
	from database import db
	db.app = app
	db.init_app(app)

	login_manager = LoginManager()
	login_manager.setup_app(app) 
	@login_manager.user_loader
	def load_user(userid):
		user = User.query.get(userid)
		if user:
			return FLUserWrapper(user)
		else:
			return None
		pass
Esempio n. 30
0
def init_login(app):
    login_manager = LoginManager()

    login_manager.login_view = "user.login"
    login_manager.logout_view = 'user.logout'
    login_manager.login_message = u"Please log in to access this page."
    login_manager.refresh_view = "user.reauth"
    login_manager.anonymous_user = Anonymous

    login_manager.setup_app(app)
    
    
    @login_manager.user_loader
    def load_user(id):
        from user.models import User
        from common import db
        return db.session.query(User).filter(User.id==id).first()
Esempio n. 31
0
File: app.py Progetto: sopnic/ybk
def configure_extensions(app):
    # flask-mail
    # flask-cache
    # flask-login
    # flask-openid
    login_manager = LoginManager()

    login_manager.login_view = 'user.login'
    login_manager.refresh_view = 'user.refresh'

    @login_manager.user_loader
    def load_user(user_id):
        return User.query_one({'_id': user_id})

    login_manager.setup_app(app)

    assets = Environment()
    assets.init_app(app)
Esempio n. 32
0
File: app.py Progetto: maocis/ybk
def configure_extensions(app):
    # flask-mail
    # flask-cache
    # flask-login
    # flask-openid
    login_manager = LoginManager()

    login_manager.login_view = 'user.login'
    login_manager.refresh_view = 'user.refresh'

    @login_manager.user_loader
    def load_user(user_id):
        return User.query_one({'_id': user_id})

    login_manager.setup_app(app)

    assets = Environment()
    assets.init_app(app)
Esempio n. 33
0
def configure_identity(app):
    ''' Configure middleware. '''

    login_manager = LoginManager()
    login_manager.login_view = 'users.login'
    login_manager.login_message = u'Please log in to access this page.'
    login_manager.refresh_view = 'users.reauth'
    login_manager.needs_refresh_message = u'To protect your account, please reauthenticate to access this page.'

    ADMIN_USER = User(app.config['ADMIN_USERNAME']) 
    @login_manager.user_loader
    def load_user(username):
        if username == ADMIN_USER.username:
            return ADMIN_USER
        else:
            return None

    login_manager.setup_app(app)
Esempio n. 34
0
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
Esempio n. 35
0
def configure_identity(app):
    ''' Configure middleware. '''

    login_manager = LoginManager()
    login_manager.login_view = 'users.login'
    login_manager.login_message = u'Please log in to access this page.'
    login_manager.refresh_view = 'users.reauth'
    login_manager.needs_refresh_message = u'To protect your account, please reauthenticate to access this page.'

    ADMIN_USER = User(app.config['ADMIN_USERNAME'])

    @login_manager.user_loader
    def load_user(username):
        if username == ADMIN_USER.username:
            return ADMIN_USER
        else:
            return None

    login_manager.setup_app(app)
Esempio n. 36
0
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
Esempio n. 37
0
    def __init__(self, app):
        lm = LoginManager()

        lm.login_view = '/login'
        lm.login_message = 'Login required.'
        lm.login_message_category = 'error'
        lm.anonymous_user = AnonymousUser

        lm.setup_app(app)

        @lm.user_loader
        def user_loader(id):
            try:
                id = int(id)
                user = User.query.filter_by(id=id).first()
            except:
                return None
            return user

        app.login_manager = lm
        app.auth_handler = self.auth_handler
Esempio n. 38
0
    def __init__(self, app):
        lm = LoginManager()

        lm.login_view = '/login'
        lm.login_message = 'Login required.'
        lm.login_message_category = 'error'
        lm.anonymous_user = AnonymousUser

        lm.setup_app(app)

        @lm.user_loader
        def user_loader(id):
            try:
                id = int(id)
                user = User.query.filter_by(id=id).first()
            except:
                return None
            return user

        app.login_manager = lm
        app.auth_handler = self.auth_handler
Esempio n. 39
0
def init_app(app):
    """ Configure middleware for the application. """

    principal = Principal(app)
    login_manager = LoginManager()
    login_manager.setup_app(app)
    login_manager.login_view = 'users.login'
    login_manager.anonymous_user = Guest

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        user = user_from_id(identity._id) 
        identity.provides.add(RoleNeed(user.access_level))
        identity.user = user
        g.user = user

    @login_manager.user_loader
    def load_user(uid):
        return user_from_id(uid)


    db.register(User)
Esempio n. 40
0
def init(app):
    lm = LoginManager()
    lm.login_view = "auth.login"
    lm.login_message = False
    lm.user_callback = admins_service.get
    lm.setup_app(app)

    @app.before_request
    def before_request():
        # if user is logged in or no endpoint is set allow the request
        if current_user.is_authenticated():
            return

        endpoint = request.endpoint or ''

        criteria = [
            endpoint.find('auth.login') == -1,
            endpoint.find('static') == -1
        ]

        if all(criteria):
            return app.login_manager.unauthorized()
Esempio n. 41
0
# Initialize cache for views
view_cache = Cache(app, config={'CACHE_TYPE': 'redis', \
                'CACHE_REDIS_HOST':'localhost', 'CACHE_REDIS_PORT':6379, \
                'CACHE_REDIS_PASSWORD':None})

# Set session store as server side (Redis)
redis_sesh = RedisSessionInterface()
if redis_sesh.redis:
    app.session_interface = redis_sesh

# Global Latest Year Variables
__latest_year__ = {"secex": 2014, "rais": 2012, "population": 2012}

# login manager for user management
lm = LoginManager()
lm.setup_app(app)

# babel configuration for lang support
babel = Babel(app)

# add a few extra template filters to jinja
app.jinja_env.globals['moment_js'] = jinja_momentjs
app.jinja_env.globals['format'] = jinja_formatter
app.jinja_env.filters['strip_html'] = jinja_strip_html
app.jinja_env.filters['split'] = jinja_split

# Load the modules for each different section of the site
''' data API view/models '''
from dataviva.attrs.views import mod as attrs_module
from dataviva.secex.views import mod as secex_module
from dataviva.rais.views import mod as rais_module
Esempio n. 42
0
from flaskpress.settings import theme
from flaskpress.config import Config
from flaskpress.tools import ModifiedLoader

# Init Flask
app = Flask(__name__,
            template_folder='themes/',
            static_folder='themes/' + theme['active'] + '/static/',
            static_url_path='/static')
app.config.from_object(Config)

app.wsgi_app = ProxyFix(app.wsgi_app)
db = SQLAlchemy(app)
lg = LoginManager()
lg.setup_app(app)

# Blueprints & shit
from flaskpress.ctx import objects, filters
from flaskpress.models import users
from flaskpress.views import default

from flaskpress.views.pages import mod as pages_bp
from flaskpress.views.posts import mod as posts_bp
from flaskpress.admin.view import mod as admin_bp

# Blueprints
app.register_blueprint(admin_bp)
app.register_blueprint(pages_bp)
app.register_blueprint(posts_bp)
Esempio n. 43
0
File: editor.py Progetto: dsmall/red
editor.config.from_object(__name__)

login_manager = LoginManager()

login_manager.anonymous_user = Anonymous
login_manager.login_view = '/editor/auth'
login_manager.login_message = u'Please log in to access this page.'
login_manager.refresh_view = '/editor/reauth'


@login_manager.user_loader
def load_user(id):
    return USERS.get(int(id))


login_manager.setup_app(editor)


def get_hash(username):
    #     f = open('/etc/passwd', 'r')
    f = open(PASSWD_FILE, 'r')
    accounts = f.readlines()
    for account in accounts:
        if account.startswith(username):
            return account.split(':')[1]
    import os
    return os.urandom(
        13
    )  # In the event that the account doesn't exist, return random noise to prevent login

Esempio n. 44
0
# -*- coding: utf-8 -*-

from flask import Flask, render_template, redirect
from flask.ext.admin import Admin

from flask.ext.login import LoginManager

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

from admin.model_view import UserView, EndpointView, LogoutView
from admin.model_view import ReportView, ChartView, PrefixView

app = Flask(__name__)

engine = create_engine('sqlite:///opendash.db')
Session = sessionmaker(bind=engine)
session = Session()

app.config['SECRET_KEY'] = '123456790'

login_manager = LoginManager()
login_manager.setup_app(app)

admin = Admin(app, name='OpenDASH')
admin.add_view(UserView(session))
admin.add_view(EndpointView(session))
admin.add_view(ReportView(session))
admin.add_view(ChartView(session))
admin.add_view(PrefixView(session))
admin.add_view(LogoutView(name='Log out'))
Esempio n. 45
0
#!/user/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
login = LoginManager()
login.setup_app(app)

from app import views, models
Esempio n. 46
0
def init_chat():
    global room_mgr
    room_mgr = ChatRoomMgr()
    init_volunteers()
    login_manager = LoginManager()
    login_manager.setup_app(app)
Esempio n. 47
0
def unauthorized_401(app):
    lm = LoginManager()
    lm.setup_app(app)
    with raises(Unauthorized):
        with assert_fired(user_unauthorized):
            res = lm.unauthorized()
Esempio n. 48
0
def lm_creation_and_setup(app):
    lm = LoginManager()
    lm.setup_app(app)
    assert app.login_manager is lm
    assert lm._load_user in app.before_request_funcs[None]
    assert lm._update_remember_cookie in app.after_request_funcs[None]
Esempio n. 49
0
            error_fh.setLevel(logging.ERROR)
            app.logger.addHandler(error_fh)
        if app.config['WARNING_LOG']:
            warning_fh = RotatingFileHandler(app.config['WARNING_LOG'],
                                             maxBytes=1024 * 1024 * 10,
                                             backupCount=10,
                                             encoding='utf_8')
            warning_fh.setLevel(logging.WARNING)
            app.logger.addHandler(warning_fh)


class User(UserMixin):
    def __init__(self, id):
        self.id = id


login_manager = LoginManager()
login_manager.login_view = "login"


@login_manager.user_loader
def load_user(username):
    return User(username)


login_manager.setup_app(app, add_context_processor=True)

es = ElasticSearch(app.config['ELASTICSEARCH_ENDPOINT'], max_retries=2)

import geordi.views
Esempio n. 50
0
from flaskext.cache import Cache
import config #our super sweet configuration module!
from datetime import datetime
app = Flask(__name__)

__cfg = config.getConfig()
app.config.from_object(__cfg) 
app.configType = __cfg

db = SQLAlchemy(app) #database and ORM
loginManager = LoginManager() #handle login and sessions
crypt = Bcrypt(app) #bcrypt for password hashing
BCRYPTDATE = datetime(2012,05,25) #the day we switched to using bcrypt instead of sha1 salt
cache = Cache(app)

loginManager.setup_app(app)
loginManager.login_view = "login"
loginManager.login_message = u"Please log in to access this page."
loginManager.refresh_view = "reauth"
loginManager.session_protection = "strong"
app.jinja_env.autoescape = True

def url_static(filename=None):
	if app.config['DEBUG']:
		return url_for('static',filename=filename)
	return "//s3.amazonaws.com/origiart/static/%s"%filename


app.jinja_env.globals.update(url_static=url_static)

from origiart import views
Esempio n. 51
0
    base_url='https://www.google.com/accounts/',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    request_token_url=None,
    request_token_params={
        'scope':
        'https://www.googleapis.com/auth/userinfo.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=current_app.config['GOOGLE_CLIENT_ID'],
    consumer_secret=current_app.config['GOOGLE_CLIENT_SECRET'])

# Initialize the login manager for Flask-Login.
login_manager = LoginManager()
login_manager.setup_app(current_app)


def init_celery():
    celery = Celery(current_app.import_name,
                    broker=current_app.config['CELERY_BROKER_URL'])
    celery.conf.update(current_app.config)
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with current_app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)
Esempio n. 52
0
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
Esempio n. 53
0
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)
Esempio n. 54
0
def unauthorized_401(app):
    lm = LoginManager()
    lm.setup_app(app)
    with raises(Unauthorized):
        with assert_fired(user_unauthorized):
            res = lm.unauthorized()
Esempio n. 55
0
from flask import current_app, request, render_template, redirect, url_for
from models import Users
from flask.ext.login import LoginManager, login_user, logout_user, login_required, current_user
from wtforms import Form, TextField, PasswordField, validators

login_manager = LoginManager()
login_manager.setup_app(current_app)


@login_manager.user_loader
def load_user(userid):
    return User.query.get(userid)


class UserLoginForm(Form):
    username = TextField(
        'Username', [validators.Required(),
                     validators.Length(min=4, max=25)])
    password = PasswordField(
        'Password', [validators.Required(),
                     validators.Length(min=6, max=200)])


@current_app.route('/logout', methods=['GET'])
@auth.login_required
def logout():
    logout_user()
    return redirect(url_for('login'))


@current_app.route('/secret', methods=['GET'])
Esempio n. 56
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
import os
# from SearchEngine import Engine

__StaticDir__ = os.path.abspath(os.path.dirname(__file__)) + "/static/"
__ExcelDir__ = __StaticDir__ + "/excel/"
__Add_info__ = __StaticDir__ + "/add_info/"
#initiate the app
appME = Flask(__name__)  #__name__=app
appME.config.from_object('config')

#initiate the database
db = SQLAlchemy(appME)

# engine=Engine()

#initiate flask-login
lm = LoginManager()
lm.setup_app(appME)

from app import views, models
Esempio n. 57
0
# -*- encoding: utf-8 -*-
"""
Python Aplication Template
Licence: GPLv3
"""

from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.pymongo import PyMongo
from flask.ext.login import LoginManager

app = Flask(__name__)


# Configuration of application, see configuration.py, choose one and uncomment.
# app.config.from_object('configuration.ProductionConfig')
app.config.from_object('app.configuration.DevelopmentConfig')
# app.config.from_object('configuration.TestingConfig')

bs = Bootstrap(app) #flask-bootstrap
db = SQLAlchemy(app) #flask-sqlalchemy

lm = LoginManager()
lm.setup_app(app)
lm.login_view = 'login'

from app import views, models
Esempio n. 58
0
BOOTSTRAP_JQUERY_VERSION = None
SOURCES = []
DESTINATIONS = []
""" Load Basic config """
webackup = Flask('modules',
                 static_folder="static",
                 template_folder='templates')
webackup.config.from_object(__name__)
Bootstrap(webackup)

# instantiate the db wrapper
db = Database(webackup)

# instatiate the login
login_manager = LoginManager()
login_manager.setup_app(webackup)

# initiate scheduler
sched = Scheduler()
sched.add_jobstore(ShelveJobStore('data/scheduler.db'), 'default')
sched.start()
""" Registering the blueprint controller """
dirs = os.listdir(APP_DIR)
for module in dirs:
    """ Blueprints """
    try:
        if module.startswith('__'): continue
        webackup.register_blueprint(
            import_string(APP_DIR + '.' + module + '.controller.register'))
    except ImportError, e:
        pass