Beispiel #1
0
def init():
    global security
    
    app.config['SECURITY_CONFIRMABLE'] = not app.config['MAIL_SUPPRESS_SEND']
    app.config['SECURITY_CHANGEABLE'] = True
    app.config['SECURITY_SEND_PASSWORD_CHANGE_EMAIL'] = not app.config['MAIL_SUPPRESS_SEND']
    app.config['SECURITY_POST_CHANGE_VIEW'] = "profile.html"
    app.config['SECURITY_PASSWORD_HASH'] = "bcrypt"
    app.config['SECURITY_MSG_CONFIRMATION_REQUIRED'] = (
            Markup('Email requires confirmation. <a href="/confirm">Resend confirmation instructions</a>.'), 
            'error')
    # This comes from config: app.config['SECURITY_REGISTERABLE']

    # Update all salts with SECRET_KEY if they are not set
    secret_key = app.config['SECRET_KEY']
    for salt in ('SECURITY_PASSWORD_SALT', 'SECURITY_CONFIRM_SALT', 
            'SECURITY_RESET_SALT', 'SECURITY_LOGIN_SALT', 
            'SECURITY_REMEMBER_SALT'):
        app.config[salt] = app.config.get(salt, secret_key)

    app.config['SECURITY_EMAIL_SENDER'] = app.config['MAIL_DEFAULT_SENDER']

    app.config['SECURITY_POST_LOGIN_VIEW'] = "/"

    security = Security(app, CustomUserDatastore(), 
            login_form=CustomLoginForm,
            register_form=CustomRegisterForm,
            confirm_register_form=CustomRegisterForm)

    security.send_mail_task(send_security_mail)
Beispiel #2
0
def init_extensions(app):
    """
    Initialize extensions registered for this app
    :param app:
    :return:
    """

    db_adapter = SQLAlchemyUserDatastore(db, User, Role)
    user_manager = Security()

    assets_env.init_app(app)
    mail.init_app(app)
    celery.init_app(app)
    compress.init_app(app)
    csrf.init_app(app)
    review_images_factory(app.testing, app)
    db.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db, directory='store/migrations')
    resize.init_app(app)
    socketio.init_app(app)
    if app.config.get("MODE") == assets.AppModes.PRODUCTION:
        sentry.init_app(app, logging=True)
    from auth.forms import ExtendedRegisterForm, ExtendedLoginForm
    user_manager.init_app(app, db_adapter, register_form=ExtendedRegisterForm, login_form=ExtendedLoginForm,
                          confirm_register_form=ExtendedRegisterForm)
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)
Beispiel #4
0
    def create_app(self):
        app = super(UserRegistrationDbTests, self).create_app()

        app.config['NOI_CAN_UNCONFIRMED_USERS_FULLY_REGISTER'] = False

        security = Security()
        security.init_app(app, datastore=DeploySQLAlchemyUserDatastore(
            db, User, Role
        ))

        return app
def init_app(app):
    from flask_login import LoginManager
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.user_loader(load_user)
    login_manager.login_view = "/login"

    # Setup Flask-Security
    security = Security()
    security = security.init_app(app, AppEngineUserDatastore(User, Role))
    security.send_mail_task(send_mail)

    from flask_social_blueprint.core import SocialBlueprint
    SocialBlueprint.init_bp(app, SocialConnection, url_prefix="/_social")
Beispiel #6
0
def init_app(app):
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.user_loader(load_user)
    login_manager.login_view = '/login'

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

    from flask_social_blueprint.core import SocialBlueprint
    SocialBlueprint.init_bp(app, SocialConnection, url_prefix='/_social')

    state = app.extensions['security']
    state.render_template = render_template
    app.extensions['security'] = state
Beispiel #7
0
def init_app(app):

	# Flask-Login
	# https://flask-login.readthedocs.org/en/latest/
    from flask_login import LoginManager
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.user_loader(load_user)
    login_manager.login_view = "/login"

    # Setup Flask-Security
    security = Security()
    security = security.init_app(app, SQLAlchemyUserDatastore(db, User, Role))
    security.send_mail_task(send_mail)

    from flask_social_blueprint.core import SocialBlueprint
    SocialBlueprint.init_bp(app, SocialConnection, url_prefix="/_social")
Beispiel #8
0
def create_app(config_override: Mapping = None) -> Flask:
    """Create the flask app for the debug server.

    Parameters:
        config_override:
            Dict containing custom configuration to apply after loading the
            normal config. Useful for testing.
    """
    config_override = {} if config_override is None else config_override
    # TODO: Rename app, no longer used only for debugging
    app = Flask('stuffrdebugserver',
                instance_relative_config=True,
                static_url_path='',
                template_folder='static')
    app.config.from_object('config.default')
    app.config.from_envvar('STUFFR_SETTINGS')
    app.config.from_mapping(config_override)
    app.json_encoder = StuffrJSONEncoder
    logger.set_logger(app.logger)

    db.init_app(app)
    security = Security(app, user_store, confirm_register_form=StuffrRegisterForm)
    security.unauthorized_handler(api_unauthenticated_handler)
    Mail(app)

    # In debug mode Swagger documentation is served at root
    if not app.config['DEBUG']:
        def api_root_view():
            """Provide a link to API documentation if root accessed."""
            return error_response(
                'TODO: Link to documentation here', HTTPStatus.NOT_FOUND)
        blueprint_api.add_url_rule('/', 'apiindex', api_root_view)

    app.register_blueprint(blueprint_simple, url_prefix='/simple')
    app.register_blueprint(blueprint_api, url_prefix='/api')

    def default404(e):
        """Default handler for 404."""
        # TODO: Conditional JSON/HTML response (for simple mode)
        return error_response(e.description, HTTPStatus.NOT_FOUND)
    app.register_error_handler(HTTPStatus.NOT_FOUND, default404)

    # TODO: Make friendlier error message (40x or 50x?)
    app.add_url_rule('/', 'index', lambda: "You probably shouldn't be here")

    return app
def test_custom_forms_via_config(app, sqlalchemy_datastore):
    class MyLoginForm(LoginForm):
        email = StringField('My Login Email Address Field')

    class MyRegisterForm(RegisterForm):
        email = StringField('My Register Email Address Field')

    app.config['SECURITY_LOGIN_FORM'] = MyLoginForm
    app.config['SECURITY_REGISTER_FORM'] = MyRegisterForm

    security = Security(datastore=sqlalchemy_datastore)
    security.init_app(app)

    client = app.test_client()

    response = client.get('/login')
    assert b'My Login Email Address Field' in response.data

    response = client.get('/register')
    assert b'My Register Email Address Field' in response.data
Beispiel #10
0
    def __init__(self, app=None, sessionstore=None):
        """Extension initialization.

        :param app: The Flask application.
        :param sessionstore: store for sessions. Passed to
            ``flask-kvsession``. Defaults to redis.
        """
        self.security = Security()
        self.datastore = None
        if app:
            self.init_app(app, sessionstore=sessionstore)
Beispiel #11
0
def init():
    global security

    app.config["SECURITY_CONFIRMABLE"] = not app.config["MAIL_SUPPRESS_SEND"]
    app.config["SECURITY_CHANGEABLE"] = True
    app.config["SECURITY_SEND_PASSWORD_CHANGE_EMAIL"] = not app.config["MAIL_SUPPRESS_SEND"]
    app.config["SECURITY_POST_CHANGE_VIEW"] = "profile.html"
    app.config["SECURITY_PASSWORD_HASH"] = "bcrypt"
    app.config["SECURITY_MSG_CONFIRMATION_REQUIRED"] = (
        Markup('Email requires confirmation. <a href="/confirm">Resend confirmation instructions</a>.'),
        "error",
    )
    # This comes from config: app.config['SECURITY_REGISTERABLE']

    # Update all salts with SECRET_KEY if they are not set
    secret_key = app.config["SECRET_KEY"]
    for salt in (
        "SECURITY_PASSWORD_SALT",
        "SECURITY_CONFIRM_SALT",
        "SECURITY_RESET_SALT",
        "SECURITY_LOGIN_SALT",
        "SECURITY_REMEMBER_SALT",
    ):
        app.config[salt] = app.config.get(salt, secret_key)

    app.config["SECURITY_EMAIL_SENDER"] = app.config["MAIL_DEFAULT_SENDER"]

    app.config["SECURITY_POST_LOGIN_VIEW"] = "/"

    security = Security(
        app,
        CustomUserDatastore(),
        login_form=CustomLoginForm,
        register_form=CustomRegisterForm,
        confirm_register_form=CustomRegisterForm,
    )

    security.send_mail_task(send_security_mail)

    if app.config["SECURITY_CONFIRMABLE"] and app.config["NEW_USER_NOTIFICATION"]:
        user_confirmed.connect(new_user_notification, app)
Beispiel #12
0
def init():
    global security

    app.config['SECURITY_REGISTERABLE'] = True
    app.config['SECURITY_CONFIRMABLE'] = True
    app.config['SECURITY_PASSWORD_HASH'] = "bcrypt"
    
    # Update all salts with SECRET_KEY if they are not set
    secret_key = app.config['SECRET_KEY']
    for salt in ('SECURITY_PASSWORD_SALT', 'SECURITY_CONFIRM_SALT', 
            'SECURITY_RESET_SALT', 'SECURITY_LOGIN_SALT', 
            'SECURITY_REMEMBER_SALT'):
        app.config[salt] = app.config.get(salt, secret_key)

    app.config['SECURITY_EMAIL_SENDER'] = app.config['MAIL_DEFAULT_SENDER']

    app.config['SECURITY_POST_LOGIN_VIEW'] = "/pledge.html"

    security = Security(app, IcoinUserDatastore(), 
            confirm_register_form=IcoinRegisterForm)

    security.send_mail_task(send_security_mail)
def init_app(app):

    # Flask-Login
    # https://flask-login.readthedocs.org/en/latest/
    from flask_login import LoginManager
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.user_loader(load_user)
    login_manager.login_view = "/login"

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

    from flask_social_blueprint.core import SocialBlueprint
    SocialBlueprint.init_bp(app, SocialConnection, url_prefix="/_social")

    @app.before_first_request
    def before_first_request():
        for m in [User, Role, SocialConnection]:
            m.drop_collection()
Beispiel #14
0
from adminlte.views import FaLink
from config import config, host, port
import api.routes

from api.models import db
from api.models.user import User

from api.admin.user import UserView

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

