Esempio n. 1
0
def create_app(config=None):
    app = Flask(__name__)

    # load configuration
    if config:
        app.config.from_object(config)
    else:
        app.config.from_object('rhiz.config.Default')
        app.config.from_envvar('RHIZ_APPLICATION_SETTINGS')

    security = Security()
    security.init_app(app, user_datastore)

    assets.init_app(app)
    db.init_app(app)
    admin.init_app(app)

    mail = Mail()
    mail.init_app(app)

    feature_flag = FeatureFlag()
    feature_flag.init_app(app)

    # register routes
    register_blog_routes(app)
    return app
Esempio n. 2
0
def init_app(app, user_datastore, LoginForm):
    def load_user(user_id):
        return user_datastore.get_user(user_id)

    def load_user_from_request(request):
        apikey = request.headers.environ.get('HTTP_X_API_KEY', None)
        if apikey:
            user = user_datastore.find_user(apikey=apikey)
            if not user:
                return None
        else:
            auth = request.headers.get('Authorization')
            if not auth or auth.count(':') != 1:
                return None
            login, password = auth.split(':')
            user = user_datastore.find_user(email=login.strip())
            if user is None:
                return None
            if not verify_and_update_password(password.strip(), user):
                return None
        return user if login_user(user) else None
    security = Security()
    security.init_app(app, user_datastore, login_form=LoginForm)
    app.login_manager.request_loader(load_user_from_request)
    app.login_manager.user_loader(load_user)
    user_logged_out.connect(invalidate_user)
Esempio n. 3
0
def init_app(app):
    security = Security()
    security.init_app(app, user_datastore, login_form=LoginForm)
    app.login_manager.request_loader(load_user_from_request)
    app.login_manager.user_loader(load_user)
    user_logged_out.connect(invalidate_user)
    user_logged_in.connect(invalidate_user)
Esempio n. 4
0
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
Esempio n. 5
0
    def init_app(self, app):
        if app.config.get('AUTH_DEBUG'):
            DebugAuthProvider().init_app(app)

        if app.config.get('AUTH_ZOPE'):
            ZopeAuthProvider().init_app(app)

        app.config.update({
            'SECURITY_CONFIRMABLE': True,
            'SECURITY_POST_CONFIRM_VIEW': self.homepage,
            'SECURITY_PASSWORD_HASH': 'ldap_salted_sha1',
            'SECURITY_SEND_PASSWORD_CHANGE_EMAIL': False,
            'SECURITY_EMAIL_SUBJECT_REGISTER': (
                "Please confirm your email address for "
                "the Biological Diversity website"
            ),
            'SECURITY_MSG_EMAIL_CONFIRMED': (
                ("Your email has been confirmed. You can now log in by "
                 "clicking the link at the top."),
                'success',
            ),
            'SECURITY_RECOVERABLE': True,
            'SECURITY_RESET_URL': '/auth/recover_password',
            'SECURITY_POST_LOGIN_VIEW': self.homepage,
            'SECURITY_MSG_PASSWORD_RESET': (
                "You have successfully reset your password.",
                'success',
            ),
            'SECURITY_FORGOT_PASSWORD_TEMPLATE': 'auth/forgot_password.html',
            'SECURITY_RESET_PASSWORD_TEMPLATE': 'auth/reset_password.html',
            'SECURITY_PASSWORD_SCHEMES': ['ldap_salted_sha1'],
        })
        Security.init_app(self.security_ext, app)
        security_state = app.extensions['security']
        security_state.pwd_context.update(ldap_salted_sha1__salt_size=7)
        security_state.forgot_password_form = EeaForgotPasswordForm

        app.register_blueprint(auth)
        app.jinja_env.globals['AUTH_BLUEPRINT_INSTALLED'] = True
        app.jinja_env.filters['ugly_fix'] = ugly_fix
        auth.models = self.models
        auth.HOMEPAGE = self.homepage
Esempio n. 6
0
def create_app(**config_overrides):
    global security
    app = Flask(__name__, template_folder='templates')
    app.config.from_object('config')
    app.config.update(config_overrides
                      )
    import sys
    import logging
    app.logger.addHandler(logging.StreamHandler(sys.stdout))
    app.logger.setLevel(logging.ERROR)
    engine_db.init_app(app)

    # setup security
    from wsgi import admin_views

    def security_context_processor():
        return dict(
            admin_base_template=admin.base_template,
            admin_view=admin.index_view,
            h=admin_helpers,
        )

    from wsgi.authentication_models import User, Role
    user_datastore = MongoEngineUserDatastore(engine_db, User, Role)
    security = Security(app)
    security._state = security.init_app(app, user_datastore)
    security.context_processor(security_context_processor)
    admin.init_app(app)

    app.register_blueprint(frontend)
    app.register_blueprint(filters)

    from wsgi.api import api
    from wsgi.resume_api import resume_api
    api.init_app(app)
    resume_api.init_app(app)

    return app
Esempio n. 7
0
    @property
    def admin_url(self):
        return "%s/%s/%s" % (app.config['ADMIN_URL'], 'review', self.id)

    @property
    def url(self):
        return "%s/%s/" % ('review', self.id)

users = SQLAlchemyUserDatastore(db, User, Role)
# social = Social(app, SQLAlchemyConnectionDatastore(db, Connection))


class ExtendedRegisterForm(RegisterForm):
    name = TextField(u'İsim Soyisim', [Required(u'İsmini girmen gerekli')])
    why = TextAreaField(
        u'Eşya Kütüphanesi\'ne neden geldiğinden kısaca bahsedebilir misin? '
        u'Mesela buradan beklentilerin neler? '
        u'Bizi nereden duydun?',
        [Length(min=0, max=1000, message=u'En fazla 1000 karakter girebilirsin.'),
         Required(u'Seni daha yakından tanımayı istiyoruz.')]
    )
    about = TextAreaField(
        u'Hobilerin neler? Bir ejderhan olsa adını ne koyardın? '
        u'En sevdiğin yemek ne? Boş zamanlarında ne yapmaktan hoşlanırsın?',
        [Length(min=0, max=1000, message=u'En fazla 1000 karakter girebilirsin.'),
         Required(u'Bize biraz kendinden bahseder misin?')]
    )
    agreement = BooleanField('', [Required(u'Kullanıcı sözleşmesini onaylamalısın.')])

security = Security(app, users, register_form=ExtendedRegisterForm)
Esempio n. 8
0
app = Flask(__name__)
app.config.from_yaml(app.root_path)
app.config.from_heroku()
app.wsgi_app = MethodRewriteMiddleware(app.wsgi_app)

db = SQLAlchemy(app)
webassets = Environment(app)

# Late import so modules can import their dependencies properly
from . import assets, models, views

security_ds = SQLAlchemyUserDatastore(db, models.User, models.Role)
social_ds = SQLAlchemyConnectionDatastore(db, models.Connection)

app.security = Security(app, security_ds)
app.social = Social(app, social_ds)


class SocialLoginError(Exception):
    def __init__(self, provider):
        self.provider = provider


