コード例 #1
0
ファイル: database.py プロジェクト: rei901/realize-core
 def run(self, user):
     from app import db
     user_datastore = SQLAlchemyUserDatastore(db, User, Role)
     u = User.query.filter_by(email=user).first()
     role = user_datastore.find_or_create_role('admin')
     user_datastore.add_role_to_user(u, role)
     db.session.commit()
コード例 #2
0
def init_accounts(self, user=None, role=None):
    """
    Initialize Security for application.

    :param kwargs: parameters that will be passed through to Flask-Security
    :type kwargs: dict
    :returns: None

    A number of common User account operations are provided by `Flask-
    Security <http://pythonhosted.org/Flask-Security/>`_. This function is
    responsible for associating User models in the database with the
    Security object.

    In case you need to override a Flask-Security form (as is the case
    with implementing CAPTCHA) then you must use super() from within your
    application and provide any arguments destined for Flask-Security.

    >>> def ext_security(self):
    >>>    super(MyApp, self).ext_security(confirm_register_form=CaptchaRegisterForm)
    """

    # import database
    from .. import db

    if not user or not role:
        raise Exception

    # create datastore
    user_datastore = SQLAlchemyUserDatastore(db, user, role)
    setattr(Security, "user_datastore", user_datastore)
    security.init_app(self.app, datastore=user_datastore)
コード例 #3
0
def create_app(package_name=__name__, package_path=__path__, has_blueprints=True, **config_overrides):
    app = Flask(package_name, static_url_path='')
    app.config.update(APP)
    app.config.update(SECURITY)

    # Apply overrides.
    app.config.update(config_overrides)

    # Initialize the database and declarative Base class.
    db.init_app(app)
    Migrate(app, db)

    # Setup security.
    from argos.web import models
    user_db = SQLAlchemyUserDatastore(db, models.User, models.Role)
    Security(app, user_db)

    # Create the database tables.
    # Flask-SQLAlchemy needs to know which
    # app context to create the tables in.
    with app.app_context():
        db.create_all()

    # Register blueprints.
    if has_blueprints:
        register_blueprints(app, package_name, package_path)

    return app
コード例 #4
0
    def ext_security(self, app_models=None, **kwargs):
        """
        Initialize Security for application.

        :param kwargs: parameters that will be passed through to Flask-Security
        :type kwargs: dict
        :returns: None

        A number of common User account operations are provided by `Flask-
        Security <http://pythonhosted.org/Flask-Security/>`_. This function is
        responsible for associating User models in the database with the
        Security object.

        In case you need to override a Flask-Security form (as is the case
        with implementing CAPTCHA) then you must use super() from within your
        application and provide any arguments destined for Flask-Security.

        >>> def ext_security(self):
        >>>    super(MyApp, self).ext_security(confirm_register_form=CaptchaRegisterForm)
        """

        if not app_models:
            from . import models
        else:
            models = app_models

        user_datastore = SQLAlchemyUserDatastore(db, models.User, models.Role)
        security.init_app(self.app, datastore=user_datastore, **kwargs)
        security._state = self.app.extensions["security"]
        security.datastore = user_datastore
コード例 #5
0
def configure_extensions(app):
    # configure extensions
    # sqlalchemy
    db.init_app(app)
    db_ean.init_app(app)
    # mail
    mail.init_app(app)
    # cache
    cache.init_app(app)
    # babel
    babel = Babel(app)
    # login
    login_manager.login_view = 'frontend.login'
    login_manager.refresh_view = 'frontend.reauth'

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

    login_manager.setup_app(app)
    # security and Social
    app.flask_security = Security(app, SQLAlchemyUserDatastore(db, User, Role))
    #app.flask_social = Social(app, SQLAlchemyConnectionDatastore(db, Connection))
    # admin
    admin = Admin(app)
    #admin.add_view(ModelView(GenomeRule, db.session))
    admin.add_view(GenomeRuleView(db.session, name="Genome Rules"))
    admin.add_view(GenomeCategoryView(db.session, name="Genome Categories"))