# AdminLTE Panel
security = Security(app, admins_store)
admin = AdminLte(app,
                 skin='green',
                 name='FlaskCMS',
                 short_name="<b>F</b>C",
                 long_name="<b>Flask</b>CMS")
admin.add_link(
    FaLink(name="Documentation",
           icon_value='fa-book',
           icon_type="fa",
           url='/docs/'))
admin.add_view(
    UserView(User, db.session, name="Users", menu_icon_value='fa-users'))


@security.context_processor
Beispiel #15
0
class BaseModelView(ModelView):
    def on_model_change(self, form, model, is_created):
        model.generate_slug()
        return super(BaseModelView,
                     self).on_model_change(form, model, is_created)


class AdminView(AdminMixin, ModelView):
    pass


class HomeAdminView(AdminMixin, AdminIndexView):
    pass


class PostAdminView(AdminMixin, BaseModelView):
    form_columns = ['title', 'body', 'tags']


class TagAdminView(AdminMixin, BaseModelView):
    form_columns = ['name', 'posts']


admin = Admin(app, 'Flask', url='/', index_view=HomeAdminView(name='Home'))
admin.add_view(PostAdminView(Post, db.session))
admin.add_view(TagAdminView(Tag, db.session))

#-------Flask security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
Beispiel #16
0
#!/usr/bin/env python

import os
from datetime import datetime
from flask_security import Security, SQLAlchemySessionUserDatastore
from manager.setup import app
from manager.setup_db import init_db, db
from manager.user import User, Role

# with app.app_context():

# Create any database tables that don't exist yet.
init_db()

user_datastore = SQLAlchemySessionUserDatastore(db.session, User, Role)
security = Security(app, user_datastore)  # this sets some app.config

# Create the Roles "admin" and "end-user" -- unless they already exist
user_datastore.find_or_create_role(name='admin', description='Administrator')
user_datastore.find_or_create_role(name='user', description='End user')

admin_email = os.environ['ADMIN_EMAIL']
# create admin user
if not user_datastore.get_user(admin_email):
    user_datastore.create_user(
        email=admin_email,
        username='******',
        password=os.environ['ADMIN_PASSWORD'],
        active=True,
        confirmed_at=datetime.now(),
    )
Beispiel #17
0
# Memcache
from flask_cache import Cache
app.cache = Cache(app)

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

from flask_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):
Beispiel #18
0

class User(db.Document, UserMixin):
    firstname = db.StringField(required=True, max_length=30)
    lastname = db.StringField(required=True, max_length=30)
    dateOfBirth = db.StringField(required=True, max_length=30)
    email = db.EmailField(required=True, max_length=50)
    password = db.StringField(required=True)
    confirmpassword = db.StringField(required=True)
    active = db.BooleanField(default=True)
    confirmed_at = db.DateTimeField()
    roles = db.ListField(db.ReferenceField(Role), default=[])


user_datastore = MongoEngineUserDatastore(db, User, Role)
security = Security(app, user_datastore, register_form=RegisterForm)


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


@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()

    if request.method == 'POST':
        passwordtest = request.form.get("password")
        if len(passwordtest) < 6:
Beispiel #19
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('settings.py', silent=True)

    db.init_app(app)

    admin = Admin(app,
                  name='Flask-Docker CPanel',
                  template_mode='bootstrap3',
                  index_view=SecureAdminIndexView())
    admin.add_view(
        MenuModelView(Menu,
                      db.session,
                      menu_icon_type=ICON_TYPE_FONT_AWESOME,
                      menu_icon_value='fa-list'))
    admin.add_view(
        PageModelView(Page,
                      db.session,
                      menu_icon_type=ICON_TYPE_FONT_AWESOME,
                      menu_icon_value='fa-file-o'))
    admin.add_view(
        RoleModelView(Role,
                      db.session,
                      menu_icon_type=ICON_TYPE_FONT_AWESOME,
                      menu_icon_value='fa-users'))
    admin.add_view(
        UserModelView(User,
                      db.session,
                      menu_icon_type=ICON_TYPE_FONT_AWESOME,
                      menu_icon_value='fa-user-o'))

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

    @app.route('/')
    @app.route('/<url>')
    def index(url=None):
        content = ''
        page = None

        if url is not None:
            page = Page.query.filter_by(url=url).first()
        else:
            page = Page.query.filter_by(is_homepage=True).first()

        if page is not None:
            content = page.content
        else:
            return '<b>404</b> : Page not found'

        menu = Menu.query.order_by('order').all()

        return render_template('index.html',
                               TITLE='Flask-Docker',
                               CONTENT=content,
                               MENU=menu)

    @app.route('/db_test')
    def db_test():
        import psycopg2

        connection = psycopg2.connect(
            'dbname=flask user=postgres password=postgres host=postgres')
        cursor = connection.cursor()
        cursor.execute('select id, title, content from page')
        id, title, content = cursor.fetchone()
        connection.close()

        return 'Test query fetch 1 : {} | {}'.format(id, title)

    @app.route('/secret_url')
    @login_required
    def secret_url():
        return '<h1>SECRET PAGE</h1>'

    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory(os.path.join(app.root_path, 'static'),
                                   'favicon.ico',
                                   mimetype='image/vnd.microsoft.icon')

    return app
Beispiel #20
0
""" Pulls together modules to implement
user roles and authorization
"""
from flask_security import Security, SQLAlchemyUserDatastore
from flask_security.forms import ConfirmRegisterForm
from wtforms import validators, StringField

from . import db, app
from .models import User, Role


class ExtendedConfirmRegisterForm(ConfirmRegisterForm):
    # flask-security user registration
    first_name = StringField('First Name', validators=[validators.required()])
    last_name = StringField('Last Name', validators=[validators.required()])
    nickname = StringField('Nickname')


user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app,
                    user_datastore,
                    confirm_register_form=ExtendedConfirmRegisterForm)
Beispiel #21
0
def init_app_with_options(app, datastore, **options):
    security_args = options.pop("security_args", {})
    app.config.update(**options)
    app.security = Security(app, datastore=datastore, **security_args)
    populate_data(app)
Beispiel #22
0
def create_app(db_connection_string=None, testing=None):
    app = Flask(__name__)

    try:
        secret_key = server.config.faraday_server.secret_key
    except Exception:
        # Now when the config file does not exist it doesn't enter in this
        # condition, but it could happen in the future. TODO check
        save_new_secret_key(app)
    else:
        if secret_key is None:
            # This is what happens now when the config file doesn't exist.
            # TODO check
            save_new_secret_key(app)
        else:
            app.config['SECRET_KEY'] = secret_key

    login_failed_message = ("Invalid username or password", 'error')

    app.config.update({
        'SECURITY_PASSWORD_SINGLE_HASH':
        True,
        'WTF_CSRF_ENABLED':
        False,
        'SECURITY_USER_IDENTITY_ATTRIBUTES': ['username'],
        'SECURITY_POST_LOGIN_VIEW':
        '/_api/session',
        'SECURITY_POST_LOGOUT_VIEW':
        '/_api/login',
        'SECURITY_POST_CHANGE_VIEW':
        '/_api/change',
        'SECURITY_CHANGEABLE':
        True,
        'SECURITY_SEND_PASSWORD_CHANGE_EMAIL':
        False,
        'SECURITY_MSG_USER_DOES_NOT_EXIST':
        login_failed_message,

        # The line bellow should not be necessary because of the
        # CustomLoginForm, but i'll include it anyway.
        'SECURITY_MSG_INVALID_PASSWORD':
        login_failed_message,
        'SESSION_TYPE':
        'filesystem',
        'SESSION_FILE_DIR':
        server.config.FARADAY_SERVER_SESSIONS_DIR,
        'SQLALCHEMY_TRACK_MODIFICATIONS':
        False,
        'SQLALCHEMY_RECORD_QUERIES':
        True,
        # app.config['SQLALCHEMY_ECHO'] = True
        'SECURITY_PASSWORD_SCHEMES': [
            'bcrypt',  # This should be the default value
            # 'des_crypt',
            'pbkdf2_sha1',  # Used by CouchDB passwords
            # 'pbkdf2_sha256',
            # 'pbkdf2_sha512',
            # 'sha256_crypt',
            # 'sha512_crypt',
            'plaintext',  # TODO: remove it
        ],
        'PERMANENT_SESSION_LIFETIME':
        datetime.timedelta(hours=12),
    })

    try:
        storage_path = server.config.storage.path
    except AttributeError:
        logger.warn(
            'No storage section or path in the .faraday/server.ini. Setting the default value to .faraday/storage'
        )
        storage_path = setup_storage_path()
    if not DepotManager.get('default'):
        if testing:
            DepotManager.configure('default', {'depot.storage_path': '/tmp'})
        else:
            DepotManager.configure('default',
                                   {'depot.storage_path': storage_path})

    check_testing_configuration(testing, app)

    try:
        app.config[
            'SQLALCHEMY_DATABASE_URI'] = db_connection_string or server.config.database.connection_string.strip(
                "'")
    except AttributeError:
        logger.info(
            'Missing [database] section on server.ini. Please configure the database before running the server.'
        )
    except NoOptionError:
        logger.info(
            'Missing connection_string on [database] section on server.ini. Please configure the database before running the server.'
        )

    from server.models import db
    db.init_app(app)
    #Session(app)

    # Setup Flask-Security
    app.user_datastore = SQLAlchemyUserDatastore(
        db, user_model=server.models.User,
        role_model=None)  # We won't use flask security roles feature
    Security(app, app.user_datastore, login_form=CustomLoginForm)
    # Make API endpoints require a login user by default. Based on
    # https://stackoverflow.com/questions/13428708/best-way-to-make-flask-logins-login-required-the-default
    app.view_functions['security.login'].is_public = True
    app.view_functions['security.logout'].is_public = True

    app.debug = server.config.is_debug_mode()
    minify_json_output(app)

    for handler in LOGGING_HANDLERS:
        app.logger.addHandler(handler)

    register_blueprints(app)
    register_handlers(app)

    return app