@app.before_first_request
def before_first_request():
    try:
        models.db.create_all()
    except Exception, e:
        app.logger.error(str(e))
Esempio n. 9
0
import yaml
import sys

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.assets import Environment, Bundle
from flask.ext.security import Security, SQLAlchemyUserDatastore
from flask_mail import Mail
from jinja2 import FileSystemLoader

root = os.path.abspath(os.path.dirname(__file__) + '/../')
lm = LoginManager()
db = SQLAlchemy()
assets = Environment()
security = Security()
mail = Mail()


def create_app(config='/config.yml', log_level='INFO'):
    # initialize our flask application
    app = Flask(__name__, static_folder='../static', static_url_path='/static')

    # set our template path and configs
    app.jinja_loader = FileSystemLoader(os.path.join(root, 'templates'))
    config_vars = yaml.load(open(root + config))
    # inject all the yaml configs
    app.config.update(config_vars)
    # Remove the defaualt installed flask logger
    del app.logger.handlers[0]
    app.logger.setLevel(logging.NOTSET)
from flask_application.helpers import datetimeformat

app.jinja_env.filters['datetimeformat'] = datetimeformat

# Business Logic
# http://flask.pocoo.org/docs/patterns/packages/
# http://flask.pocoo.org/docs/blueprints/
from flask_application.controllers.frontend import frontend

app.register_blueprint(frontend)

from flask.ext.security import Security, MongoEngineUserDatastore
from flask_application.models import db, User, Role, Connection
from flask_application.security_extras import ExtendedRegisterForm

# Setup Flask-Security
user_datastore = MongoEngineUserDatastore(db, User, Role)
app.security = Security(app,
                        user_datastore,
                        register_form=ExtendedRegisterForm)

# Setup Flask-Social
from flask.ext.social import Social
from flask.ext.social.datastore import MongoEngineConnectionDatastore

app.social = Social(app, MongoEngineConnectionDatastore(db, Connection))

from flask_application.controllers.admin import admin

app.register_blueprint(admin)
Esempio n. 11
0
def create_app(name=__name__, enable_security=True, debug=False, **kwargs):
    """ Create the server istance for Flask application """

    #################################################
    # Flask app instance
    #################################################
    from confs import config
    template_dir = os.path.join(config.BASE_DIR, __package__)
    microservice = Flask(
        name,
        # Quick note:
        # i use the template folder from the current dir
        # just for Administration.
        # I expect to have 'admin' dir here to change
        # the default look of flask-admin
        template_folder=template_dir,
        **kwargs)

    ##############################
    # ERROR HANDLING

    # Handling exceptions with json
    for code in default_exceptions.keys():
        microservice.error_handler_spec[None][code] = make_json_error
    # Custom error handling: save to log
    got_request_exception.connect(log_exception, microservice)

    # Custom exceptions
    @microservice.errorhandler(RESTError)
    def handle_invalid_usage(error):
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
        return response

    ##############################
    # Flask configuration from config file
    microservice.config.from_object(config)
    microservice.config['DEBUG'] = debug
    # // TO FIX:
    # development/production split?
    logger.info("FLASKING! Created application")

    #################################################
    # Other components
    #################################################

    ##############################
    # Cors
    from .cors import cors
    cors.init_app(microservice)
    logger.info("FLASKING! Injected CORS")

    ##############################
    # DB
    from .models import db
    db.init_app(microservice)
    logger.info("FLASKING! Injected sqlalchemy. (please use it)")

    ##############################
    # Flask security
    if enable_security:

        ############################################
        # Should open an issue on flask-admin!
        # BUG!
        # from .security import security
        # security.init_app(microservice)
        # WORKAROUND
        from .security import udstore
        from flask.ext.security import Security
        security = Security(microservice, udstore)
        # WORKAROUND
        ############################################

        logger.info("FLASKING! Injected security")

    ##############################
    # Restful plugin
    from .rest import epo, create_endpoints
    logger.info("FLASKING! Injected rest endpoints")
    epo = create_endpoints(epo, security, debug)

    # Restful init of the app
    epo.rest_api.init_app(microservice)

    ##############################
    # Prepare database and tables
    with microservice.app_context():
        try:
            if config.REMOVE_DATA_AT_INIT_TIME:
                db.drop_all()
            db.create_all()
            logger.info("DB: Connected and ready")
        except Exception as e:
            logger.critical("Database connection failure: %s" % str(e))
            exit(1)

        if enable_security:
            from .security import db_auth
            # Prepare user/roles
            db_auth()

    ##############################
    # Flask admin
    if enable_security:
        from .admin import admin, UserView, RoleView
        from .models import User, Role
        from flask_admin import helpers as admin_helpers

        admin.init_app(microservice)
        admin.add_view(UserView(User, db.session))
        admin.add_view(RoleView(Role, db.session))

        # Context processor for merging flask-admin's template context
        # into the flask-security views
        @security.context_processor
        def security_context_processor():
            return dict(admin_base_template=admin.base_template,
                        admin_view=admin.index_view,
                        h=admin_helpers)

        logger.info("FLASKING! Injected admin endpoints")

    ##############################
    # RETHINKDB
# // TO FIX, not for every endpoint
    if RDB_AVAILABLE:

        @microservice.before_request
        def before_request():
            logger.debug("Hello request RDB")
            # === Connection ===
            # The RethinkDB server doesn’t use a thread-per-connnection approach,
            # so opening connections per request will not slow down your database.

            # Database should be already connected in "before_first_request"
            # But the post method fails to find the object!
            try_to_connect()

    ##############################
    # Logging responses
    @microservice.after_request
    def log_response(response):
        logger.info("{} {} {}\n{}".format(request.method, request.url,
                                          request.data, response))
        return response

    # OR
    # http://www.wiredmonk.me/error-handling-and-logging-in-flask-restful.html
    # WRITE TO FILE
    # file_handler = logging.FileHandler('app.log')
    # app.logger.addHandler(file_handler)
    # app.logger.setLevel(logging.INFO)

    ##############################
    # App is ready
    return microservice
Esempio n. 12
0
def configure_login_manager(app):
    security = Security(app)
    security.init_app(app, UserDataStore)

    app.config['SECURITY_LOGIN_URL'] = '/auth/login'
    app.config['SECURITY_LOGIN_USER_TEMPLATE'] = 'mod_auth/log_in.html'