コード例 #6
0
ファイル: security.py プロジェクト: leiyue/diamond-demo
def init_security(self):
    from .. import db
    from ..models import Role
    from ..models import User
    from ..forms import ExtendedLoginForm

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(
        self.app,
        datastore=user_datastore,
        login_form=ExtendedLoginForm,
    )

    try:
        from wtforms.fields import HiddenField
    except ImportError:

        def is_hidden_field_filter(field):
            raise RuntimeError('WTForms is not installed.')
    else:

        def is_hidden_field_filter(field):
            return isinstance(field, HiddenField)

    self.app.jinja_env.globals['is_hidden_field'] = is_hidden_field_filter
コード例 #7
0
ファイル: tut_gps_tests.py プロジェクト: vputz/marion
    def setUp(self):
        self.user_datastore = SQLAlchemyUserDatastore(tutorial.db, User, Role)
        tutorial.db.create_all()
        # u = User( nickname='test1', email='*****@*****.**' )
        self.remap_from = "University of Oxford"
        self.remap_to = "Oxford, United Kingdom"
        self.cache_loc = "Oxford, United Kingdom"
        self.cache_lat = 51.7519
        self.cache_lon = -1.2578

        self.user = self.user_datastore.create_user(nickname='test1',
                                                    email='*****@*****.**',
                                                    password='******')
        tutorial.db.session.add(self.user)
        tutorial.db.session.commit()

        oxford_remap = Gps_remap(from_location=self.remap_from,
                                 to_location=self.remap_to)
        tutorial.db.session.add(oxford_remap)

        oxford_lookup = Gps_cache(location=self.cache_loc,
                                  latitude=self.cache_lat,
                                  longitude=self.cache_lon)
        tutorial.db.session.add(oxford_lookup)

        tutorial.db.session.commit()
コード例 #8
0
ファイル: setup.py プロジェクト: vnthang/pgadmin4
def do_setup(app):
    """Create a new settings database from scratch"""
    if config.SERVER_MODE is False:
        print("NOTE: Configuring authentication for DESKTOP mode.")
        email = config.DESKTOP_USER
        p1 = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(32)
        ])

    else:
        print("NOTE: Configuring authentication for SERVER mode.\n")

        # Prompt the user for their default username and password.
        print("""
Enter the email address and password to use for the initial pgAdmin user \
account:\n""")
        email = ''
        while email == '':
            email = input("Email address: ")

        def pprompt():
            return getpass.getpass(), getpass.getpass('Retype password:'******'Passwords do not match. Try again')
            p1, p2 = pprompt()

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

    with app.app_context():
        password = encrypt_password(p1)

        db.create_all()
        user_datastore.create_role(name='Administrators',
                                   description='pgAdmin Administrators Role')
        user_datastore.create_user(email=email, password=password)
        db.session.flush()
        user_datastore.add_role_to_user(email, 'Administrators')

        # Get the user's ID and create the default server group
        user = User.query.filter_by(email=email).first()
        server_group = ServerGroup(user_id=user.id, name="Servers")
        db.session.merge(server_group)

        # Set the schema version
        version = Version(name='ConfigDB',
                          value=config.SETTINGS_SCHEMA_VERSION)
        db.session.merge(version)

        db.session.commit()

    # Done!
    print("")
    print("The configuration database has been created at {0}".format(
        config.SQLITE_PATH))