Beispiel #23
0
def create_app(test_config=None):
    from . import models, routes

    # app = Flask(__name__, static_folder="static/")
    ### FLASK CONFIG
    app = Flask(__name__,
                instance_relative_config=True,
                static_folder="static/")
    CORS(app, supports_credentials=True)

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile("config.py", silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        # os.makedirs(app.instance_path)
        pass
    except OSError:
        pass

    #### END

    basedir = os.path.abspath(os.path.dirname(__file__))
    # Database
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(
        basedir, "database/db.sqlite")
    print(app.config["SQLALCHEMY_DATABASE_URI"])
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

    app.config["SECRET_KEY"] = "super-secret"
    app.config["SECURITY_PASSWORD_SALT"] = "super-secret"
    app.config["SECURITY_TRACKABLE"] = True
    app.config["SECURITY_REGISTERABLE"] = True
    app.config["WTF_CSRF_ENABLED"] = False
    app.config["SECURITY_SEND_REGISTER_EMAIL"] = False

    # Mail config
    app.config["MAIL_SERVER"] = "smtp.gmail.com"
    app.config["MAIL_PORT"] = 465
    app.config["MAIL_USERNAME"] = "******"
    app.config["MAIL_PASSWORD"] = "******"
    app.config["MAIL_USE_TLS"] = False
    app.config["MAIL_USE_SSL"] = True

    from src.models.user import User, Role, db
    from flask_security import (
        SQLAlchemySessionUserDatastore,
        Security,
        login_required,
        current_user,
    )

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

    import src.mail as mail

    models.init_app(app)
    routes.init_app(app)
    mail.init_app(app)

    from flask import send_from_directory

    # Serve React App
    @app.route("/", defaults={"path": ""})
    @app.route("/<path:path>")
    @login_required
    def serve(path):
        if path != "" and os.path.exists(app.static_folder + "/" + path):
            return send_from_directory(app.static_folder, path)
        else:
            return send_from_directory(app.static_folder, "index.html")

    @app.errorhandler(404)
    def page_not_found(e):
        return redirect("/"), 404

    @app.route("/schema")
    def get_schema():
        return render_template("schema.html")

    return app
Beispiel #24
0
from flask import Flask, abort, redirect, url_for, request
from flask_sqlalchemy import SQLAlchemy
from config import config
from flask_security import Security, SQLAlchemyUserDatastore, current_user, \
    UserMixin, RoleMixin, login_required, auth_token_required, http_auth_required
from flask_security.utils import encrypt_password
from flask_admin.contrib import sqla
from flask_admin import Admin, helpers as admin_helpers

db = SQLAlchemy()

# models引用必须在 db/login_manager之后,不然会循环引用
from .models import User, Role

user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(datastore=user_datastore)

# Create admin
admin = Admin(name=u'简读Admin')


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)
    security.init_app(app)
    admin.init_app(app)

    from .main import main as main_blueprint
Beispiel #25
0
 def create() -> SecurityFixture:
     security = Security(app, datastore=sqlalchemy_datastore)
     app.security = security
     return app
Beispiel #26
0
def create_app():
    #Creamos una instancia del flask
    logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
    app = Flask(__name__)

    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    #Generar la clave de sessión para crear una cookie con la inf. de la sessión
    app.config['SECRET_KEY'] = os.urandom(24)
    #Usar en caso de que no se tenga algun acceso a la principal
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@31.170.161.1/u512768467_muebleria2'
    #app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@31.170.161.1/u512768467_muebleria'
    app.config['SECURITY_PASSWORD_SALT'] = 'thisissecretsalt'

    db.init_app(app)

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

            userDataStore.find_or_create_role(name='admin',
                                              description='Administrator')
            userDataStore.find_or_create_role(name='vendedor',
                                              description='Vendedor')
            userDataStore.find_or_create_role(name='almacenista',
                                              description='Almacenista')

            encrypted_password = generate_password_hash(
                'password',
                method='sha512')  #utils.encrypt_password('password')
            if not userDataStore.get_user('*****@*****.**'):
                userDataStore.create_user(email='*****@*****.**',
                                          password=encrypted_password,
                                          numero_empleado=232,
                                          nivel_escolar='Telesecundaria',
                                          profesion='Ama de casa',
                                          observaciones='Es a toda madre',
                                          idPersona=7,
                                          estatus=1)
                db.session.commit()
            if not userDataStore.get_user('*****@*****.**'):
                userDataStore.create_user(email='*****@*****.**',
                                          password=encrypted_password,
                                          numero_empleado=32,
                                          nivel_escolar='Telesecundaria',
                                          profesion='Ama de casa',
                                          observaciones='Es a toda madre',
                                          idPersona=5,
                                          estatus=1)
                db.session.commit()
            if not userDataStore.get_user('*****@*****.**'):
                userDataStore.create_user(email='*****@*****.**',
                                          password=encrypted_password,
                                          numero_empleado=2132,
                                          nivel_escolar='Telesecundaria',
                                          profesion='Ama de casa',
                                          observaciones='Es a toda madre',
                                          idPersona=6,
                                          estatus=1)
                db.session.commit()

            # Commit any database changes; the User and Roles must exist before we can add a Role to the User

        except Exception as inst:
            message = {"result": "error"}
            logging.error(
                str(type(inst)) + '\n Tipo de error: ' + str(inst) + '[' +
                str(datetime.now()) + ']')
            return render_template('error.html')

    security = Security(app, userDataStore)

    try:

        # Initialize Flask-Admin
        admin = Admin(app)

        # Add Flask-Admin views for Users and Roles
        admin.add_view(UserAdmin(User, db.session))
        admin.add_view(RoleAdmin(Role, db.session))

    except Exception as inst:
        message = {"result": "error"}
        logging.error(
            str(type(inst)) + '\n Tipo de error: ' + str(inst) + '[' +
            str(datetime.now()) + ']')
        return render_template('error.html')

    @app.route('/login', methods=['GET', 'POST'])
    def index_login_fail():

        if request.method == 'POST' and request.form['email']:
            return render_template('security/login.html')
            print(request.form.get('next'))
        else:
            return render_template('security/login.html')

    try:
        #Registramos el blueprint para el resto de la aplicación
        from .main import main as main_blueprint
        app.register_blueprint(main_blueprint)

        from .auth import auth as auth_blueprint
        app.register_blueprint(auth_blueprint)

        from .materialRutas import materialRutas as materialRutas_blueprint
        app.register_blueprint(materialRutas_blueprint)

        from .categoriasRutas import categoriasRutas as categoriasRutas_blueprint
        app.register_blueprint(categoriasRutas_blueprint)

        from .proveedorRutas import proveedorRutas as proveedorRutas_blueprint
        app.register_blueprint(proveedorRutas_blueprint)

        from .clienteRutas import clienteRutas as clienteRutas_blueprint
        app.register_blueprint(clienteRutas_blueprint)

        from .ventasRutas import ventasRutas as ventasRutas_blueprint
        app.register_blueprint(ventasRutas_blueprint)

        from .productoRutas import productoRutas as productoRutas_blueprint
        app.register_blueprint(productoRutas_blueprint)

        from .detalleProductoMaterialRutas import detalleProductoMaterialRutas as detalleProductoMaterialRutas_blueprint
        app.register_blueprint(detalleProductoMaterialRutas_blueprint)

        from .ordenCompraRutas import ordenCompraRutas as ordenCompraRutas_blueprint
        app.register_blueprint(ordenCompraRutas_blueprint)

        from .empleadoRutas import empleadoRutas as empleadoRutas_blueprint
        app.register_blueprint(empleadoRutas_blueprint)

    except Exception as inst:
        message = {"result": "error"}
        logging.error(
            str(type(inst)) + '\n Tipo de error: ' + str(inst) + '[' +
            str(datetime.now()) + ']')
        return render_template('error.html')

    logging.info('Incio de la aplicacion [' + str(datetime.now()) + ']')

    register_error_handlers(app)

    return app
Beispiel #27
0
def create_app(app_name=None):

    # Configuration settings
    import config
    if not app_name:
        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)
    app.config.update(dict(PROPAGATE_EXCEPTIONS=True))

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

    # Set SQLITE_PATH to TEST_SQLITE_PATH while running test cases
    if "PGADMIN_TESTING_MODE" in os. environ and \
                    os.environ["PGADMIN_TESTING_MODE"] == "1":
        config.SQLITE_PATH = config.TEST_SQLITE_PATH

    # Ensure the various working directories exist
    from pgadmin.setup import create_app_data_directory, db_upgrade
    create_app_data_directory(config)

    # File logging
    fh = logging.FileHandler(config.LOG_FILE, encoding='utf-8')
    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 language for the user."""
        language = 'en'
        if config.SERVER_MODE is False:
            # Get the user language preference from the miscellaneous module
            misc_preference = Preferences.module('miscellaneous', False)
            if misc_preference:
                user_languages = misc_preference.preference('user_language')
                if user_languages:
                    language = user_languages.get() or language
        else:
            # If language is available in get request then return the same
            # otherwise check the session or cookie
            data = request.form
            if 'language' in data:
                language = data['language'] or language
                setattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(session, 'PGADMIN_LANGUAGE'):
                language = getattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(request.cookies, 'PGADMIN_LANGUAGE'):
                language = getattr(request.cookies, 'PGADMIN_LANGUAGE',
                                   language)

        return language

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

    app.config[
        'SQLALCHEMY_DATABASE_URI'] = u'sqlite:///{0}?timeout={1}'.format(
            config.SQLITE_PATH.replace(u'\\', u'/'),
            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)

    ##########################################################################
    # Upgrade the schema (if required)
    ##########################################################################
    db_upgrade(app)

    Mail(app)

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

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

    ##########################################################################
    # Setup security
    ##########################################################################
    with app.app_context():
        config.CSRF_SESSION_KEY = Keys.query.filter_by(
            name='CSRF_SESSION_KEY').first().value
        config.SECRET_KEY = Keys.query.filter_by(
            name='SECRET_KEY').first().value
        config.SECURITY_PASSWORD_SALT = Keys.query.filter_by(
            name='SECURITY_PASSWORD_SALT').first().value

    # Update the app.config with proper security keyes for signing CSRF data,
    # signing cookies, and the SALT for hashing the passwords.
    app.config.update(dict(CSRF_SESSION_KEY=config.CSRF_SESSION_KEY))
    app.config.update(dict(SECRET_KEY=config.SECRET_KEY))
    app.config.update(
        dict(SECURITY_PASSWORD_SALT=config.SECURITY_PASSWORD_SALT))

    security.init_app(app)

    app.session_interface = create_session_interface(app)

    # Make the Session more secure against XSS & CSRF when running in web mode
    if config.SERVER_MODE:
        paranoid = Paranoid(app)
        paranoid.redirect_view = 'browser.index'

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

    ##########################################################################
    # Register language to the preferences after login
    ##########################################################################
    @user_logged_in.connect_via(app)
    def register_language(sender, user):
        # After logged in, set the language in the preferences if we get from
        # the login page
        data = request.form
        if 'language' in data:
            language = data['language']

            # Set the user language preference
            misc_preference = Preferences.module('miscellaneous')
            user_languages = misc_preference.preference('user_language')

            if user_languages and language:
                language = user_languages.set(language)

    ##########################################################################
    # 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 winreg is not None:
            arch_keys = set()
            proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()

            try:
                proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()
            except:
                proc_arch64 = None

            if proc_arch == 'x86' and not proc_arch64:
                arch_keys.add(0)
            elif proc_arch == 'x86' or proc_arch == 'amd64':
                arch_keys.add(winreg.KEY_WOW64_32KEY)
                arch_keys.add(winreg.KEY_WOW64_64KEY)

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

                            svr_name = winreg.QueryValueEx(
                                inst_key, 'Display Name')[0]
                            svr_superuser = winreg.QueryValueEx(
                                inst_key, 'Database Superuser')[0]
                            svr_port = winreg.QueryValueEx(inst_key, 'Port')[0]
                            svr_discovery_id = inst_id
                            svr_comment = gettext(
                                "Auto-detected %s installation with the data directory at %s"
                                % (winreg.QueryValueEx(inst_key,
                                                       'Display Name')[0],
                                   winreg.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-winreg.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
                    description = registry.get(section, 'Description')
                    data_directory = registry.get(section, 'DataDirectory')
                    if hasattr(str, 'decode'):
                        description = description.decode('utf-8')
                        data_directory = data_directory.decode('utf-8')
                    svr_comment = gettext(
                        u"Auto-detected %s installation with the data directory at %s"
                        % (description, data_directory))
                    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"""

        # Check the auth key is valid, if it's set, and we're not in server
        # mode, and it's not a help file request.
        if not config.SERVER_MODE and app.PGADMIN_KEY != '':
            if ((not 'key' in request.args
                 or request.args['key'] != app.PGADMIN_KEY)
                    and request.cookies.get('PGADMIN_KEY') != app.PGADMIN_KEY
                    and request.endpoint != 'help.static'):
                abort(401)

        if not config.SERVER_MODE:
            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)

    @app.after_request
    def after_request(response):
        if 'key' in request.args:
            response.set_cookie('PGADMIN_KEY', value=request.args['key'])

        return response

    ##########################################################################
    # Minify output
    ##########################################################################
    # HTMLMIN doesn't work with Python 2.6.
    if not config.DEBUG and sys.version_info >= (2, 7):
        HTMLMIN(app)

    @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!
    ##########################################################################

    return app