Esempio n. 13
0
def create_app(app_name=config.APP_NAME):
    """Create the Flask application, startup logging and dynamically load
    additional modules (blueprints) that are found in this directory."""
    app = PgAdmin(__name__, static_url_path='/static')
    # Removes unwanted whitespace from render_template function
    app.jinja_env.trim_blocks = True
    app.config.from_object(config)

    ##########################################################################
    # Setup session management
    ##########################################################################
    app.session_interface = ServerSideSessionInterface(config.SESSION_DB_PATH)

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

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

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

    # File logging
    fh = logging.FileHandler(config.LOG_FILE)
    fh.setLevel(config.FILE_LOG_LEVEL)
    fh.setFormatter(logging.Formatter(config.FILE_LOG_FORMAT))
    app.logger.addHandler(fh)
    logger.addHandler(fh)

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

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

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

    # Initialise i18n
    babel = Babel(app)

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

    @babel.localeselector
    def get_locale():
        """Get the best language for the user."""
        language = request.accept_languages.best_match(config.LANGUAGES.keys())
        return language

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

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{0}'.format(
            config.SQLITE_PATH.replace('\\', '/')
            )

    # Only enable password related functionality in server mode.
    if config.SERVER_MODE is True:
        # TODO: Figure out how to disable /logout and /login
        app.config['SECURITY_RECOVERABLE'] = True
        app.config['SECURITY_CHANGEABLE'] = True

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

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

    # Upgrade the schema (if required)
    with app.app_context():
        version = Version.query.filter_by(name='ConfigDB').first()

        # Pre-flight checks
        if int(version.value) < int(config.SETTINGS_SCHEMA_VERSION):
            app.logger.info(
                    """Upgrading the database schema from version {0} to {1}.""".format(
                        version.value, config.SETTINGS_SCHEMA_VERSION
                        )
                    )
            from setup import do_upgrade
            do_upgrade(app, user_datastore, security, version)

    # Load all available serve drivers
    driver.init_app(app)

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

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

    @app.before_request
    def before_request():
        """Login the default user if running in desktop mode"""
        if config.SERVER_MODE is False:
            user = user_datastore.get_user(config.DESKTOP_USER)

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

            login_user(user)

    ##########################################################################
    # Minify output
    ##########################################################################
    @app.after_request
    def response_minify(response):
        """Minify html response to decrease traffic"""
        if config.MINIFY_HTML and not config.DEBUG:
            if response.content_type == u'text/html; charset=utf-8':
                response.set_data(
                    html_minify(response.get_data(as_text=True))
                )

        return response

    @app.context_processor
    def inject_blueprint():
        """Inject a reference to the current blueprint, if any."""
        return {
            'current_app': current_app,
            'current_blueprint': current_blueprint
            }

    ##########################################################################
    # All done!
    ##########################################################################
    app.logger.debug('URL map: %s' % app.url_map)

    return app
Esempio n. 14
0
def create_app(app=None, config_file=None):
    """
    factory that instantiates the app
    """

    if not app:
        app = Flask(__name__)

    # config files
    app.config.from_pyfile("config/base.py")
    if config_file:
        app.config.from_pyfile("config/{}.py".format(config_file))

    # extensions
    debug.init_app(app)
    db.init_app(app)
    admin = Admin(app, name='Laborapp', template_mode='bootstrap3')
    # Setup Flask-Security
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app=app,
        datastore=user_datastore, register_form=ExtendedRegisterForm)
    

    

    # Blueprints
    app.register_blueprint(front)
    app.register_blueprint(dashboard)

    # Admin Blueprints
    admin.add_view(AdminSkillView(Skill, db.session))
    admin.add_view(AdminRoleView(Role, db.session))
    admin.add_view(AdminUserView(User, db.session))

    # Context Processors
    @security.register_context_processor
    def security_register_processor():
        role = request.args.get("role", None)
        if role:

            

            # signal processors
            @user_registered.connect_via(app)
            def user_registered_sighandler(sender, role=role, **extra):
                
                user = extra.get('user')
                
                user_datastore.add_role_to_user(user,role)
                db.session.commit()
                

            
        return dict(role=role)
        # else:
        #     abort(500)

    @app.before_request
    def add_user_role():
        if hasattr(current_user, "id"):
            user = db.session.query(User).get(current_user.id)
            if not current_user.has_role("candidate") or \
                not current_user.has_role("company"):
                role = request.args.get("role", None)
                if role:
                    role_to_set = db.session.query(Role).filter_by(name=role).first()
                    user.roles.append(role_to_set)
                    db.session.commit()



    



    return app
Esempio n. 15
0
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
Esempio n. 16
0
def register_extensions(app):
    oauth.init_app(app)
    babel.init_app(app)
    security = Security(app, user_datastore)
Esempio n. 17
0
from city_lang.core.datastore import MongoSetUserDatastore
from flask import Blueprint, current_app
from flask.ext.security import Security

from werkzeug.local import LocalProxy

bp = Blueprint('pages', __name__, url_prefix="")
mongo = LocalProxy(lambda: current_app.extensions['mongoset'])
_security = LocalProxy(lambda: current_app.extensions['security'])

import views
import models

user_datastore = MongoSetUserDatastore(mongo, models.User, models.Role)
Security(current_app, user_datastore)
Esempio n. 18
0
def configure(app, db):
    from quokka.modules.accounts.models import User, Role
    app.security = Security(
        app=app,
        datastore=MongoEngineUserDatastore(db, User, Role),
    )