コード例 #9
0
def create_app(package_name,
               package_path,
               config_name,
               debug_override=None,
               register_security_blueprint=True):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the Longboxed platform.

    :param package_name: application package name
    :param package_path: application package path
    :param settings_override: a dictionary of settings to override
    :param debug_overide: :class:`Bool` value that overrides the debug settings
    """
    app = Flask(package_name, instance_relative_config=True)

    app.config.from_object(config[config_name])
    app.config.from_pyfile('settings.cfg', silent=True)
    if debug_override is not None:
        app.debug = debug_override

    #: Additional Settings setup
    config[config_name].init_app(app, store=store)

    #: Setup Flask Extensions
    cache.init_app(app, config=app.config.get('CACHE_CONFIG'))
    db.init_app(app)
    mail.init_app(app)
    s3_assets.init_app(app)
    #: Setup Flask-Security
    security.init_app(app,
                      SQLAlchemyUserDatastore(db, User, Role),
                      register_blueprint=register_security_blueprint,
                      confirm_register_form=ExtendedConfirmRegisterForm)

    # Register all blueprints
    register_blueprints(app, package_name, package_path)

    # Register all signal handlers
    signals.init_app(app)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    @app.before_request
    def start_implicit_store_context():
        push_store_context(store)

    @app.teardown_request
    def stop_implicit_store_context(exception=None):
        try:
            pop_store_context()
        except IndexError:
            pass

    #: Setup Logging if not debug
    setup_logging()

    return app
コード例 #10
0
def create_app(package_name,
               package_path,
               settings_override=None,
               security_register_blueprint=False):
    """
    Returns a :class:`Flask` application instance configured with common
    functionality for the webapp.

    :param package_name: application package name
    :param package_path: application package path
    :param settings_override: a dictionary of settings to override
    :param security_register_blueprint: register views for flask-security
    """
    # Instance Path
    instance_path = os.environ.get(
        "{{ cookiecutter.app_name | upper }}_INSTANCE_PATH", None)

    app = Flask(package_name,
                instance_relative_config=True,
                instance_path=instance_path)

    # Initialize settings
    app.config.from_object("{{ cookiecutter.app_name }}.settings")
    app.config.from_pyfile("settings.cfg", silent=True)
    app.config.from_object(settings_override)

    # Flask-SQLAlchemy
    db.init_app(app)

    # Flask-Migrate
    migrate.init_app(app, db)

    # Flask-Mail
    mail.init_app(app)

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

    # Flask-JWT
    jwt.init_app(app)
    jwt.authentication_handler(authenticate)
    jwt.payload_handler(make_payload)
    jwt.user_handler(load_user)

    # Sentry - only for production
    if not app.debug and not app.testing and 'SENTRY_DSN' in app.config:
        sentry = Sentry(app)

    # Middleware
    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    _log.info("Flask framework app created.")
    return app
コード例 #11
0
ファイル: __init__.py プロジェクト: DBeath/push-tester
def initialise_app(app, configclass):
    # Load the default configuration
    app.config.from_object(configclass)

    # Load the configuration from the instance folder
    try:
        app.config.from_pyfile('config.py')
    except:
        print 'No instance config file'

    if app.config['USE_PROXY']:
        app.wsgi_app = ProxyFix(app.wsgi_app)

    toolbar = DebugToolbarExtension(app)

    db.init_app(app)
    mail.init_app(app)

    assets = Environment(app)
    assets.register(bundles)

    from .models import User, Feed, Entry, Author, Role

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    app.security = Security(app, user_datastore)

    wtf.add_helpers(app)

    admin = Admin(app, 'Admin', index_view=SecuredAdminIndexView())
    admin.add_view(SecuredModelView(User, db.session))
    admin.add_view(SecuredModelView(Feed, db.session))
    admin.add_view(SecuredModelView(Entry, db.session))
    admin.add_view(SecuredModelView(Author, db.session))

    app.register_blueprint(frontend_blueprint)
    identity_loaded.connect_via(app)(on_identity_loaded)

    add_errorhandlers(app)

    Principal(app)

    if not app.debug:
        import logging
        from .utils.loggers import add_logger_filehandler, add_logger_external

        add_logger_filehandler(app)

        if app.config['LOG_ADDRESS']:
            add_logger_external(app)

        app.logger.setLevel(logging.INFO)
        app.logger.info(u'{0} startup'.format(app.config['PROJECT_NAME']))

    return app
コード例 #12
0
ファイル: tut_tests.py プロジェクト: vputz/marion
 def setUp(self):
     self.user_datastore = SQLAlchemyUserDatastore(tutorial.db, User, Role)
     tutorial.db.create_all()
     #u = User( nickname='test1', email='*****@*****.**' )
     self.user = self.user_datastore.create_user(nickname='test1',
                                                 email='*****@*****.**',
                                                 password='******')
     tutorial.db.session.add(self.user)
     tutorial.db.session.commit()
     # must commit before ID exists
     self.first_id = self.user.id
コード例 #13
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('jobs_board.settings')
    db.init_app(app)
    foundation.init_app(app)
    mail.init_app(app)
    from .users.models import Role, User
    security.init_app(app, SQLAlchemyUserDatastore(db, User, Role))
    from .jobs.views import blueprint as jobs
    app.register_blueprint(jobs)
    return app
コード例 #14
0
def register_extensions(app):
    cache.init_app(app)
    db.init_app(app)
    admin.init_app(app)
    register_admin_views(admin)
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore, confirm_register_form=ExtendedRegisterForm)
    mail.init_app(app)
    debug_toolbar.init_app(app)

    return None
コード例 #15
0
ファイル: database.py プロジェクト: rei901/realize-core
    def run(self):
        command.upgrade(alembic_cfg, "head")
        roles = ['admin', 'user', 'superuser']

        user_datastore = SQLAlchemyUserDatastore(db, User, Role)
        for r in roles:
            user_datastore.find_or_create_role(r)
        try:
            db.session.commit()
        except IntegrityError:
            # Happens if records already exist.
            db.session.rollback()
コード例 #16
0
def init(app):
    # --> Extension setup
    db.init_app(app)
    admin.init_app(app)

    modules["migrate"] = Migrate(app, db)

    modules["user_datastore"] = SQLAlchemyUserDatastore(db, User, Role)
    modules["security"] = Security(app,
                                   modules["user_datastore"],
                                   confirm_register_form=MyRegisterForm)

    # --> Register blueprints
    from modules.play.play import play

    app.register_blueprint(play, url_prefix='/play')

    from modules.api.core import api_core

    app.register_blueprint(api_core, url_prefix='/kcsapi')

    # Declare API v1 blueprints.
    from modules.api.v1.user import api_user
    from modules.api.v1.actions import api_actions
    app.register_blueprint(api_user, url_prefix='/kcsapi')
    app.register_blueprint(api_actions, url_prefix='/kcsapi')

    # Declare API v2 blueprints.
    from modules.api.v2.AdmiralAPI import AdmiralAPIv2
    from modules.api.v2.DockAPI import DockAPIv2
    app.register_blueprint(AdmiralAPIv2, url_prefix='/api/v2/admiral')
    app.register_blueprint(DockAPIv2, url_prefix='/api/v2/docks')

    from modules.resources import resources

    app.register_blueprint(resources, url_prefix='/kcs')

    # --> Base application routes
    @app.route('/')
    def index():
        return render_template('index.html')

    @app.route('/kcs/<path:path>')
    def kcs(path):
        return send_from_directory('kcs', path)

    # --> Signals
    @user_logged_in.connect_via(app)
    def u_logged_in(sender, user):
        """
        Regenerate the API token every login.
        """
        user.api_token = generate_api_token()
コード例 #17
0
def register_extensions(app):
    db.init_app(app)
    bcrypt.init_app(app)
    babel.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = '/login'
    s3.init_app(app)
    mail.init_app(app)

    from app.models import AppUser, Role
    user_datastore = SQLAlchemyUserDatastore(db, AppUser, Role)
    Security(app, user_datastore)
コード例 #18
0
ファイル: sqlalchemy.py プロジェクト: DevTable/flask-social
def create_app(config=None, debug=True):
    app = create_base_app(config, debug)
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'mysql://root@localhost/flask_social_test'

    db = SQLAlchemy(app)

    roles_users = db.Table(
        'roles_users',
        db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
        db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))

    class Role(db.Model, RoleMixin):
        id = db.Column(db.Integer(), primary_key=True)
        name = db.Column(db.String(80), unique=True)
        description = db.Column(db.String(255))

    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        email = db.Column(db.String(255), unique=True)
        password = db.Column(db.String(120))
        active = db.Column(db.Boolean())
        roles = db.relationship('Role',
                                secondary=roles_users,
                                backref=db.backref('users', lazy='dynamic'))
        connections = db.relationship('Connection',
                                      backref=db.backref('user',
                                                         lazy='joined'))

    class Connection(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
        provider_id = db.Column(db.String(255))
        provider_user_id = db.Column(db.String(255))
        access_token = db.Column(db.String(255))
        secret = db.Column(db.String(255))
        display_name = db.Column(db.String(255))
        profile_url = db.Column(db.String(512))
        image_url = db.Column(db.String(512))
        rank = db.Column(db.Integer)

    app.security = Security(app, SQLAlchemyUserDatastore(db, User, Role))
    app.social = Social(app, SQLAlchemyConnectionDatastore(db, Connection))

    @app.before_first_request
    def before_first_request():
        db.drop_all()
        db.create_all()
        populate_data()
        pass

    return app
コード例 #19
0
def create_app(config):
    app = Flask(
        __name__,
        template_folder="../dist/",
        static_folder="static/",
        static_url_path="/static")
    app.config.from_object(config)

    for key, value in security_messages.items():
        app.config['SECURITY_MSG_' + key] = value
    # app.config['SESSION_TYPE'] = 'filesystem'
    app.config['SECRET_KEY'] = os.urandom(24)
    # Session(app)
    _log_config(app)

    app.db = db
    db.init_app(app)
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)
    app.user_datastore = user_datastore


    @app.route('/')
    def to_app():
        return redirect(url_for('ngapp.home'))

    @app.route('/_uploads/photos/<path:path>')
    def do_not_allow_uploads(path):
        return abort(404)

    from .response import init as response_init
    response_init(app)

    import ngapp
    app.register_blueprint(ngapp.bp)

    @app.before_request
    def populate_user():
        header_key = app.config.get('SECURITY_TOKEN_AUTHENTICATION_HEADER', 'Authentication-Token')
        args_key = app.config.get('SECURITY_TOKEN_AUTHENTICATION_KEY', 'token')
        header_token = request.headers.get(header_key, None)
        token = request.args.get(args_key, header_token)
        if request.get_json(silent=True):
            token = request.json.get(args_key, token)

        if token:
            user = app.extensions['security'].login_manager.token_callback(token)
            _request_ctx_stack.top.user = user

    return app
コード例 #20
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('transcriber.app_config')
    app.config['SQLALCHEMY_DATABASE_URI'] = app.config['DB_CONN']

    app.register_blueprint(views)
    app.register_blueprint(auth)

    db.init_app(app)

    datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app,
                      datastore,
                      login_form=LoginForm,
                      confirm_register_form=RegisterForm)

    mail.init_app(app)
    csrf.init_app(app)
    flask_bcrypt.init_app(app)

    @app.template_filter('format_number')
    def format_number(s): # pragma: no cover
        if s:
            return '{:,}'.format(s)
        return s

    @app.template_filter('format_date')
    def format_date(s, fmt='%H:%M%p %b %d, %Y'): # pragma: no cover
        if s:
            return s.strftime(fmt)
        else:
            return '0'

    @app.template_filter('format_date_sort')
    def format_date_sort(s, fmt='%Y%m%d%H%M'): # pragma: no cover
        if s:
            return s.strftime(fmt)
        else:
            return '0'

    app.config['sentry'] = None

    if sentry:
        sentry.init_app(app)
        app.config['sentry'] = sentry

    return app
コード例 #21
0
    def create_user(self):

        if self.email is None or self.password is None:
            logging.warning('Email and Password cannot be null')
            return None
        try:
            SQLAlchemyUserDatastore(db, UsersModel, RolesModel).create_user(
                email=self.email,
                password=self.password,
                first_name=self.first_name,
                last_name=self.last_name,
                token=generate_token(),
                active=self.active)
            db.session.commit()
            return self
        except Exception as ex:
            logging.warning(ex)
コード例 #22
0
def create_app(settings_override=None):
    """Creates and returns a configured :class:`~flask.Flask` application.

    :param package_name: application package name.
    :param settings_override: ``dict`` containing settings to override.
    """
    if settings_override is None:
        settings_override = {}
    app = Flask(__name__)
    app.config.from_object('ivadb.settings')
    app.config.update(settings_override)

    api.init_app(app)
    db.init_app(app)
    security.init_app(app, SQLAlchemyUserDatastore(db, User, Role))
    app.register_blueprint(bp)
    return app
コード例 #23
0
ファイル: sqlalchemy.py プロジェクト: wbashir/flask-security
def create_app(config, **kwargs):
    app = create_base_app(config)

    #app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root@localhost/flask_security_test'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'

    db = SQLAlchemy(app)

    roles_users = db.Table(
        'roles_users',
        db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
        db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))

    class Role(db.Model, RoleMixin):
        id = db.Column(db.Integer(), primary_key=True)
        name = db.Column(db.String(80), unique=True)
        description = db.Column(db.String(255))

    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        email = db.Column(db.String(255), unique=True)
        password = db.Column(db.String(255))
        last_login_at = db.Column(db.DateTime())
        current_login_at = db.Column(db.DateTime())
        last_login_ip = db.Column(db.String(100))
        current_login_ip = db.Column(db.String(100))
        login_count = db.Column(db.Integer)
        active = db.Column(db.Boolean())
        confirmed_at = db.Column(db.DateTime())
        roles = db.relationship('Role',
                                secondary=roles_users,
                                backref=db.backref('users', lazy='dynamic'))

    @app.before_first_request
    def before_first_request():
        db.drop_all()
        db.create_all()
        populate_data(app.config.get('USER_COUNT', None))

    app.security = Security(app,
                            datastore=SQLAlchemyUserDatastore(db, User, Role),
                            **kwargs)

    add_context_processors(app.security)

    return app
コード例 #24
0
def init_webapp():
    """Initialize the web application."""

    # logging.getLogger('flask_cors').level = logging.DEBUG
    # app.wsgi_app = LoggingMiddleware(app.wsgi_app)

    # Note, this url namespace also exists for the Flask-Restless
    # extension and is where CRUD interfaces live, so be careful not to
    # collide with model names here. We could change this, but it's nice
    # to have API live in the same url namespace.
    app.register_blueprint(api, url_prefix='/api')

    # Initialize Flask configuration
    app.config['SQLALCHEMY_DATABASE_URI'] = make_conn_str()
    app.config['SECRET_KEY'] = 'abc123'
    app.config['WTF_CSRF_ENABLED'] = False
    app.config['SECURITY_TOKEN_MAX_AGE'] = 60
    app.config['SECURITY_TOKEN_AUTHENTICATION_HEADER'] = 'Auth-Token'
    # app.config['SECURITY_POST_LOGIN_VIEW'] = 'http://127.0.0.1:4200'
    # app.config['CORS_HEADERS'] = 'Content-Type'

    # Initialize Flask-CORS
    CORS(app, supports_credentials=True)
    # CORS(app, supports_credentials=True, resources={r"/*": {"origins": "*"}})

    # Initialize Flask-Bootstrap
    Bootstrap(app)

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

    # Initialize Flask-SQLAlchemy
    db.app = app
    db.init_app(app)
    db.create_all()

    # Initialize Flask-Restless
    manager = APIManager(
        app,
        flask_sqlalchemy_db=db,
        preprocessors=dict(GET_MANY=[restless_api_auth_func]),
    )
    manager.create_api(Employee, methods=['GET', 'POST', 'OPTIONS'])
    return app
コード例 #25
0
ファイル: ivysaur_app.py プロジェクト: skyclean906/python
def create_app(env):
    init_config(env)
    app = _initialize_flask_app()
    app.wsgi_app = RequestLoggerMiddleware(app.wsgi_app)
    app = _configure_logging(app)
    app.config.from_object(Ivysaur.Config)
    app = _register_blueprints(app)
    app = _register_version_and_log(app)

    db = SQLAlchemy(app, session_options={"autoflush": False})
    reg = get_registry()
    reg['DB'] = db

    mail = Mail(app)
    reg['MAIL'] = mail

    reg['TOKBOX'] = OpenTok(
        Ivysaur.Config.TOKBOX_API_KEY, Ivysaur.Config.TOKBOX_API_SECRET
    )

    from lib.models.user import User
    from lib.models.role import Role

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    Security(app, user_datastore)

    from lib.repo.user_repo import UserRepo
    from lib.repo.device_repo import DeviceRepo
    from lib.repo.deck_repo import DeckRepo
    from lib.repo.notification_repo import NotificationRepo
    from lib.repo.ask_repo import AskRepo

    # see comment for this method
    _initialize_models()

    reg['USER_DATASTORE'] = user_datastore
    reg['USER_REPO'] = UserRepo()
    reg['DEVICE_REPO'] = DeviceRepo()
    reg['DECK_REPO'] = DeckRepo()
    reg['NOTIFICATION_REPO'] = NotificationRepo()
    reg['ASK_REPO'] = AskRepo()

    app = _initialize_managers(app)
    app.json_encoder = AppJSONEncoder
    return app
コード例 #26
0
def setup_app(app):
    from adsws.core import db, User, Role
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)

    app.config.setdefault('SECURITY_PASSWORD_HASH', 'pbkdf2_sha512')
    app.config.setdefault('SECURITY_PASSWORD_SALT',
                          app.config.get('SECRET_KEY'))
    register_blueprint = app.config.get('SECURITY_REGISTER_BLUEPRINT', True)

    # if desired, we'll use ADS Classic as a source for authenticating
    # users
    if app.config.get('FALL_BACK_ADS_CLASSIC_LOGIN', False):

        from .ads_classic_login import AdsClassicFallBackLoginForm
        security.init_app(app,
                          user_datastore,
                          register_blueprint=register_blueprint,
                          login_form=AdsClassicFallBackLoginForm)
    else:
        security.init_app(app,
                          user_datastore,
                          register_blueprint=register_blueprint)

    # if there is Flask-Email extension, we'll use that one for sending
    # emails
    if 'email' in app.extensions:
        from flask_email import EmailMessage

        def send_email(msg):
            if not 'email' in app.extensions:
                warn(
                    "Flask-Email extension has disappeared from app.extensions"
                )
                return

            email = EmailMessage(subject=msg.subject,
                                 body=msg.body,
                                 from_email=msg.sender,
                                 to=msg.recipients)
            email.send(app.extensions['email'])

        app.extensions['security'].send_mail_task(send_email)

    return app
コード例 #27
0
        filename="hexbin_query.json", template="hexbin_query.html")

    # create tabdata queries
    replace_tabdata_query(
        db, name="Tabdata_hexbin",
        description="Hexbin of geographical data", 
        parameters='{ "locationColumn" : 0, "valueColumn" : 0, "textColumn" : 0 }',
        template="tabdata_hexbin_query.html")
    replace_tabdata_query(
        db, name="Tabdata_markercluster",
        description="Markercluster map of geographical data",
        parameters='{ "locationColumn" : 0, "valueColumn" : 0, "textColumn" : 0 }', 
        template="tabdata_markercluster_query.html")

        # create users
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    if user_datastore.find_user(nickname="admin") is None:
        admin = user_datastore.create_user(
            nickname="admin", email="*****@*****.**", password="******")
        db.session.add(admin)
        db.session.commit()

    create_gps_cache()


if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
    api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
    api.version_control(SQLALCHEMY_DATABASE_URI,
                        SQLALCHEMY_MIGRATE_REPO,
コード例 #28
0
def create_app(option):
    app = FlaskOpinewExt(__name__)
    config = config_factory.get(option)
    app.config.from_object(config)

    from common import create_jinja_filters, random_pwd, verify_initialization

    create_jinja_filters(app)
    from webapp.client import client
    from webapp.media import media

    app.register_blueprint(client)
    app.register_blueprint(media, url_prefix=Constants.MEDIA_URL_PREFIX)

    compress.init_app(app)
    gravatar.init_app(app)
    resize.init_app(app)
    db.init_app(app)
    admin.init_app(app)
    mail.init_app(app)
    migrate.init_app(app, db)
    babel.init_app(app)
    from models import User, Role
    from webapp.forms import ExtendedRegisterForm

    assets.init_app(app)
    assets.register('js_all', js_assets)
    assets.register('css_all', css_assets)

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app,
                      user_datastore,
                      confirm_register_form=ExtendedRegisterForm)
    with app.app_context():
        from providers import database, payment

        if not app.testing:
            verify_initialization()

        if app.testing:
            from async import tasks
        api_manager.init_app(app, flask_sqlalchemy_db=db)

        @app.before_request
        def before_request():
            # hack to allow browsers who don't set 3rd party cookies
            x_session = request.headers.get('X-Session')
            if x_session:
                rc = dict(request.cookies)
                rc['session'] = x_session
                request.cookies = ImmutableTypeConversionDict(rc)
                # refresh session
                refreshed_csrf_token = app.session_interface.open_session(
                    app, request).get('csrf_token')
                session['csrf_token'] = refreshed_csrf_token
            user_agent = parse(request.user_agent.string)
            g.mobile = False
            if user_agent.is_mobile or user_agent.is_tablet:
                g.mobile = True
            g.constants = Constants
            g.config = app.config
            g.mode = app.config.get('MODE')
            g.response_context = []
            g.s = strings
            g.payment = payment.StripeAPI()
            g.db = database.OpinewSQLAlchemyFacade()

        @app.after_request
        def redirect_if_next(response_class):
            if request.endpoint == 'static':
                response_class.headers['Access-Control-Allow-Origin'] = '*'
            payload = request.args if request.method == 'GET' else request.form
            if 'api_next' in payload:
                if not response_class.status_code == 200:
                    flash(response_class.data)
                    return redirect(request.referrer)
                return redirect(payload.get('api_next'))
            return response_class

    # register here CSRF so that the before_request is executed after the hack above
    csrf.init_app(app)
    patch_request_class(app, Constants.MAX_FILE_SIZE)

    from webapp.common import make_json_error

    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error

    configure_uploads(app, (
        user_images,
        review_images,
        shop_images,
    ))
    admins = [email for name, email in config.ADMINS]

    if not (app.debug or app.testing):
        mail_handler = SMTPHandler(
            app.config.get('MAIL_SERVER'),
            '*****@*****.**',
            admins,
            'Your Application Failed',
            credentials=(app.config.get('MAIL_USERNAME'),
                         app.config.get('MAIL_PASSWORD')),
            secure=())
        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(
            Formatter('''
Time        : %(asctime)s
Location    : %(pathname)s:%(lineno)d
Module      : %(module)s
Function    : %(funcName)s

%(message)s'''))
        app.logger.addHandler(mail_handler)

    return app
コード例 #29
0
ファイル: models.py プロジェクト: EsyaKutuphanesi/things-demo
    comment = db.Column(db.String(1000))
    rating = db.Column(db.Integer)
    created_at = db.Column(db.DateTime, default=datetime.now)

    def __repr__(self):
        return str(self.id)

    @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?',
コード例 #30
0
ファイル: main.py プロジェクト: shachar183/anyway
    username = StringField('User Name', [validators.DataRequired()])

    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')