Beispiel #28
0
 def create():
     app.security = Security(app, datastore=pony_datastore)
     return app
Beispiel #29
0
app = Flask(__name__)
app.config.from_object(Config)

# Database ---------------------------------------------------------------------

model.db.init_app(app)
migrations_dir = app.config.get('MIGRATE_DIRECTORY', 'data/migrations')
Migrate(app, model.db, migrations_dir, render_as_batch=True)

# Security ---------------------------------------------------------------------

LoginForm.email.label = wtf.Label('email', _l('Username or e-mail'))
LoginForm.password.label = wtf.Label('password', _l('Password'))
LoginForm.submit.label = wtf.Label('submit', _l('Log in'))

Security(app, SQLAlchemyUserDatastore(model.db, model.User, model.Role))

# Frontend ---------------------------------------------------------------------

admin.admin.init_app(app)
Bootstrap(app)

# Translations -----------------------------------------------------------------

domain = Domain(app.config.get("BABEL_TRANSLATIONS")[0], "messages")
babel = Babel(app, default_domain=domain)
babel.domain = "messages"
babel.translation_directories = app.config.get("BABEL_TRANSLATIONS")


@babel.localeselector
Beispiel #30
0
 def create_app(info):
     app.config.update(
         **{'SECURITY_USER_IDENTITY_ATTRIBUTES': ('email', 'username')})
     app.security = Security(app, datastore=datastore)
     return app
Beispiel #31
0
import config

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from flask.ext.security import SQLAlchemyUserDatastore
from .models import User, Role
ud = SQLAlchemyUserDatastore(db, User, Role)

from flask.ext.mail import Mail
mail = Mail()

from pyelasticsearch import ElasticSearch
es = ElasticSearch(config.ELASTICSEARCH_SERVER)

from flask_security import Security
sec = Security()
sec.datastore = ud

class HSSError(Exception):
    def __init__(self, msg):
        self.msg = msg