Esempio n. 19
0
def create_app(app_name=config.APP_NAME):
    """Create the Flask application, startup logging and dynamically load
    additional modules (blueprints) that are found in this directory."""
    app = PgAdmin(__name__, static_url_path='/static')
    # Removes unwanted whitespace from render_template function
    app.jinja_env.trim_blocks = True
    app.config.from_object(config)

    ##########################################################################
    # Setup session management
    ##########################################################################
    app.session_interface = ServerSideSessionInterface(config.SESSION_DB_PATH)

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

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

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

    # File logging
    fh = logging.FileHandler(config.LOG_FILE)
    fh.setLevel(config.FILE_LOG_LEVEL)
    fh.setFormatter(logging.Formatter(config.FILE_LOG_FORMAT))
    app.logger.addHandler(fh)
    logger.addHandler(fh)

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

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

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

    # Initialise i18n
    babel = Babel(app)

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

    @babel.localeselector
    def get_locale():
        """Get the best language for the user."""
        language = request.accept_languages.best_match(config.LANGUAGES.keys())
        return language

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

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

    # Only enable password related functionality in server mode.
    if config.SERVER_MODE is True:
        # TODO: Figure out how to disable /logout and /login
        app.config['SECURITY_RECOVERABLE'] = True
        app.config['SECURITY_CHANGEABLE'] = True

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

    import pgadmin.utils.paths as paths
    paths.init_app(app)

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

    # Upgrade the schema (if required)
    with app.app_context():
        version = Version.query.filter_by(name='ConfigDB').first()

        # Pre-flight checks
        if int(version.value) < int(config.SETTINGS_SCHEMA_VERSION):
            app.logger.info(
                """Upgrading the database schema from version {0} to {1}.""".
                format(version.value, config.SETTINGS_SCHEMA_VERSION))
            from setup import do_upgrade
            do_upgrade(app, user_datastore, security, version)

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

    ##########################################################################
    # Register any local servers we can discover
    ##########################################################################
    @user_logged_in.connect_via(app)
    def on_user_logged_in(sender, user):

        # Keep hold of the user ID
        user_id = user.id

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

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

            if servers.count() > 0:
                return

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

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

        # Figure out what servers are present
        if os.name == 'nt':
            proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()
            proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()

            if proc_arch == 'x86' and not proc_arch64:
                arch_keys = {0}
            elif proc_arch == 'x86' or proc_arch == 'amd64':
                arch_keys = {KEY_WOW64_32KEY, KEY_WOW64_64KEY}

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

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

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

                            inst_key.Close()
                    except:
                        pass
        else:
            # We use the postgres-reg.ini file on non-Windows
            try:
                from configparser import ConfigParser
            except ImportError:
                from ConfigParser import ConfigParser  # Python 2

            registry = ConfigParser()

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

            # Loop the sections, and get the data from any that are PG or PPAS
            for section in sections:
                if section.startswith('PostgreSQL/') or section.startswith(
                        'EnterpriseDB/'):
                    svr_name = registry.get(section, 'Description')
                    svr_superuser = registry.get(section, 'Superuser')
                    svr_port = registry.getint(section, 'Port')
                    svr_discovery_id = section
                    svr_comment = gettext(
                        "Auto-detected %s installation with the data directory at %s"
                        % (registry.get(section, 'Description'),
                           registry.get(section, 'DataDirectory')))
                    add_server(user_id, servergroup_id, svr_name,
                               svr_superuser, svr_port, svr_discovery_id,
                               svr_comment)

        except:
            pass

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

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

    @app.before_request
    def before_request():
        """Login the default user if running in desktop mode"""
        if config.SERVER_MODE is False:
            user = user_datastore.get_user(config.DESKTOP_USER)

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

            login_user(user)

    ##########################################################################
    # Minify output
    ##########################################################################
    @app.after_request
    def response_minify(response):
        """Minify html response to decrease traffic"""
        if config.MINIFY_HTML and not config.DEBUG:
            if response.content_type == u'text/html; charset=utf-8':
                response.set_data(html_minify(response.get_data(as_text=True)))

        return response

    @app.context_processor
    def inject_blueprint():
        """Inject a reference to the current blueprint, if any."""
        return {
            'current_app': current_app,
            'current_blueprint': current_blueprint
        }

    ##########################################################################
    # All done!
    ##########################################################################
    app.logger.debug('URL map: %s' % app.url_map)

    return app
Esempio n. 20
0
# Memcache
from flask.ext.cache import Cache
app.cache = Cache(app)

# MongoEngine
from flask_application.models import db
app.db = db
app.db.init_app(app)

from flask.ext.security import Security, MongoEngineUserDatastore
from flask_application.users.models import User, Role

# Setup Flask-Security
app.user_datastore = MongoEngineUserDatastore(app.db, User, Role)
app.security = Security(app, app.user_datastore)

# Business Logic
# http://flask.pocoo.org/docs/patterns/packages/
# http://flask.pocoo.org/docs/blueprints/
from flask_application.public.controllers import public
app.register_blueprint(public)

from flask_application.users.controllers import users
app.register_blueprint(users)

from flask_application.admin.controllers import admin
app.register_blueprint(admin)


def scan_and_import(name):
Esempio n. 21
0
def create_app(testing=False, live=False):
    from bhs_api.models import User, Role
    from bhs_api.forms import LoginForm

    app = Flask(__name__)
    app.testing = testing

    # Get configuration from file
    must_have_keys = set([
        'secret_key',
        'mail_server',
        'mail_port',
        'user_db_host',
        'user_db_port',
        'elasticsearch_host',
        'user_db_name',
        'data_db_host',
        'data_db_port',
        'data_db_name',
        'image_bucket_url',
        'video_bucket_url',
        'redis_host',
        'redis_port',
        'caching_ttl',
    ])

    # load the conf file. use local copy if nothing in the system
    if os.path.exists(CONF_FILE):
        conf = get_conf(CONF_FILE, must_have_keys)
    else:
        path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                            os.pardir, 'conf', 'bhs_config.yaml')
        conf = get_conf(path, must_have_keys)

    # Our config - need to move everything here
    app.config[
        'VIDEO_BUCKET_URL'] = "https://storage.googleapis.com/bhs-movies"
    app.config[
        'IMAGE_BUCKET_URL'] = "https://storage.googleapis.com/bhs-flat-pics"

    # Set app config
    app.config['DEBUG'] = True
    app.config['FRONTEND_SERVER'] = conf.frontend_server
    app.config['DEFAULT_NEXT'] = '/mjs'
    # Security Config
    app.config['SECRET_KEY'] = conf.secret_key
    app.config['WTF_CSRF_ENABLED'] = False
    app.config['SECURITY_PASSWORDLESS'] = True
    app.config['SECURITY_EMAIL_SENDER'] = 'BH Databases<*****@*****.**>'
    app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = 'email'
    app.config[
        'SECURITY_EMAIL_SUBJECT_PASSWORDLESS'] = 'Login link for Your Jewish Story'
    app.config['SECURITY_POST_LOGIN_VIEW'] = '/mjs'
    app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = ('email', 'username',
                                                       'hash')
    # Mail Config
    app.config['MAIL_SERVER'] = conf.mail_server
    app.config['MAIL_PORT'] = conf.mail_port
    # Mail optional username and password
    try:
        app.config['MAIL_USERNAME'] = conf.mail_username
        app.config['MAIL_PASSWORD'] = conf.mail_password
    except AttributeError:
        pass

    # DB Config
    app.config['MONGODB_DB'] = conf.user_db_name
    app.config['MONGODB_HOST'] = conf.user_db_host
    app.config['MONGODB_PORT'] = conf.user_db_port
    # CACHING
    app.config['CACHING_TTL'] = conf.caching_ttl

    app.mail = Mail(app)
    app.db = MongoEngine(app)
    app.user_datastore = MongoEngineUserDatastore(app.db, User, Role)
    app.security = Security(app,
                            app.user_datastore,
                            passwordless_login_form=LoginForm)
    # Create database connection object
    app.client_data_db = pymongo.MongoClient(
        conf.data_db_host,
        conf.data_db_port,
        read_preference=pymongo.ReadPreference.SECONDARY_PREFERRED)
    app.data_db = app.client_data_db[conf.data_db_name]

    # Create the elasticsearch connection
    app.es = elasticsearch.Elasticsearch(conf.elasticsearch_host)
    # Add the user's endpoints
    from bhs_api.user import user_endpoints
    app.register_blueprint(user_endpoints)
    # Add the v1 endpoint
    from bhs_api.v1_endpoints import v1_endpoints
    app.register_blueprint(v1_endpoints, url_prefix='/v1')
    # Initialize autodoc - https://github.com/acoomans/flask-autodoc
    #allow CORS
    cors = CORS(app,
                origins=['*'],
                headers=[
                    'content-type', 'accept', 'authentication-token',
                    'Authorization'
                ])
    # logging
    if live:
        app.config['PROPAGATE_EXCEPTIONS'] = True
        try:
            fh = logging.FileHandler(conf.log_file)
            formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            fh.setFormatter(formatter)
            app.logger.addHandler(fh)
        except AttributeError:
            pass

    # redis
    try:
        app.redis = redis.StrictRedis(host=conf.redis_host,
                                      port=conf.redis_port,
                                      db=0)
    except AttributeError:
        app.redis = None

    app.logger.debug("Hellow world")

    return app, conf