Beispiel #32
0
def create_app(app_name=None):
    # Configuration settings
    import config
    if not app_name:
        app_name = config.APP_NAME

    # Check if app is created for CLI operations or Web
    cli_mode = False
    if app_name.endswith('-cli'):
        cli_mode = True

    # Only enable password related functionality in server mode.
    if config.SERVER_MODE is True:
        # Some times we need to access these config params where application
        # context is not available (we can't use current_app.config in those
        # cases even with current_app.app_context())
        # So update these params in config itself.
        # And also these updated config values will picked up by application
        # since we are updating config before the application instance is
        # created.

        config.SECURITY_RECOVERABLE = True
        config.SECURITY_CHANGEABLE = True
        # Now we'll open change password page in alertify dialog
        # we don't want it to redirect to main page after password
        # change operation so we will open the same password change page again.
        config.SECURITY_POST_CHANGE_VIEW = 'browser.change_password'

    """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)
    app.config.update(dict(PROPAGATE_EXCEPTIONS=True))

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

    # We won't care about errors in the logging system, we are more
    # interested in application errors.
    logging.raiseExceptions = False

    # 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(config.CONSOLE_LOG_LEVEL)

    # Set SQLITE_PATH to TEST_SQLITE_PATH while running test cases
    if (
        'PGADMIN_TESTING_MODE' in os.environ and
        os.environ['PGADMIN_TESTING_MODE'] == '1'
    ):
        config.SQLITE_PATH = config.TEST_SQLITE_PATH
        config.MASTER_PASSWORD_REQUIRED = False
        config.UPGRADE_CHECK_ENABLED = False

    if not cli_mode:
        # Ensure the various working directories exist
        from pgadmin.setup import create_app_data_directory
        create_app_data_directory(config)

        # File logging
        fh = logging.FileHandler(config.LOG_FILE, encoding='utf-8')
        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 language for the user."""
        language = 'en'
        if config.SERVER_MODE is False:
            # Get the user language preference from the miscellaneous module
            if current_user.is_authenticated:
                user_id = current_user.id
            else:
                user = user_datastore.get_user(config.DESKTOP_USER)
                if user is not None:
                    user_id = user.id
            user_language = Preferences.raw_value(
                'misc', 'user_language', 'user_language', user_id
            )
            if user_language is not None:
                language = user_language
        else:
            # If language is available in get request then return the same
            # otherwise check the session or cookie
            data = request.form
            if 'language' in data:
                language = data['language'] or language
                setattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(session, 'PGADMIN_LANGUAGE'):
                language = getattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(request.cookies, 'PGADMIN_LANGUAGE'):
                language = getattr(
                    request.cookies, 'PGADMIN_LANGUAGE', language
                )

        return language

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

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

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

    ##########################################################################
    # Upgrade the schema (if required)
    ##########################################################################
    with app.app_context():
        # Run migration for the first time i.e. create database
        from config import SQLITE_PATH
        from pgadmin.setup import db_upgrade

        # If version not available, user must have aborted. Tables are not
        # created and so its an empty db
        if not os.path.exists(SQLITE_PATH) or get_version() == -1:
            # If running in cli mode then don't try to upgrade, just raise
            # the exception
            if not cli_mode:
                db_upgrade(app)
            else:
                if not os.path.exists(SQLITE_PATH):
                    raise FileNotFoundError(
                        'SQLite database file "' + SQLITE_PATH +
                        '" does not exists.')
                raise Exception('Specified SQLite database file is not valid.')
        else:
            schema_version = get_version()

            # Run migration if current schema version is greater than the
            # schema version stored in version table
            if CURRENT_SCHEMA_VERSION >= schema_version:
                db_upgrade(app)

            # Update schema version to the latest
            if CURRENT_SCHEMA_VERSION > schema_version:
                set_version(CURRENT_SCHEMA_VERSION)
                db.session.commit()

        if os.name != 'nt':
            os.chmod(config.SQLITE_PATH, 0o600)

    Mail(app)

    # Don't bother paths when running in cli mode
    if not cli_mode:
        import pgadmin.utils.paths as paths
        paths.init_app(app)

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

    ##########################################################################
    # Setup security
    ##########################################################################
    with app.app_context():
        config.CSRF_SESSION_KEY = Keys.query.filter_by(
            name='CSRF_SESSION_KEY').first().value
        config.SECRET_KEY = Keys.query.filter_by(
            name='SECRET_KEY').first().value
        config.SECURITY_PASSWORD_SALT = Keys.query.filter_by(
            name='SECURITY_PASSWORD_SALT').first().value

    # Update the app.config with proper security keyes for signing CSRF data,
    # signing cookies, and the SALT for hashing the passwords.
    app.config.update(dict({
        'CSRF_SESSION_KEY': config.CSRF_SESSION_KEY,
        'SECRET_KEY': config.SECRET_KEY,
        'SECURITY_PASSWORD_SALT': config.SECURITY_PASSWORD_SALT,
        'SESSION_COOKIE_DOMAIN': config.SESSION_COOKIE_DOMAIN,
        # CSRF Token expiration till session expires
        'WTF_CSRF_TIME_LIMIT': getattr(config, 'CSRF_TIME_LIMIT', None),
        'WTF_CSRF_METHODS': ['GET', 'POST', 'PUT', 'DELETE'],
    }))

    security.init_app(app, user_datastore)

    # register custom unauthorised handler.
    app.login_manager.unauthorized_handler(pga_unauthorised)

    # Set the permanent session lifetime to the specified value in config file.
    app.permanent_session_lifetime = timedelta(
        days=config.SESSION_EXPIRATION_TIME)

    if not cli_mode:
        app.session_interface = create_session_interface(
            app, config.SESSION_SKIP_PATHS
        )

    # Make the Session more secure against XSS & CSRF when running in web mode
    if config.SERVER_MODE and config.ENHANCED_COOKIE_PROTECTION:
        paranoid = Paranoid(app)
        paranoid.redirect_view = 'browser.index'

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

    ##########################################################################
    # Register language to the preferences after login
    ##########################################################################
    @user_logged_in.connect_via(app)
    def register_language(sender, user):
        # After logged in, set the language in the preferences if we get from
        # the login page
        data = request.form
        if 'language' in data:
            language = data['language']

            # Set the user language preference
            misc_preference = Preferences.module('misc')
            user_languages = misc_preference.preference(
                'user_language'
            )

            if user_languages and language:
                language = user_languages.set(language)

    ##########################################################################
    # 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 winreg is not None:
            arch_keys = set()
            proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()

            try:
                proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()
            except Exception:
                proc_arch64 = None

            if proc_arch == 'x86' and not proc_arch64:
                arch_keys.add(0)
            elif proc_arch == 'x86' or proc_arch == 'amd64':
                arch_keys.add(winreg.KEY_WOW64_32KEY)
                arch_keys.add(winreg.KEY_WOW64_64KEY)

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

                            svr_name = winreg.QueryValueEx(
                                inst_key, 'Display Name'
                            )[0]
                            svr_superuser = winreg.QueryValueEx(
                                inst_key, 'Database Superuser'
                            )[0]
                            svr_port = winreg.QueryValueEx(inst_key, 'Port')[0]
                            svr_discovery_id = inst_id
                            svr_comment = gettext(
                                "Auto-detected {0} installation with the data "
                                "directory at {1}").format(
                                    winreg.QueryValueEx(
                                        inst_key, 'Display Name'
                                    )[0],
                                    winreg.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 Exception:
                        pass
        else:
            # We use the postgres-winreg.ini file on non-Windows
            from configparser import ConfigParser

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

                    # getint function throws exception if value is blank.
                    # Ex: Port=
                    # In such case we should handle the exception and continue
                    # to read the next section of the config file.
                    try:
                        svr_port = registry.getint(section, 'Port')
                    except ValueError:
                        continue

                    svr_discovery_id = section
                    description = registry.get(section, 'Description')
                    data_directory = registry.get(section, 'DataDirectory')
                    if hasattr(str, 'decode'):
                        description = description.decode('utf-8')
                        data_directory = data_directory.decode('utf-8')
                    svr_comment = gettext(u"Auto-detected {0} installation "
                                          u"with the data directory at {1}"
                                          ).format(description, data_directory)
                    add_server(user_id, servergroup_id, svr_name,
                               svr_superuser, svr_port, svr_discovery_id,
                               svr_comment)

        except Exception:
            pass

    @user_logged_in.connect_via(app)
    @user_logged_out.connect_via(app)
    def force_session_write(app, user):
        session.force_write = True

    @user_logged_in.connect_via(app)
    def store_crypt_key(app, user):
        # in desktop mode, master password is used to encrypt/decrypt
        # and is stored in the keyManager memory
        if config.SERVER_MODE and 'password' in request.form:
            current_app.keyManager.set(request.form['password'])

    @user_logged_out.connect_via(app)
    def current_user_cleanup(app, user):
        from config import PG_DEFAULT_DRIVER
        from pgadmin.utils.driver import get_driver
        from flask import current_app

        # remove key
        current_app.keyManager.reset()

        for mdl in current_app.logout_hooks:
            try:
                mdl.on_logout(user)
            except Exception as e:
                current_app.logger.exception(e)

        _driver = get_driver(PG_DEFAULT_DRIVER)
        _driver.gc_own()

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

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

    @app.before_request
    def before_request():
        """Login the default user if running in desktop mode"""

        # Check the auth key is valid, if it's set, and we're not in server
        # mode, and it's not a help file request.
        if not config.SERVER_MODE and app.PGADMIN_INT_KEY != '' and ((
            'key' not in request.args or
            request.args['key'] != app.PGADMIN_INT_KEY) and
            request.cookies.get('PGADMIN_INT_KEY') != app.PGADMIN_INT_KEY and
            request.endpoint != 'help.static'
        ):
            abort(401)

        if not config.SERVER_MODE and not current_user.is_authenticated:
            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)

        # if the server is restarted the in memory key will be lost
        # but the user session may still be active. Logout the user
        # to get the key again when login
        if config.SERVER_MODE and current_user.is_authenticated and \
                current_app.keyManager.get() is None and \
                request.endpoint not in ('security.login', 'security.logout'):
            logout_user()

    @app.after_request
    def after_request(response):
        if 'key' in request.args:
            domain = dict()
            if config.COOKIE_DEFAULT_DOMAIN and \
                    config.COOKIE_DEFAULT_DOMAIN != 'localhost':
                domain['domain'] = config.COOKIE_DEFAULT_DOMAIN
            response.set_cookie('PGADMIN_INT_KEY', value=request.args['key'],
                                path=config.COOKIE_DEFAULT_PATH,
                                **domain)

        # X-Frame-Options for security
        if config.X_FRAME_OPTIONS != "" and \
                config.X_FRAME_OPTIONS.lower() != "deny":
            response.headers["X-Frame-Options"] = config.X_FRAME_OPTIONS

        return response

    ##########################################################################
    # Cache busting
    ##########################################################################

    # Version number to be added to all static file url requests
    # This is used by url_for function when generating urls
    # This will solve caching issues when application is upgrading
    # This is called - Cache Busting
    @app.url_defaults
    def add_internal_version(endpoint, values):
        extensions = config.APP_VERSION_EXTN

        # Add the internal version only if it is set
        if config.APP_VERSION_PARAM is not None and \
           config.APP_VERSION_PARAM != '':
            # If there is a filename, add the version
            if 'filename' in values \
               and values['filename'].endswith(extensions):
                values[config.APP_VERSION_PARAM] = config.APP_VERSION_INT
            else:
                # Sometimes there may be direct endpoint for some files
                # There will be only one rule for such endpoints
                urls = [url for url in app.url_map.iter_rules(endpoint)]
                if len(urls) == 1 and urls[0].rule.endswith(extensions):
                    values[config.APP_VERSION_PARAM] = \
                        config.APP_VERSION_INT

    # Strip away internal version param before sending further to app as it was
    # required for cache busting only
    @app.url_value_preprocessor
    def strip_version_number(endpoint, values):
        if values and config.APP_VERSION_PARAM in values:
            values.pop(config.APP_VERSION_PARAM)

    ##########################################################################
    # Minify output. Not required in desktop mode
    ##########################################################################
    if not config.DEBUG and config.SERVER_MODE:
        from flask_compress import Compress
        Compress(app)

    from pgadmin.misc.themes import themes
    themes(app)

    @app.context_processor
    def inject_blueprint():
        """
        Inject a reference to the current blueprint, if any.
        """

        return {
            'current_app': current_app,
            'current_blueprint': current_blueprint,
        }

    @app.errorhandler(Exception)
    def all_exception_handler(e):
        current_app.logger.error(e, exc_info=True)
        return internal_server_error(errormsg=str(e))

    # Exclude HTTPexception from above handler (all_exception_handler)
    # HTTPException are user defined exceptions and those should be returned
    # as is
    @app.errorhandler(HTTPException)
    def http_exception_handler(e):
        current_app.logger.error(e, exc_info=True)
        return e

    # Intialize the key manager
    app.keyManager = KeyManager()

    ##########################################################################
    # Protection against CSRF attacks
    ##########################################################################
    with app.app_context():
        pgCSRFProtect.init_app(app)

    ##########################################################################
    # All done!
    ##########################################################################
    return app
Beispiel #33
0
class InvenioAccounts(object):
    """Invenio-Accounts extension."""

    def __init__(self, app=None):
        """Extension initialization."""
        self.security = Security()
        self.datastore = None
        if app:
            self.init_app(app)

    def init_app(self, app, use_celery=True):
        """Flask application initialization."""
        self.init_config(app)

        # Create user datastore
        self.datastore = SQLAlchemyUserDatastore(db, User, Role)

        # Initialize extension.
        state = self.security.init_app(app, datastore=self.datastore)

        if app.config['ACCOUNTS_USE_CELERY']:
            from invenio_accounts.tasks import send_security_email

            @state.send_mail_task
            def delay_security_email(msg):
                send_security_email.delay(msg)

        # Register CLI
        app.cli.add_command(roles_cli, 'roles')
        app.cli.add_command(users_cli, 'users')

        app.extensions['invenio-accounts'] = self

    def init_config(self, app):
        """Initialize configuration."""
        try:
            pkg_resources.get_distribution('celery')
            app.config.setdefault("ACCOUNTS_USE_CELERY", True)
        except pkg_resources.DistributionNotFound:
            app.config.setdefault("ACCOUNTS_USE_CELERY", False)

        app.config.setdefault('ACCOUNTS', True)

        # Change Flask-Security defaults
        app.config.setdefault('SECURITY_CHANGEABLE', True)
        app.config.setdefault('SECURITY_CONFIRMABLE', True)
        app.config.setdefault('SECURITY_PASSWORD_HASH', 'pbkdf2_sha512')
        app.config.setdefault('SECURITY_PASSWORD_SCHEMES', ['pbkdf2_sha512'])
        app.config.setdefault('SECURITY_DEPRECATED_PASSWORD_SCHEMES', [])
        app.config.setdefault('SECURITY_RECOVERABLE', True)
        app.config.setdefault('SECURITY_REGISTERABLE', True)
        app.config.setdefault('SECURITY_TRACKABLE', True)
        app.config.setdefault('SECURITY_LOGIN_WITHOUT_CONFIRMATION', True)
        app.config.setdefault('SECURITY_PASSWORD_SALT',
                              app.config['SECRET_KEY'])

        # Change default templates
        app.config.setdefault("SECURITY_FORGOT_PASSWORD_TEMPLATE",
                              "invenio_accounts/forgot_password.html")
        app.config.setdefault("SECURITY_LOGIN_USER_TEMPLATE",
                              "invenio_accounts/login_user.html")
        app.config.setdefault("SECURITY_REGISTER_USER_TEMPLATE",
                              "invenio_accounts/register_user.html")
        app.config.setdefault("SECURITY_RESET_PASSWORD_TEMPLATE",
                              "invenio_accounts/reset_password.html")
        app.config.setdefault("SECURITY_CHANGE_PASSWORD_TEMPLATE",
                              "invenio_accounts/change_password.html")
        app.config.setdefault("SECURITY_SEND_CONFIRMATION_TEMPLATE",
                              "invenio_accounts/send_confirmation.html")
        app.config.setdefault("SECURITY_SEND_LOGIN_TEMPLATE",
                              "invenio_accounts/send_login.html")
        app.config.setdefault("SECURITY_REGISTER_URL",
                              "/signup")
Beispiel #34
0
def create_app(ENV_SETTING):
    app = Flask(__name__, instance_relative_config=True)

    #configuration
    app.config.from_object(app_config[ENV_SETTING])

    # Logging configuration
    logging.config.dictConfig(yaml.load(open(app.config['LOGGING_FILEPATH'])))

    # Yaml Loader to load css and js
    assets = Environment(app)
    loader = YAMLLoader(app.config['ASSETS_FILEPATH']).load_bundles()
    load_assets(assets, loader)

    #database init
    db.init_app(app)
    # with app.app_context():
    #     create_user(app,db)
    #flask_admin
    admin = Admin(app, index_view=AdminIndexCustomView(url=None,endpoint=None) , name='Admin Panel', base_template='admin/my_master.html', template_mode='bootstrap3')
    # Mail
    mail.init_app(app)
    # csrf
    csrf.init_app(app)
    #SSL
    sslify = SSLify(app)
    #setting babelex
    babel = Babel(app)
    @babel.localeselector
    def get_locale():
        # if the user has set up the language manually it will be stored in the session,
        # so we use the locale from the user settings
        try:
            language = session['language']
        except KeyError:
            language = None
        if language is not None:
            return language
        return request.accept_languages.best_match(app.config['LANGUAGES'].keys())

    # Inject to JINJA Template
    app.context_processor(inject_current_language)
    app.context_processor(inject_all_languages)
    app.context_processor(inject_google_token)
    app.context_processor(inject_total_notification)
    app.context_processor(inject_tasks)

    # Template Filter
    app.jinja_env.globals['momentjs'] = momentjs

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

    # Integrate Flask Security with Flask Admin
    @security.context_processor
    def security_context_processor():
        return dict(
            admin_base_template=admin.base_template,
            admin_view=admin.index_view,
            h=admin_helpers,
            get_url=url_for
        )

    # Admin Views
    load_admin_views(admin, db)
    # Blueprint Views
    load_blueprints(app)
    # Register Error Handling
    app.register_error_handler(400, bad_request)
    app.register_error_handler(404, page_not_found)
    app.register_error_handler(403, page_forbidden)
    app.register_error_handler(500, page_server_error)
    app.logger.info('app started')

    return app
Beispiel #35
0
def create_app(config=None):
    """ config should be a python file """
    from pathlib import Path

    from flask import (Flask,
            current_app,
            g,
            session,
            url_for,
            render_template)

    from flask_sqlalchemy import SQLAlchemy
    from flask_security import (Security, SQLAlchemyUserDatastore)

    from flask_wtf.csrf import CsrfProtect

    from flask_assets import (Environment, Bundle)

    from .app_setup import (init_db, setup_dirs)
    from .core import (db, load_blueprints, setup_logger)
    from .lib.template_filters import (
        fmt_datetime,
        none_as_str,
        next_page_url,
        prev_page_url,
        get_page_url,
        get_images)

    from .models.user import (User, Role, user_datastore)

    from .Admin import (index, series, images, texts, contact)
    from .Public import (index, contact, texts)
    from .Security import user

    app = Flask(__name__.split('.')[0], instance_relative_config=True)

    app.config.from_object('config')
    app.config.from_pyfile('config.py')

    if config is not None:
        app.config.from_pyfile(config)
        setup_logger(app)
        app.logger.info('Started with config from: {}'.format(config))
    else:
        setup_logger(app)
        app.logger.info('Started App')

    # Flask.sqlalchemy
    db.init_app(app)

    load_blueprints(app)

    # make sure db tables and required directories exist
    before_first_request_funcs = [setup_dirs(app),
                                  init_db(app)]

    #Security
    csrf = CsrfProtect()
    csrf.init_app(app)
    security = Security()
    security.init_app(app, user_datastore, register_blueprint=False)

    # Assets
    assets = Environment(app=app)
    assets.from_yaml('assets.yml')

    # template filters
    app.add_template_filter(fmt_datetime)
    app.add_template_filter(none_as_str)
    app.add_template_filter(next_page_url)
    app.add_template_filter(prev_page_url)
    app.add_template_filter(get_page_url)
    app.add_template_filter(get_images)

    return app
Beispiel #36
0
        db.Integer(),
        db.ForeignKey('user.id', ondelete="CASCADE")),
    db.Column(
        'committee_id',
        db.Integer(),
        db.ForeignKey('committee.id', ondelete="CASCADE")),
    db.Column(
        'created_at',
        db.DateTime(timezone=True),
        index=True,
        unique=False,
        nullable=False,
        server_default=func.now()))

user_committee_alerts = db.Table(
    'user_committee_alerts',
    db.Column(
        'user_id',
        db.Integer(),
        db.ForeignKey('user.id', ondelete="CASCADE")),
    db.Column(
        'committee_id',
        db.Integer(),
        db.ForeignKey('committee.id', ondelete="CASCADE")))


# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore, confirm_register_form=forms.RegisterForm, send_confirmation_form=forms.SendConfirmationForm)
user_confirmed.connect(user_confirmed_handler, app)
Beispiel #37
0
class InvenioAccounts(object):
    """Invenio-Accounts extension."""

    def __init__(self, app=None, sessionstore=None):
        """Extension initialization."""
        self.security = Security()
        self.datastore = None
        if app:
            self.init_app(app, sessionstore=sessionstore)

    def init_app(self, app, use_celery=True, sessionstore=None):
        """Flask application initialization.

        :param sessionstore: store for sessions. Passed to
            ``flask-kvsession``. Defaults to redis.
        """
        self.init_config(app)

        # Create user datastore
        self.datastore = SQLAlchemyUserDatastore(db, User, Role)

        # Create sessionstore
        if sessionstore is None:
            import redis
            from simplekv.memory.redisstore import RedisStore

            sessionstore = RedisStore(redis.StrictRedis.from_url(
                app.config['ACCOUNTS_SESSION_REDIS_URL']))

        self.sessionstore = sessionstore
        user_logged_in.connect(login_listener, app)

        # Initialize extension.
        state = self.security.init_app(app, datastore=self.datastore)
        self.kvsession_extension = KVSessionExtension(self.sessionstore, app)

        if app.config['ACCOUNTS_USE_CELERY']:
            from invenio_accounts.tasks import send_security_email

            @state.send_mail_task
            def delay_security_email(msg):
                send_security_email.delay(msg.__dict__)

        # Register CLI
        app.cli.add_command(roles_cli, 'roles')
        app.cli.add_command(users_cli, 'users')

        app.extensions['invenio-accounts'] = self

    def init_config(self, app):
        """Initialize configuration."""
        try:
            pkg_resources.get_distribution('celery')
            app.config.setdefault(
                "ACCOUNTS_USE_CELERY", not (app.debug or app.testing))
        except pkg_resources.DistributionNotFound:
            app.config.setdefault("ACCOUNTS_USE_CELERY", False)

        app.config.setdefault('ACCOUNTS', True)

        # Change Flask-Security defaults
        app.config.setdefault('SECURITY_CHANGEABLE', True)
        app.config.setdefault('SECURITY_CONFIRMABLE', True)
        app.config.setdefault('SECURITY_PASSWORD_HASH', 'pbkdf2_sha512')
        app.config.setdefault('SECURITY_PASSWORD_SCHEMES', ['pbkdf2_sha512'])
        app.config.setdefault('SECURITY_DEPRECATED_PASSWORD_SCHEMES', [])
        app.config.setdefault('SECURITY_RECOVERABLE', True)
        app.config.setdefault('SECURITY_REGISTERABLE', True)
        app.config.setdefault('SECURITY_TRACKABLE', True)
        app.config.setdefault('SECURITY_LOGIN_WITHOUT_CONFIRMATION', True)
        app.config.setdefault('SECURITY_PASSWORD_SALT',
                              app.config['SECRET_KEY'])

        # Change default templates
        app.config.setdefault("SECURITY_FORGOT_PASSWORD_TEMPLATE",
                              "invenio_accounts/forgot_password.html")
        app.config.setdefault("SECURITY_LOGIN_USER_TEMPLATE",
                              "invenio_accounts/login_user.html")
        app.config.setdefault("SECURITY_REGISTER_USER_TEMPLATE",
                              "invenio_accounts/register_user.html")
        app.config.setdefault("SECURITY_RESET_PASSWORD_TEMPLATE",
                              "invenio_accounts/reset_password.html")
        app.config.setdefault("SECURITY_CHANGE_PASSWORD_TEMPLATE",
                              "invenio_accounts/change_password.html")
        app.config.setdefault("SECURITY_SEND_CONFIRMATION_TEMPLATE",
                              "invenio_accounts/send_confirmation.html")
        app.config.setdefault("SECURITY_SEND_LOGIN_TEMPLATE",
                              "invenio_accounts/send_login.html")
        app.config.setdefault("SECURITY_REGISTER_URL",
                              "/signup/")
        app.config.setdefault("SECURITY_RESET_URL",
                              "/lost-password/")
        app.config.setdefault("SECURITY_LOGIN_URL",
                              "/login/")
        app.config.setdefault("SECURITY_LOGOUT_URL",
                              "/logout/")
        app.config.setdefault("SECURITY_CHANGE_URL",
                              "/accounts/settings/password/")

        for k in dir(config):
            if k.startswith('ACCOUNTS_'):
                app.config.setdefault(k, getattr(config, k))
Beispiel #38
0
# coding=utf-8
from flask import current_app
from flask_babel import Babel
from flask_cache import Cache
from flask_login import LoginManager
from flask_mail import Mail
from flask_mako import MakoTemplates
from flask_mongoengine import MongoEngine
from flask_redis import FlaskRedis
from flask_restful import Api
from flask_security import Security
from werkzeug.local import LocalProxy

api = Api()
babel = Babel()
cache = Cache()
db = MongoEngine()
login_manager = LoginManager()
mail = Mail()
mako = MakoTemplates()
redis_store = FlaskRedis()
security = Security()

logger = LocalProxy(lambda: current_app.logger)
Beispiel #39
0
from app import app, models, forms, Config
from flask import render_template, flash, request
from flask_security import Security, SQLAlchemyUserDatastore, login_required
from flask_login import current_user

# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(models.db, models.User, models.Role)
security = Security(app, user_datastore,login_form=forms.ExtendedLoginForm)

# Create a user to test with
#@app.before_first_request
#def create_user():
#    models.db.create_all()
#    user_datastore.create_user(name='<name>', password='******')
#    models.db.session.commit()

@app.errorhandler(401)
def auth_error():
    return render_template("401.html")

@app.errorhandler(404)
def page_not_found():
    return render_template("404.html")