Esempio n. 22
0
def make_app():

    babel = Babel()
    security = Security()
    social = Social()
    user_datastore = SQLAlchemyUserDatastore(mdl.DB, mdl.User, mdl.Role)

    app = Flask(__name__)

    @login_failed.connect_via(app)
    def auto_add_user(sender, provider, oauth_response):
        connection_values = get_connection_values_from_oauth_response(
            provider, oauth_response)
        email = connection_values['email']
        if not email or not email.strip():
            email = ''

        if provider.name.lower() == 'facebook':
            fname = connection_values['full_name']
            email = fb.get_email(oauth_response)
        elif provider.name.lower() == 'twitter':
            fname = connection_values['display_name'][1:]  # cut off leading @
        else:
            fname = connection_values['display_name']

        user = user_datastore.create_user(
            email=email,
            name=fname,
            active=True,
            confirmed_at=datetime.now(),
        )

        role_query = mdl.DB.session.query(mdl.Role).filter_by(
            name='authenticated')
        try:
            role = role_query.one()
        except NoResultFound:
            role = mdl.Role(name='authenticated')

        user.roles.append(role)
        user_datastore.commit()
        connection_values['user_id'] = user.id
        connect_handler(connection_values, provider)
        login_user(user)
        mdl.DB.session.commit()
        flash(gettext(
            'Successfully linked login with {}. '
            'Ignore the message saying: "{}"').format(
            provider.name, '... account not associated with an existing user'),
            'info')
        return redirect(url_for('root.profile'))

    app.user_datastore = user_datastore
    app.localconf = lconf = Config('mamerwiselen', 'lost-tracker',
                                   version='2.0', require_load=True)
    app.config['SECRET_KEY'] = lconf.get('app', 'secret_key')
    app.config['SQLALCHEMY_DATABASE_URI'] = lconf.get('db', 'dsn')
    mdl.DB.init_app(app)

    # Social connections
    social_connections = {}
    _add_social_params(social_connections, 'facebook', app.localconf)
    _add_social_params(social_connections, 'twitter', app.localconf)
    _add_social_params(social_connections, 'google', app.localconf)

    if len(social_connections) < 1:
        LOG.error('No Social/OAuth providers defined! Users will not be '
                  'able to log-in!')

    app.config.update(social_connections)

    social.init_app(app, SQLAlchemyConnectionDatastore(mdl.DB, mdl.Connection))
    security.init_app(app, user_datastore)

    app.register_blueprint(COMMENT, url_prefix=COMMENT_PREFIX)
    app.register_blueprint(GROUP, url_prefix=GROUP_PREFIX)
    app.register_blueprint(PHOTO, url_prefix=PHOTO_PREFIX)
    app.register_blueprint(QR, url_prefix=QR_PREFIX)
    app.register_blueprint(REGISTRATION, url_prefix=REGISTRATION_PREFIX)
    app.register_blueprint(ROOT)
    app.register_blueprint(STATION, url_prefix=STATION_PREFIX)
    app.register_blueprint(TABULAR, url_prefix=TABULAR_PREFIX)
    app.register_blueprint(USER, url_prefix=USER_PREFIX)
    babel.init_app(app)
    babel.localeselector(get_locale)
    return app
Esempio n. 23
0
assets.register('all-css', less)

# Database
db = SQLAlchemy(app)
import models

# Admin
import admin

# Markdown
Markdown(app, safe_mode='escape')

# Debug toolbar
if app.config['DEBUG']:
    from flask.ext.debugtoolbar import DebugToolbarExtension as DTE
    toolbar = DTE(app)

# Security
datastore = SQLAlchemyUserDatastore(db, models.User, models.Role)
security = Security(app, datastore)


# Endpoints
@app.route('/')
def index():
    return render_template('index.html', User=models.User)


import forum.views as forum
app.register_blueprint(forum.bp, url_prefix='/forum')
Esempio n. 24
0
def create_app(config=None):
    if config is None:
        config = {}

    ROOT_DIR = os.path.abspath(os.path.dirname(__file__))

    app = flask.Flask(__name__,
                      static_folder=os.path.join(ROOT_DIR, "..", "static"))

    _CONF_D_PATH = os.environ.get('CONFIG_DIRECTORY',
                                  os.path.join(ROOT_DIR, "..", "..", "conf.d"))

    configs = [os.path.join(ROOT_DIR, "app.yml")]

    if os.path.isdir(_CONF_D_PATH):
        configs.extend(
            sorted(
                os.path.join(_CONF_D_PATH, x) for x in os.listdir(_CONF_D_PATH)
                if x.endswith(".yml")))

    for yaml_path in configs:
        if os.path.isfile(yaml_path):
            with open(yaml_path) as yaml_file:
                app.config.update(yaml.load(yaml_file))

    app.config.update(config)

    if 'SQLALCHEMY_DATABASE_URI' not in app.config:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.path.expandvars(
            os.environ.get(
                'SQLALCHEMY_DATABASE_URI',
                'postgresql://localhost/{0}'.format(app.config['app_name'])))

    if os.path.exists("/dev/log"):
        syslog_handler = logbook.SyslogHandler(app.config['app_name'],
                                               "/dev/log")
        syslog_handler.push_application()

    del app.logger.handlers[:]
    redirect_logging()

    app.logger.info("Started")

    Mail(app)

    from . import models

    models.db.init_app(app)

    from . import auth
    from .blueprints import investigations, entities, events, roles, users, event_types
    Security(app, auth.user_datastore, register_blueprint=False)
    from .auth import auth
    from .views import views
    from .setup import setup
    app.register_blueprint(auth)
    app.register_blueprint(views)
    app.register_blueprint(setup)
    app.register_blueprint(investigations, url_prefix="/investigations")
    app.register_blueprint(entities, url_prefix="/entities")
    app.register_blueprint(events, url_prefix="/events")
    app.register_blueprint(roles, url_prefix="/roles")
    app.register_blueprint(users, url_prefix="/users")
    app.register_blueprint(event_types, url_prefix="/event-types")
    from .errors import errors
    for code in errors:
        app.errorhandler(code)(errors[code])

    return app
Esempio n. 25
0
            + datetime.timedelta(days=2))

payments_users = db.Table('payments_users',
        db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
        db.Column('payment_id', db.Integer(), db.ForeignKey('payment.id')))

class Payment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    recipient_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    sender_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    event_id = db.Column(db.Integer, db.ForeignKey('event.id'))
    amount_cents = db.Column(db.Integer)

# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore, register_form = SpecialRegisterForm)

@security.context_processor
def security_register_processor():
    return dict(user=current_user)

# Api stuff
@app.route('/api/user/<int:userid>', methods = ['GET'])
def display_user_data(userid):
    return json.dumps(get_user_data(userid), default=dthandler)