@app.route('/')
@app.route('/index')
def index():
    if current_user.is_authenticated:
        user_id = current_user.get_id()
        user_name = models.User.query.filter_by(id=user_id).first()
        return render_template('index.html',
Beispiel #40
0
def create_app(config_name):
    global user_datastore
    app = Flask(__name__)

    app.config.from_object(app_config[config_name])

    csrf = CSRFProtect()
    csrf.init_app(app)

    assets = Environment(app)
    create_assets(assets)

    via = Via()
    via.init_app(app)

    # Ipload in several models - - - -

    from app.user import user_photo
    from app.restaurant import restaurant_photo
    from app.food import food_photo

    configure_uploads(app, (restaurant_photo, food_photo, user_photo))

    engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
    if not database_exists(engine.url):
        create_database(engine.url)

    security = Security(app, user_datastore, register_form=SecurityRegisterForm)

    create_security_admin(app=app, path=os.path.join(os.path.dirname(__file__)))

    with app.app_context():
        db.init_app(app)
        #Conditionally create admin/end_user
        db.create_all()
        user_datastore.find_or_create_role(name='admin', description='Administrator')

        db.session.commit()
        user_datastore.find_or_create_role(name='end-user', description='End user')
        db.session.commit()

        # Create two Users for testing purposes -- unless they already exists.
        # In each case, use Flask-Security utility function to encrypt the password.
        encrypted_password = utils.encrypt_password('password')
        if not user_datastore.get_user('*****@*****.**'):
            user_datastore.create_user(email='*****@*****.**', password=encrypted_password)
        if not user_datastore.get_user('*****@*****.**'):
            user_datastore.create_user(email='*****@*****.**', password=encrypted_password)

        # Commit any database changes; the User and Roles must exist before we can add a Role to the User
        db.session.commit()

        # Give one User has the "end-user" role, while the other has the "admin" role. (This will have no effect if the
        # Users already have these Roles.) Again, commit any database changes.
        user_datastore.add_role_to_user('*****@*****.**', 'end-user')
        user_datastore.add_role_to_user('*****@*****.**', 'admin')
        db.session.commit()


    @app.route('/', methods=['GET'])
    @app.route('/home', methods=['GET'])    
    def index():
        return render_template('index.html')

    @app.errorhandler(403)
    def forbidden(error):
        return render_template('error/403.html', title='Forbidden'), 403

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('error/404.html', title='Page Not Found'), 404

    @app.errorhandler(500)
    def internal_server_error(error):
        db.session.rollback()
        return render_template('error/500.html', title='Server Error'), 500

    return app
Beispiel #41
0
 def create():
     app.security = Security(app, datastore=mongoengine_datastore)
     return app
def test_access_datastore_from_factory(app, datastore):
    security = Security()
    security.init_app(app, datastore)

    assert security.datastore is not None
    assert security.app is not None
Beispiel #43
0
def test_register_blueprint_flag(app, sqlalchemy_datastore):
    app.security = Security(app, datastore=Security, register_blueprint=False)
    client = app.test_client()
    response = client.get("/login")
    assert response.status_code == 404
Beispiel #44
0
def create_app(app_name=None):
    # Configuration settings
    import config
    if not app_name:
        app_name = config.APP_NAME

    # Only enable password related functionality in server mode.
    if config.SERVER_MODE is True:
        # Some times we need to access these config params where application
        # context is not available (we can't use current_app.config in those
        # cases even with current_app.app_context())
        # So update these params in config itself.
        # And also these updated config values will picked up by application
        # since we are updating config before the application instance is
        # created.

        config.SECURITY_RECOVERABLE = True
        config.SECURITY_CHANGEABLE = True
        # Now we'll open change password page in alertify dialog
        # we don't want it to redirect to main page after password
        # change operation so we will open the same password change page again.
        config.SECURITY_POST_CHANGE_VIEW = 'browser.change_password'

    """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)
    app.config.update(dict(PROPAGATE_EXCEPTIONS=True))

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

    # Set SQLITE_PATH to TEST_SQLITE_PATH while running test cases
    if (
        'PGADMIN_TESTING_MODE' in os.environ and
        os.environ['PGADMIN_TESTING_MODE'] == '1'
    ):
        config.SQLITE_PATH = config.TEST_SQLITE_PATH

    # Ensure the various working directories exist
    from pgadmin.setup import create_app_data_directory, db_upgrade
    create_app_data_directory(config)

    # File logging
    fh = logging.FileHandler(config.LOG_FILE, encoding='utf-8')
    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 language for the user."""
        language = 'en'
        if config.SERVER_MODE is False:
            # Get the user language preference from the miscellaneous module
            if current_user.is_authenticated:
                user_id = current_user.id
            else:
                user = user_datastore.get_user(config.DESKTOP_USER)
                if user is not None:
                    user_id = user.id
            user_language = Preferences.raw_value(
                'miscellaneous', 'user_language', None, user_id
            )
            if user_language is not None:
                language = user_language
        else:
            # If language is available in get request then return the same
            # otherwise check the session or cookie
            data = request.form
            if 'language' in data:
                language = data['language'] or language
                setattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(session, 'PGADMIN_LANGUAGE'):
                language = getattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(request.cookies, 'PGADMIN_LANGUAGE'):
                language = getattr(
                    request.cookies, 'PGADMIN_LANGUAGE', language
                )

        return language

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

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

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

    ##########################################################################
    # Upgrade the schema (if required)
    ##########################################################################
    with app.app_context():
        # Run migration for the first time i.e. create database
        from config import SQLITE_PATH
        if not os.path.exists(SQLITE_PATH):
            db_upgrade(app)
        else:
            version = Version.query.filter_by(name='ConfigDB').first()
            schema_version = version.value

            # Run migration if current schema version is greater than the
            # schema version stored in version table
            if CURRENT_SCHEMA_VERSION >= schema_version:
                db_upgrade(app)

            # Update schema version to the latest
            if CURRENT_SCHEMA_VERSION > schema_version:
                version = Version.query.filter_by(name='ConfigDB').first()
                version.value = CURRENT_SCHEMA_VERSION
                db.session.commit()

    Mail(app)

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

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

    ##########################################################################
    # Setup security
    ##########################################################################
    with app.app_context():
        config.CSRF_SESSION_KEY = Keys.query.filter_by(
            name='CSRF_SESSION_KEY').first().value
        config.SECRET_KEY = Keys.query.filter_by(
            name='SECRET_KEY').first().value
        config.SECURITY_PASSWORD_SALT = Keys.query.filter_by(
            name='SECURITY_PASSWORD_SALT').first().value

    # Update the app.config with proper security keyes for signing CSRF data,
    # signing cookies, and the SALT for hashing the passwords.
    app.config.update(dict({
        'CSRF_SESSION_KEY': config.CSRF_SESSION_KEY,
        'SECRET_KEY': config.SECRET_KEY,
        'SECURITY_PASSWORD_SALT': config.SECURITY_PASSWORD_SALT,
        'SESSION_COOKIE_DOMAIN': config.SESSION_COOKIE_DOMAIN
    }))

    security.init_app(app, user_datastore)

    # register custom unauthorised handler.
    app.login_manager.unauthorized_handler(pga_unauthorised)

    app.session_interface = create_session_interface(app)

    # Make the Session more secure against XSS & CSRF when running in web mode
    if config.SERVER_MODE:
        paranoid = Paranoid(app)
        paranoid.redirect_view = 'browser.index'

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

    ##########################################################################
    # Register language to the preferences after login
    ##########################################################################
    @user_logged_in.connect_via(app)
    def register_language(sender, user):
        # After logged in, set the language in the preferences if we get from
        # the login page
        data = request.form
        if 'language' in data:
            language = data['language']

            # Set the user language preference
            misc_preference = Preferences.module('miscellaneous')
            user_languages = misc_preference.preference(
                'user_language'
            )

            if user_languages and language:
                language = user_languages.set(language)

    ##########################################################################
    # 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 winreg is not None:
            arch_keys = set()
            proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()

            try:
                proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()
            except Exception as e:
                proc_arch64 = None

            if proc_arch == 'x86' and not proc_arch64:
                arch_keys.add(0)
            elif proc_arch == 'x86' or proc_arch == 'amd64':
                arch_keys.add(winreg.KEY_WOW64_32KEY)
                arch_keys.add(winreg.KEY_WOW64_64KEY)

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

                            svr_name = winreg.QueryValueEx(
                                inst_key, 'Display Name'
                            )[0]
                            svr_superuser = winreg.QueryValueEx(
                                inst_key, 'Database Superuser'
                            )[0]
                            svr_port = winreg.QueryValueEx(inst_key, 'Port')[0]
                            svr_discovery_id = inst_id
                            svr_comment = gettext(
                                "Auto-detected %s installation with the data "
                                "directory at %s" % (
                                    winreg.QueryValueEx(
                                        inst_key, 'Display Name'
                                    )[0],
                                    winreg.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 Exception as e:
                        pass
        else:
            # We use the postgres-winreg.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
                    description = registry.get(section, 'Description')
                    data_directory = registry.get(section, 'DataDirectory')
                    if hasattr(str, 'decode'):
                        description = description.decode('utf-8')
                        data_directory = data_directory.decode('utf-8')
                    svr_comment = gettext(u"Auto-detected %s installation "
                                          u"with the data directory at %s" % (
                                              description,
                                              data_directory
                                          )
                                          )
                    add_server(user_id, servergroup_id, svr_name,
                               svr_superuser, svr_port, svr_discovery_id,
                               svr_comment)

        except Exception as e:
            pass

    @user_logged_in.connect_via(app)
    @user_logged_out.connect_via(app)
    def force_session_write(app, user):
        session.force_write = True

    ##########################################################################
    # 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"""

        # Check the auth key is valid, if it's set, and we're not in server
        # mode, and it's not a help file request.
        if not config.SERVER_MODE and app.PGADMIN_KEY != '':
            if (
                ('key' not in request.args or
                 request.args['key'] != app.PGADMIN_KEY) and
                request.cookies.get('PGADMIN_KEY') != app.PGADMIN_KEY and
                request.endpoint != 'help.static'
            ):
                abort(401)

        if not config.SERVER_MODE and not current_user.is_authenticated:
            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)

    @app.after_request
    def after_request(response):
        if 'key' in request.args:
            domain = dict()
            if config.COOKIE_DEFAULT_DOMAIN and \
                    config.COOKIE_DEFAULT_DOMAIN != 'localhost':
                domain['domain'] = config.COOKIE_DEFAULT_DOMAIN
            response.set_cookie('PGADMIN_KEY', value=request.args['key'],
                                path=config.COOKIE_DEFAULT_PATH,
                                **domain)

        return response

    ##########################################################################
    # Minify output
    ##########################################################################
    # HTMLMIN doesn't work with Python 2.6.
    if not config.DEBUG and sys.version_info >= (2, 7):
        from flask_htmlmin import HTMLMIN
        HTMLMIN(app)

    @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!
    ##########################################################################

    return app
Beispiel #45
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore
from malprogramm.forms import ExtendedLoginForm, ExtendedRegisterForm

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

db = SQLAlchemy(app)

from malprogramm import models

user_datastore = SQLAlchemyUserDatastore(db, models.User, models.Role)
security = Security(app,
                    user_datastore,
                    login_form=ExtendedLoginForm,
                    register_form=ExtendedRegisterForm)

from malprogramm import views
Beispiel #46
0
def create_app():
    app = Flask(__name__, static_url_path='/_static')
    app.config.from_object('config')

    jsglue.init_app(app)
    db.init_app(app)

    from models import User, Role

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

    # Create a user to test with
    @app.before_first_request
    def create_user():
        user_datastore.create_user(email='*****@*****.**',
                                   password='******')

    @app.route('/')
    def index():
        return redirect(url_for('portal.index'))

    # Views
    # @app.route('/')
    # @login_required
    # def home():
    #     return render_template('index.html')

    # @app.route('/')
    # @login_required
    # def hello_world():
    #     return redirect(url_for('project.documents'))

    from project import bpproject
    from annotation import bpannotator
    from resources import bpresources
    from typesystem import bptypesystem
    from portal import bpportal

    # from login import bpapp as bplogin

    class RegexConverter(BaseConverter):
        def __init__(self, url_map, *items):
            super(RegexConverter, self).__init__(url_map)
            self.regex = items[0]

    class MongoObjRegexConverter(BaseConverter):
        def __init__(self, url_map):
            super(MongoObjRegexConverter, self).__init__(url_map)
            self.regex = "[a-z0-9]{24}"

    gen_timestamp = time.time()

    @app.template_filter('autoversion')
    def autoversion_filter(filename):
        # determining fullpath might be project specific
        # fullpath = os.path.join('some_app/', filename[1:])
        # try:
        #     timestamp = str(os.path.getmtime(fullpath))
        # except OSError:
        #     return filename
        newfilename = "{0}?v={1}".format(filename, gen_timestamp)
        return newfilename

    # Use the RegexConverter function as a converter
    # method for mapped urls
    app.url_map.converters['regex'] = RegexConverter
    app.url_map.converters['mbj'] = MongoObjRegexConverter

    app.register_blueprint(bpportal, url_prefix='/portal')
    app.register_blueprint(bpproject, url_prefix='/p')
    app.register_blueprint(bptypesystem, url_prefix='/p/typesystem')
    app.register_blueprint(bpresources, url_prefix='/resources')
    app.register_blueprint(bpannotator, url_prefix='/p/a')

    return app
Beispiel #47
0
 def create():
     app.security = Security(app, datastore=sqlalchemy_session_datastore)
     return app
Beispiel #48
0
    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))
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime())
    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