def get_user_data(userid):
    user = User.query.filter(User.id==userid).first()
    if not user:
        return 'user not found', 404
    userdict = asdict(user)
Esempio n. 26
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.mail import Mail
from flask.ext.security import Security, SQLAlchemyUserDatastore
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.pagedown import PageDown

app = Flask(__name__)
app.config.from_object('config')

db = SQLAlchemy(app)
bootstrap = Bootstrap(app)
security = Security(app)
moment = Moment(app)
pagedown = PageDown(app)
mail = Mail(app)

from models import User, Role
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security.init_app(
    app,
    user_datastore,
)

from .main import main as main_blueprint
app.register_blueprint(main_blueprint)

from .admin import admin as admin_blueprint
app.register_blueprint(admin_blueprint, url_prefix='/admin')
Esempio n. 27
0
# -*- coding: utf-8 -*-

from __future__ import absolute_import

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from flask_mail import Mail
mail = Mail()

from flask.ext.security import (Security, SQLAlchemyUserDatastore)
from .models import User, Role
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(datastore=user_datastore)

from flask_jwt import JWT
jwt = JWT()

from flask_oauthlib.client import OAuth
oauth = OAuth()

from flask_migrate import Migrate
migrate = Migrate()

from celery import Celery
celery = Celery()

from opbeat.contrib.flask import Opbeat
opbeat = Opbeat()
Esempio n. 28
0
from flask_admin.base import MenuLink
from flask.ext.security import Security, SQLAlchemyUserDatastore
from flask_wtf.csrf import CsrfProtect
from config import FIRST_USER_PASS, FIRST_USER_NAME

# Initialize the app and database, import the config
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
CsrfProtect(app)
app.killswitch = 0

# setup db, create the db, setup security, and add first user
from app import models
userstore = SQLAlchemyUserDatastore(db, models.User, None)
sec = Security(app, userstore)
db.create_all()
try:
    userstore.create_user(email=FIRST_USER_NAME, password=FIRST_USER_PASS)
    db.session.commit()
except: db.session.rollback()

#this loads all views
from app.views import main, admin

#admin setup
_admin = Admin(app, 'NYX Admin', template_mode='bootstrap3',
              index_view=admin.ProtectedIndexView())
_admin.add_link(MenuLink(name='Back to Site', url='/'))
_admin.add_view(admin.UserModelView(models.User, db.session))
_admin.add_view(admin.BotModelView(models.Bot, db.session))
Esempio n. 29
0
app = Flask(__name__)
app.config['SECURITY_POST_LOGIN'] = '******'  #REDIRECT
app.config['SOCIAL_FACEBOOK'] = {
    'oauth': {
        'consumer_key': '110626275752351',
        'consumer_secret': 'a6d52ed9f11260e72c70b0c5432266f3',
        'request_token_params': {
            'scope': 'email'
        }
    }
}
app.config['SOCIAL_CONNECT_ALLOW_REDIRECT'] = "localhost:5000/profile"
app.config['SECRET_KEY'] = "foobarbazblah"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.sqlite'
db = SQLAlchemy(app)
Security(app, SQLAlchemyUserDatastore(db))
Social(app, SQLAlchemyConnectionDatastore(db))


@app.before_first_request
def before_first_request():
    db.create_all()


@app.route('/profile')
@login_required
def profile():
    return render_template(
        'profile.html',
        content='Profile Page',
        facebook_conn=current_app.social.facebook.get_connection())
Esempio n. 30
0
def configure_views(app):

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app,
                        user_datastore,
                        confirm_register_form=ExtendedRegisterForm)
    csrf = CsrfProtect(app)
    migrate = Migrate(app, db)
    admin = Admin(app, name="Lean Workbench Admin")

    admin.add_view(UserView(User, db.session))
    admin.add_view(
        ExportView(QuickbooksDailyAccountBalance,
                   db.session,
                   name="Quickbooks"))
    admin.add_view(ExportView(FacebookPageData, db.session, name="Facebook"))
    admin.add_view(ExportView(DateCount, db.session, name="Twitter Count"))
    admin.add_view(
        ExportView(GoogleAnalyticsVisitors, db.session, name="Visitors"))
    admin.add_view(
        ExportView(GoogleAnalyticsSignups, db.session, name="Signups"))

    print current_user

    @app.route('/')
    def index():
        if current_user.is_authenticated():
            logged_in = True
            return redirect(url_for('dashboard'))
        else:
            logged_in = False
            return render_template('public.html', logged_in=logged_in)

    @app.route('/signin', methods=["POST", "GET"])
    @app.route('/signup', methods=["POST", "GET"])
    def sign():
        if current_user.is_authenticated():
            return redirect(url_for('dashboard'))
        return render_template('public.html', logged_in=False)

    @auth_token_required
    @app.route('/stats', methods=['POST', 'GET'])
    @app.route('/stats/1', methods=['POST', 'GET'])
    @app.route('/onboarding/stick', methods=['POST', 'GET'])
    @app.route('/onboarding/scale', methods=['POST', 'GET'])
    @app.route('/onboarding/virality', methods=['POST', 'GET'])
    @app.route('/onboarding/pay', methods=['POST', 'GET'])
    @app.route('/onboarding/empathy', methods=['POST', 'GET'])
    @app.route('/export', methods=['POST', 'GET'])
    @app.route('/scale', methods=['POST', 'GET'])
    @app.route('/results', methods=['POST', 'GET'])
    @app.route('/privacy', methods=['POST', 'GET'])
    @app.route('/eula', methods=['POST', 'GET'])
    @app.route('/optimization', methods=['POST', 'GET'])
    @app.route('/baseline', methods=['POST', 'GET'])
    @app.route('/operations', methods=['POST', 'GET'])
    @app.route('/onboarding/done', methods=['GET', 'POST'])
    @app.route('/dashboard', methods=['POST', 'GET'])
    def dashboard():
        """
		"""
        if not current_user.is_authenticated():
            return render_template('public.html', logged_in=False)
        else:
            return render_template('public.html', logged_in=True)

    @app.route('/welcome', methods=['POST', 'GET'])
    def welcome():
        current_user.onboarded = True
        db.session.add(current_user)
        db.session.commit()
        return render_template('public.html', logged_in=True)

    api = restful.Api(app, decorators=[csrf.exempt])
    api.add_resource(HypothesisResource, '/api/v1/hypotheses')
    api.add_resource(FacebookResource, '/api/v1/facebook')
    api.add_resource(TwitterResource, '/api/v1/twitter')
    api.add_resource(WufooResource, '/api/v1/wufoo')
    api.add_resource(GoogleAnalyticsResource, '/api/v1/google-analytics')
    api.add_resource(Quickbooks_resource, '/api/v1/quickbooks')
    api.add_resource(UserResource, '/api/v1/users')
    api.add_resource(Ghosting_resource, '/api/v1/ghosting')
    api.add_resource(Scale_resource, '/api/v1/scale')
Esempio n. 31
0
__author__ = 'responsible'
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import SQLAlchemyUserDatastore, Security
from App import config

app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)

from App.models import User, Role, roles_users
from App.routes import api

# Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security().init_app(app, user_datastore, register_blueprint=False)

# init database data
try:
    db.create_all()
    db.session.add(User("test1", "test1"))
    db.session.add(User("test2", "test2"))
    db.session.add(Role("admin", "管理员"))
    db.session.commit()
    db.engine.execute(roles_users.insert(), user_id=1, role_id=1)
    db.session.commit()
except:
    pass
Esempio n. 32
0
    confirmed_at = DateTimeField(null=True)


class UserRoles(db.Model):
    # Because peewee does not come with built-in many-to-many
    # relationships, we need this intermediary class to link
    # user to roles.
    user = ForeignKeyField(User, related_name='roles')
    role = ForeignKeyField(Role, related_name='users')
    name = property(lambda self: self.role.name)
    description = property(lambda self: self.role.description)


# Setup Flask-Security
user_datastore = PeeweeUserDatastore(db, User, Role, UserRoles)
security = Security(app, user_datastore)


# Create a user to test with
@app.before_first_request
def create_user():
    for Model in (Role, User, UserRoles):
        Model.drop_table(fail_silently=True)
        Model.create_table(fail_silently=True)
    user_datastore.create_user(email='*****@*****.**', password='******')


# Views
@app.route('/')
@login_required
def home():
Esempio n. 33
0
    def validate(self):
        if not super(LoginForm, self).validate():
            return False
        if self.username.data.strip() == '':
            return False
        self.user = db_session.query(User).filter(User.username==self.username.data).first()
        if self.user is None:
            return False
        if self.password.data == self.user.password:
            return True
        return False


user_datastore = SQLAlchemyUserDatastore(SQLAlchemy(app), User, Role)
security = Security(app, user_datastore, login_form=ExtendedLoginForm)

@login_required
@roles_required('privileged_user')
@app.route('/testroles')
def TestLogin():
    if current_user.is_authenticated():
        if current_user.has_role('privileged_user'):
            context = {'user_name': get_current_user_first_name()}
            return render_template('testroles.html', **context)
        else:
            return  make_response("Unauthorized User")
    else:
        return redirect('/login')

Esempio n. 34
0
    mobile = db.StringField(max_length=255,required=True)
    confirmed_at = db.DateTimeField()
    birthdate = db.DateTimeField(required=True)
    gender = db.IntField(required=True)
    roles = db.ListField(db.ReferenceField(Role), default=[])
    gcm = db.ListField(required=False,default=[])

User.ensure_index([('password',ASCENDING)],index_name='password_idx')
User.ensure_index([('mobile',ASCENDING)],index_name='mobile_idx')
User.ensure_index([('name',ASCENDING)],index_name='mobile_idx')
# Setup Flask-Security
user_datastore = MongoEngineUserDatastore(db, User, Role)


#create the system wide security
security = Security()
security.init_app(app,user_datastore)



"""
This section attaches the login manager of the application
"""
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view='login'
login_manager.anonymous_user = AnonymousUser



Esempio n. 35
0
def create_app(config=None):
    if config is None:
        config = {}

    # Defaults
    config.update({
        'MAX_MAILBOX_AGE_SECONDS': 7 * 24 * 60 * 60,  # 1 week
    })

    ROOT_DIR = os.path.abspath(os.path.dirname(__file__))

    app = flask.Flask(__name__,
                      static_folder=os.path.join(ROOT_DIR, "..", "static"))

    _CONF_D_PATH = os.environ.get('CONFIG_DIRECTORY',
                                  os.path.join(ROOT_DIR, "..", "..", "conf.d"))

    configs = [os.path.join(ROOT_DIR, "app.yml")]

    if os.path.isdir(_CONF_D_PATH):
        configs.extend(
            sorted(
                os.path.join(_CONF_D_PATH, x) for x in os.listdir(_CONF_D_PATH)
                if x.endswith(".yml")))

    for yaml_path in configs:
        if os.path.isfile(yaml_path):
            with open(yaml_path) as yaml_file:
                app.config.update(yaml.load(yaml_file))

    app.config.update(config)

    if 'SQLALCHEMY_DATABASE_URI' not in app.config:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.path.expandvars(
            os.environ.get(
                'SQLALCHEMY_DATABASE_URI',
                'postgresql://localhost/{0}'.format(app.config['app_name'])))

    if os.path.exists("/dev/log"):
        syslog_handler = logbook.SyslogHandler(app.config['app_name'],
                                               "/dev/log")
        syslog_handler.push_application()

    del app.logger.handlers[:]
    redirect_logging()

    Mail(app)

    from . import models
    from . import errors

    models.db.init_app(app)

    from . import auth
    Security(app, auth.user_datastore, register_blueprint=False)

    from .errors import errors

    from .auth import auth
    from .views import views
    from .setup import setup
    blueprints = [auth, views, setup]

    for blueprint in blueprints:
        app.register_blueprint(blueprint)

    from .api import blueprint as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix="/v2")

    for code in errors:
        app.errorhandler(code)(errors[code])
    return app
Esempio n. 36
0
def create_app(config=None):
    if config is None:
        config = {}

    ROOT_DIR = os.path.abspath(os.path.dirname(__file__))

    app = flask.Flask(__name__, static_folder=os.path.join(ROOT_DIR, "..", "static"))

    app.config['COMBADGE_CONTACT_TIMEOUT'] = 60 * 60
    app.config['SHA512SUM'] = '/usr/bin/sha512sum'
    app.config['STORAGE_PATH'] = os.environ.get('STORAGE_PATH')
    _CONF_D_PATH = os.environ.get('CONFIG_DIRECTORY', os.path.join(ROOT_DIR, "..", "conf.d"))

    configs = [os.path.join(ROOT_DIR, "app.yml")]

    if os.path.isdir(_CONF_D_PATH):
        configs.extend(sorted(os.path.join(_CONF_D_PATH, x) for x in os.listdir(_CONF_D_PATH) if x.endswith(".yml")))
    for yaml_path in configs:
        if os.path.isfile(yaml_path):
            with open(yaml_path) as yaml_file:
                app.config.update(yaml.load(yaml_file))

    app.config.update(config)

    if 'SQLALCHEMY_DATABASE_URI' not in app.config:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.path.expandvars(
            os.environ.get('SQLALCHEMY_DATABASE_URI', 'postgresql://localhost/{0}'.format(app.config['app_name'])))

    del app.logger.handlers[:]
    redirect_logging()

    app.logger.info("Started")

    Mail(app)
    
    if os.environ.get("SQLALCHEMY_LOG_QUERIES"):
        logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO)

    app.raven = Sentry(
        app,
        client=raven.Client(
            dsn=app.config.get("SENTRY_DSN"),
            ignore_exceptions=[
                SSHException,
                JIRAError
            ],
        ),
    )

    from . import models

    models.db.init_app(app)

    from .errors import errors
    from .blueprints import auth, beams, files, issues, trackers, user_datastore, users, views, keys

    Security(app, user_datastore, register_blueprint=False)

    app.register_blueprint(auth)
    app.register_blueprint(beams, url_prefix="/beams")
    app.register_blueprint(files, url_prefix="/files")
    app.register_blueprint(issues, url_prefix="/issues")
    app.register_blueprint(trackers, url_prefix="/trackers")
    app.register_blueprint(users, url_prefix="/users")
    app.register_blueprint(keys, url_prefix="/keys")
    app.register_blueprint(views)

    if app.config.get('DEBUG'):
        from .blueprints import test_methods
        app.register_blueprint(test_methods)

    for code in errors:
        app.errorhandler(code)(errors[code])

    return app