security.SECURITY_PASSWORD_HASH = None
# Create a user to test with
@app.before_first_request
def create_user():
    db.create_all()
    user_datastore.create_user(email='hatlab', password='******')
    db.session.commit()


@app.route('/')
def retourner_accueil():
    contenu =[]
    jour = str(date.today())
    for line in open (sortie):
        if jour in line:
Beispiel #49
0
                        primary_key=True,
                        nullable=False)
    content_id = db.Column(db.Integer,
                           db.ForeignKey('volunteer.id'),
                           primary_key=True,
                           nullable=False)


admin.add_view(ModelView(User, db.session))
admin.add_view(ModelView(Role, db.session))
admin.add_view(ModelView(User_category, db.session))
admin.add_view(ModelView(Volunteer, db.session))
admin.add_view(ModelView(Like, db.session))

user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)  # Security 기능 확장 위함

univer = ""
major = ""


#@app.before_first_request # 초기화할때
def create_user():
    db.create_all()
    user_datastore.create_user(email='*****@*****.**', password='******')
    db.session.commit()


def classification(categories):
    category_num = 22
    receiver_cate_num = 11
Beispiel #50
0
 def __init__(self, app=None):
     """Extension initialization."""
     self.security = Security()
     self.datastore = None
     if app:
         self.init_app(app)
Beispiel #51
0
class InvenioAccounts(object):
    """Invenio-Accounts extension."""

    def __init__(self, app=None, sessionstore=None):
        """Extension initialization.

        :param app: The Flask application.
        :param sessionstore: store for sessions. Passed to
            ``flask-kvsession``. Defaults to redis.
        """
        self.security = Security()
        self.datastore = None
        if app:
            self.init_app(app, sessionstore=sessionstore)

    @staticmethod
    def monkey_patch_flask_security():
        """Monkey-patch Flask-Security."""
        if utils.get_hmac != get_hmac:
            utils.get_hmac = get_hmac
        if utils.encrypt_password != encrypt_password:
            utils.encrypt_password = encrypt_password
            changeable.encrypt_password = encrypt_password
            recoverable.encrypt_password = encrypt_password
            registerable.encrypt_password = encrypt_password

    def init_app(self, app, sessionstore=None, register_blueprint=True):
        """Flask application initialization.

        The following actions are executed:

        #. Initialize the configuration.

        #. Monkey-patch Flask-Security.

        #. Create the user datastore.

        #. Create the sessionstore.

        #. Initialize the extension, the forms to register users and
            confirms their emails, the CLI and, if ``ACCOUNTS_USE_CELERY`` is
            ``True``, register a celery task to send emails.

        :param app: The Flask application.
        :param sessionstore: store for sessions. Passed to
            ``flask-kvsession``. If ``None`` then Redis is configured.
            (Default: ``None``)
        :param register_blueprint: If ``True``, the application registers the
            blueprints. (Default: ``True``)
        """
        self.init_config(app)

        # Monkey-patch Flask-Security
        InvenioAccounts.monkey_patch_flask_security()

        # Create user datastore
        if not self.datastore:
            self.datastore = SessionAwareSQLAlchemyUserDatastore(
                db, User, Role)

        # Create sessionstore
        if sessionstore is None:
            if app.testing and \
                    os.environ.get('CI', 'false') == 'false':
                from simplekv.memory import DictStore

                sessionstore = DictStore()
            else:
                import redis
                from simplekv.memory.redisstore import RedisStore

                sessionstore = RedisStore(redis.StrictRedis.from_url(
                    app.config['ACCOUNTS_SESSION_REDIS_URL']))

        user_logged_in.connect(login_listener, app)

        # Initialize extension.
        _register_blueprint = app.config.get('ACCOUNTS_REGISTER_BLUEPRINT')
        if _register_blueprint is not None:
            register_blueprint = _register_blueprint

        state = self.security.init_app(app, datastore=self.datastore,
                                       register_blueprint=register_blueprint)
        self.kvsession_extension = KVSessionExtension(sessionstore, app)

        app.extensions['security'].register_form = register_form_factory(
            app.extensions['security'].register_form, app)

        app.extensions['security'].confirm_register_form = \
            confirm_register_form_factory(
                app.extensions['security'].confirm_register_form, app
            )

        if app.config['ACCOUNTS_USE_CELERY']:
            from invenio_accounts.tasks import send_security_email

            @state.send_mail_task
            def delay_security_email(msg):
                send_security_email.delay(msg.__dict__)

        app.extensions['invenio-accounts'] = self

    def init_config(self, app):
        """Initialize configuration.

        :param app: The Flask application.
        """
        try:
            pkg_resources.get_distribution('celery')
            app.config.setdefault(
                "ACCOUNTS_USE_CELERY", not (app.debug or app.testing))
        except pkg_resources.DistributionNotFound:  # pragma: no cover
            app.config.setdefault("ACCOUNTS_USE_CELERY", False)

        app.config.setdefault('ACCOUNTS', True)

        # Register Invenio legacy password hashing
        register_crypt_handler(InvenioAesEncryptedEmail)

        # Change Flask-Security defaults
        app.config.setdefault('SECURITY_CHANGEABLE', True)
        app.config.setdefault('SECURITY_CONFIRMABLE', True)
        app.config.setdefault('SECURITY_PASSWORD_HASH', 'pbkdf2_sha512')
        app.config.setdefault('SECURITY_PASSWORD_SCHEMES',
                              ['pbkdf2_sha512', 'invenio_aes_encrypted_email'])
        app.config.setdefault('SECURITY_DEPRECATED_PASSWORD_SCHEMES',
                              ['invenio_aes_encrypted_email'])
        app.config.setdefault('SECURITY_RECOVERABLE', True)
        app.config.setdefault('SECURITY_REGISTERABLE', True)
        app.config.setdefault('SECURITY_TRACKABLE', True)
        app.config.setdefault('SECURITY_LOGIN_WITHOUT_CONFIRMATION', True)
        app.config.setdefault('SECURITY_PASSWORD_SALT',
                              app.config['SECRET_KEY'])

        # Change default templates
        app.config.setdefault("SECURITY_FORGOT_PASSWORD_TEMPLATE",
                              "invenio_accounts/forgot_password.html")
        app.config.setdefault("SECURITY_LOGIN_USER_TEMPLATE",
                              "invenio_accounts/login_user.html")
        app.config.setdefault("SECURITY_REGISTER_USER_TEMPLATE",
                              "invenio_accounts/register_user.html")
        app.config.setdefault("SECURITY_RESET_PASSWORD_TEMPLATE",
                              "invenio_accounts/reset_password.html")
        app.config.setdefault("SECURITY_CHANGE_PASSWORD_TEMPLATE",
                              "invenio_accounts/change_password.html")
        app.config.setdefault("SECURITY_SEND_CONFIRMATION_TEMPLATE",
                              "invenio_accounts/send_confirmation.html")
        app.config.setdefault("SECURITY_SEND_LOGIN_TEMPLATE",
                              "invenio_accounts/send_login.html")
        app.config.setdefault("SECURITY_REGISTER_URL",
                              "/signup/")
        app.config.setdefault("SECURITY_RESET_URL",
                              "/lost-password/")
        app.config.setdefault("SECURITY_LOGIN_URL",
                              "/login/")
        app.config.setdefault("SECURITY_LOGOUT_URL",
                              "/logout/")
        app.config.setdefault("SECURITY_CHANGE_URL",
                              "/accounts/settings/password/")

        for k in dir(config):
            if k.startswith('ACCOUNTS_'):
                app.config.setdefault(k, getattr(config, k))