Esempio n. 37
0
from mhn.auth.models import User, Role, ApiKey
user_datastore = SQLAlchemyUserDatastore(db, User, Role)

mhn = Flask(__name__)
mhn.config.from_object('config')
csrf.init_app(mhn)

# Email app setup.
mail = Mail()
mail.init_app(mhn)

# Registering app on db instance.
db.init_app(mhn)

# Setup flask-security for auth.
Security(mhn, user_datastore)

# Registering blueprints.
from mhn.api.views import api
mhn.register_blueprint(api)

from mhn.ui.views import ui
mhn.register_blueprint(ui)

from mhn.auth.views import auth
mhn.register_blueprint(auth)

# Trigger templatetag register.
from mhn.common.templatetags import format_date
mhn.jinja_env.filters['fdate'] = format_date
Esempio n. 38
0
def create_app(mode="development"):
    """Create webapp instance."""
    app = Flask(__name__, instance_relative_config=True)
    #Load database

    #Initilise DB

    from unifispot.models import user_datastore
    db.init_app(app)

    # Load the default configuration
    app.config.from_object('config.default')

    # Load the configuration from the instance folder
    app.config.from_pyfile('config.py')

    # Load the file specified by the config_filename environment variable
    # Variables defined here will override those in the default configuration
    if mode is not None:
        app.config.from_object('config.' + mode)
        # Load test database config
        if mode == 'testing':
            app.config.from_pyfile('config_test.py')
        elif mode == 'e2e_testing':
            app.config.from_pyfile('config_e2e_test.py')
    #Setup Flask-Security before loading any blueprints
    security = Security(app, user_datastore)
    #initilise mail,celery and redis

    mail.init_app(app)
    celery.init_app(app)
    redis.init_app(app)
    ##not going to use server side sessions
    #sess.init_app(app)

    #initlize assets
    assets = Environment(app)
    assets.register(bundles)
    # simple load all blueprint settings, enabled in config
    load_blueprint_settings(app, blueprint_path='unifispot')

    # simple load all blueprints, enabled in config
    load_blueprints(app, blueprint_path='unifispot')

    #check for default values required before starting app
    with app.app_context():
        from importlib import import_module
        import_module('unifispot.middleware')

    @app.route("/")
    @login_required
    def home():
        if current_user.type == 'admin':
            return redirect(url_for('admin.admin_index'))
        elif current_user.type == 'client':
            return redirect(url_for('client.client_index'))
        else:
            app.logger.error("Unknown User Type!! for ID:%s" % current_user.id)
            abort(400)

    return app
Esempio n. 39
0
#Bootstrap
Bootstrap(app)
#Setup Mail
mail = Mail(app)
mail.init_app(app)

# mail test
with mail.record_messages() as outbox:
    mail.send_message(subject='testing',
                      body='test',
                      recipients=['*****@*****.**'])

    assert len(outbox) == 1
    assert outbox[0].subject == "testing"

# Setup Flask-Security
user_datastore = MongoEngineUserDatastore(db, User, Role)
security = Security(app,
                    user_datastore,
                    confirm_register_form=ExtendedConfirmRegisterForm)
#security = Security(app, user_datastore)


@app.route('/')
def index():
    return render_template('index.html')


if __name__ == "__main__":
    app.run(debug=True, port=5000, host="0.0.0.0")
Esempio n. 40
0
def create_app(config_name):
    app = Flask(__name__)
    env = Environments(app, default_env=config_name)
    if os.path.exists(os.path.join(basedir, 'config_local.yml')):
        env.from_yaml(os.path.join(basedir, 'config_local.yml'))
    else:
        env.from_yaml(os.path.join(basedir, 'config.yml'))

    # Uses REDIS_URL from config.yml to set the connection to the redis-server
    cache.config = {
        'CACHE_TYPE': 'redis',
        'CACHE_REDIS_URL': app.config['REDIS_URL']}

    # Adding logging capabilities.
    if app.config['LOGGING'] is True:
        import logging
        logger = logging.getLogger('replicate')
        logger.setLevel(logging.DEBUG)

        log_directory = basedir + app.config['LOG_FILE_PTAH']
        log_filename = log_directory + app.config['LOG_FILE']
        if not os.path.exists(os.path.dirname(log_filename)):
            os.makedirs(os.path.dirname(log_filename))
        file_handler = logging.FileHandler(log_filename, mode='a+')

        stream_handler = logging.StreamHandler()
        formatter = logging.Formatter(
            '%(asctime)s - %(process)d - %(name)s - ' +
            '%(module)s:%(lineno)d - %(levelname)s - %(message)s')
        file_handler.setFormatter(formatter)
        stream_handler.setFormatter(formatter)
        app.logger.addHandler(file_handler)
        # app.logger.addHandler(stream_handler)
        app.logger.setLevel(logging.DEBUG)
        app.logger.info('Application Process Started')

    # SSL
    if not app.debug and not app.testing and app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        sslify = SSLify(app)

    # handle proxy server headers
    from werkzeug.contrib.fixers import ProxyFix
    app.wsgi_app = ProxyFix(app.wsgi_app)

    db.init_app(app)
    login_manager.init_app(app)
    cache.init_app(app)
    csrf.init_app(app)
    redis_store.init_app(app)
    cors.init_app(app)

    # Flask-Security Init
    from ooiservices.app.models import User, Role
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)
    security.init_app(app, register_blueprint=False)

    from ooiservices.app.main import api as main_blueprint
    app.register_blueprint(main_blueprint)

    from ooiservices.app.uframe import uframe as uframe_blueprint
    app.register_blueprint(uframe_blueprint, url_prefix='/uframe')

    from ooiservices.app.redmine import redmine as redmine_blueprint
    app.register_blueprint(redmine_blueprint, url_prefix='/redmine')

    from ooiservices.app.alfresco import alfresco as alfresco_blueprint
    app.register_blueprint(alfresco_blueprint, url_prefix='/alfresco')

    from ooiservices.app.m2m import m2m as m2m_blueprint
    app.register_blueprint(m2m_blueprint, url_prefix='/m2m')

    # If debug is enabled add route for site-map
    if app.config['DEBUG']:
        app.add_url_rule('/site-map', 'site_map', site_map)

    return app