Esempio n. 1
0
user_committee = db.Table(
    'user_committee',
    db.Column('user_id', db.Integer(),
              db.ForeignKey('user.id', ondelete="CASCADE")),
    db.Column('committee_id', db.Integer(),
              db.ForeignKey('committee.id', ondelete="CASCADE")))

user_following = db.Table(
    'user_following',
    db.Column('user_id', 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, register_form=forms.RegisterForm)
Esempio n. 2
0
def create_app(config=None):
    if config is None:
        config = {}

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

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

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

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

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

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

    app.config.update(config)

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

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

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

    app.logger.info("Started")

    Mail(app)

    from . import models

    models.db.init_app(app)

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

    return app
Esempio n. 3
0
from flask_admin.base import MenuLink
from flask.ext.security import Security, SQLAlchemyUserDatastore
from flask_wtf.csrf import CsrfProtect
from config import FIRST_USER_PASS, FIRST_USER_NAME

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

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

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

#admin setup
_admin = Admin(app, 'NYX Admin', template_mode='bootstrap3',
              index_view=admin.ProtectedIndexView())
_admin.add_link(MenuLink(name='Back to Site', url='/'))
_admin.add_view(admin.UserModelView(models.User, db.session))
_admin.add_view(admin.BotModelView(models.Bot, db.session))
Esempio n. 4
0
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

    def __unicode__(self):
        return self.name

    def __name__(self):
        return u'角色管理'

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'))
    # Required for administrative interface. For python 3 please use __str__ instead.
    def __unicode__(self):
        return self.email

    def __name__(self):
        return u'用户管理'
   
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security()


# Create admin
admin = admin.Admin(name=u'权限管理', template_mode='bootstrap3')
Esempio n. 5
0
def create_app(app=None, config_file=None):
    """
    factory that instantiates the app
    """

    if not app:
        app = Flask(__name__)

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

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

    

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

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

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

            

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

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

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



    



    return app
Esempio n. 6
0
def configure(app, db):
    from quokka.modules.accounts.models import User, Role
    app.security = Security(
        app=app,
        datastore=MongoEngineUserDatastore(db, User, Role),
    )
Esempio n. 7
0
def create_app(testing=False, live=False):
    from bhs_api.models import User, Role
    from bhs_api.forms import LoginForm

    app = Flask(__name__)
    app.testing = testing

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

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

    # DB Config
    app.config['MONGODB_DB'] = conf.user_db_name
    app.config['MONGODB_HOST'] = conf.user_db_host
    app.config['MONGODB_PORT'] = conf.user_db_port
    # Redis
    app.config['REDIS_HOST'] = conf.redis_host
    app.config['REDIS_PORT'] = conf.redis_port
    app.config['REDIS_PASSWORD'] = getattr(conf, 'redis_password', None)

    # CACHING
    app.config['CACHING_TTL'] = conf.caching_ttl

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

    # Create the elasticsearch connection
    app.es = elasticsearch.Elasticsearch(conf.elasticsearch_host)
    app.es_data_db_index_name = getattr(conf, "elasticsearch_data_index", app.data_db.name)

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

    # redis
    try:
        app.redis = redis.StrictRedis(host=conf.redis_host,
                                      port=conf.redis_port,
                                      password = app.config['REDIS_PASSWORD'],
                                      db=0)
    except AttributeError:
        app.redis = None

    return app, conf
Esempio n. 8
0
from os import path

from flask import Flask
from flask.ext.security import SQLAlchemyUserDatastore, Security

from sample_app.database import db
from sample_app.extensions import admin, config, cors, debug_toolbar, mail, oauth

__version__ = '0.1'

# Setup Flask-Security
from sample_app.core.models import Role, User  # NOQA
from sample_app.database import db  # NOQA

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

_current_dir = path.dirname(path.abspath(__file__))


def create_app(config_name='default'):
    """
    :param config_name: developtment, production or testing
    :return: flask application

    flask application generator
    """
    app = create_app_min(config_name)

    cors.init_app(app, resources={r"/v1/*": {"origins": "*"}})
    oauth.init_app(app)
class CheckError(ValueError):
    pass


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


from flask.ext.cors import CORS
cors = CORS()


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


from flask_jwt import JWT
from flask import abort, jsonify, current_app
from datetime import datetime
jwt = JWT()


@jwt.authentication_handler
def custom_authentication_handler(username, password):
    user = datastore.find_user(email=username)
    if user is not None:
        if not user.is_active():
            abort(401)
        if username == user.email and user.check_password(password):
Esempio n. 10
0
# -*- coding: utf-8 -*-
from flask.ext.security import Security, SQLAlchemyUserDatastore
from coin import coin
from coin.models import db
from coin.models.role import Role
from coin.models.user import User

user_datastore = SQLAlchemyUserDatastore(db, User, Role)

security = Security(coin, user_datastore)


@security.context_processor
def security_context_processor():

    return dict()


@security.mail_context_processor
def security_mail_processor():

    return dict()


# [Emails with Celery](https://pythonhosted.org/Flask-Security/customizing.html#emails-with-celery)
Esempio n. 11
0
def create_app():
    # Create app
    app = Flask(__name__)
    mail = Mail(app)
    app.config.from_object('config')

    mail = Mail(app)
    mail.init_app(app)

    # db instance is created in models.py (for factory pattern)
    from models import db
    db.init_app(app)

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

    # importmore Moules here
    from models import InvoiceDocument

    # Import modules here
    from app.mod_api.api import api_mod as api_module
    from app.mod_crew.controllers import crew_mod as crew_module
    app.register_blueprint(api_module)
    app.register_blueprint(crew_module)

    # Views

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

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

    @app.route('/hourly_rate', methods=['GET', 'POST'])
    @login_required
    def hourly_rate():
        form = HourlyRateForm(request.form)
        entry = None
        if request.method == 'POST':

            if form.validate_on_submit():
                entry = FreelanceEntry(
                    hourly_rate=form.hours_worked.data,
                    hours=form.hours_worked.data,
                )
                if "submit" in request.form:
                    flash("button 1 was pressed")
                    return render_template('hourly_rate.html',
                                           form=form,
                                           entry=entry)

                if "save_invoice" in request.form:
                    flash("Data Saved ")
                    invoice_saved = InvoiceDocument(
                        option_selected="hourly_rate",
                        hours=form.hours_worked.data,
                        hourly_rate=form.hourly_rate.data,
                        creation_date=timenow)
                    db.session.add(invoice_saved)
                    db.session.commit()
                    return render_template('hourly_rate.html',
                                           form=form,
                                           entry=entry)

            else:
                flash("Fill Out both fields")
                return render_template('hourly_rate.html',
                                       form=form,
                                       entry=entry)

        elif request.method == 'GET':
            return render_template('hourly_rate.html', form=form, entry=entry)

    @app.route('/guaranteedhours', methods=['GET', 'POST'])
    @login_required
    def guaranteed_hours():
        form = GuaranteedHoursForm(request.form)
        entry = None
        if form.validate_on_submit():
            entry = FreelanceEntry(
                guaranteed_rate=form.guaranteed_rate.data,
                guaranteed_hours=form.guaranteed_hours.data,
                hours_worked=form.actual_hours_worked.data,
            )
        return render_template('guaranteedhours.html', form=form, entry=entry)

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

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

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

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

    return app
Esempio n. 12
0
def configure_security(app):
    """
    ABOUT
        Configures Flask-Security with our app
    """
    from .user.models import Role, User

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

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        # Set the default state
        g.user = None

        if identity.name is None:
            return

        # Ok we're ok to proceed now ...
        if isinstance(identity.name, (bson.ObjectId)):
            user = User.objects(id=identity.name)
        elif isinstance(identity.name, (str, unicode)):
            user = User.objects(email=identity.name)

        if user.count() > 1:
            app.logger.error("Got more than one match for user login %s" %
                             identity.name)
            raise Exception(
                "[on_identity_loaded] Error getting login information. Please contact an administrator"
            )
            g.user = None
        elif user.count() == 0:
            g.user = None
        else:
            user = user.first()

            if hasattr(user, 'id'):
                identity.provides.add(UserNeed(user.id))

            # Assuming the User model has a list of roles, update the
            # identity with the roles that the user provides
            if hasattr(user, 'roles'):
                for role in user.roles:
                    identity.provides.add(RoleNeed(role.name))

            # Assuming the User model has a list of posts the user
            # has authored, add the needs to the identity
            if hasattr(user, 'posts'):
                for post in user.posts:
                    identity.provides.add(EditBlogPostNeed(unicode(post.id)))

            identity.user = user
            g.user = user

    # set the user load clalback
    @login_manager.user_loader
    def load_user(userid):
        return User.objects.with_id(userid)

    @app.before_request
    def before_request():
        """
        ABOUT
            This was inserted when we started to see errors from
            g.user.is_anonymous() for non-registered users, this seemed
            to fix that
        """
        g.user = current_user
Esempio n. 13
0
def init_flask_security(app):
    user_datastore = MongoEngineUserDatastore(db, User, Role)
    security = Security(app, user_datastore)
    # This step may not be necessary
    app.security = security
Esempio n. 14
0
from argos.web.app import app
from argos.datastore import init_db, init_model

from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import SQLAlchemyUserDatastore, Security
from flask_oauthlib.provider import OAuth2Provider

# Initialize the database and declarative Base class
db = SQLAlchemy(app)

init_db(db)

init_model(db.Model)

# Setup security
import argos.web.models

user_db = SQLAlchemyUserDatastore(db, web.models.User, web.models.Role)
Security(app, user_db)

db.create_all()

# Import routes (which depend on database)
from argos.web import routes
Esempio n. 15
0
# Memcache
from flask.ext.cache import Cache
app.cache = Cache(app)

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

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

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

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

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

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


def scan_and_import(name):
Esempio n. 16
0
app = Flask(__name__)
app.config.from_yaml(app.root_path)
#app.config.from_heroku()
app.wsgi_app = MethodRewriteMiddleware(app.wsgi_app)

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

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

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

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


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


@app.before_first_request
def before_first_request():
    try:
        models.db.create_all()
    except Exception, e:
        app.logger.error(str(e))
Esempio n. 17
0
def create_app(app_name=config.APP_NAME):
    """Create the Flask application, startup logging and dynamically load
    additional modules (blueprints) that are found in this directory."""
    app = PgAdmin(__name__, static_url_path='/static')
    # Removes unwanted whitespace from render_template function
    app.jinja_env.trim_blocks = True
    app.config.from_object(config)

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

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

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

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

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

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

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

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

    # Initialise i18n
    babel = Babel(app)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            if servers.count() > 0:
                return

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

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

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

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

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

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

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

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

            registry = ConfigParser()

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

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

        except:
            pass

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

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

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

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

            login_user(user)

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

        return response

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

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

    return app
Esempio n. 18
0
def init(app):
    # --> Jinja2 Env Update
    app.jinja_env.globals.update(__builtins__=__builtins__)

    # --> URI setup
    app.config["SQLALCHEMY_DATABASE_URI"] = \
        "postgresql://{}:{}@{}:{}/{}".format(app.config["DB_USERNAME"], app.config["DB_PASSWORD"],
                                             app.config["DB_HOSTNAME"], app.config["DB_PORT"],
                                             app.config["DB_DATABASE"])

    # --> Extension setup
    db.init_app(app)
    admin.init_app(app)
    mail = Mail()
    mail.init_app(app)

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

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

    # --> Admiral load on each request
    def admiral_load():
        api_token = request.values.get('api_token', None)
        if api_token is None:
            logger.warning("No API Key -> Skipping request")
            abort(403)
        user = db.session.query(User).filter(
            User.api_token == api_token).first()
        if user is None:
            logger.warning("Unknown API Key -> {}".format(api_token))
            abort(404)
        g.admiral = user.admiral if user.admiral else Admiral().create(user)
        # Update resources.
        curr_t = datetime.datetime.utcnow()
        lastaction = g.admiral.last_action
        if not lastaction:
            lastaction = curr_t
        delta = (curr_t - lastaction).total_seconds() / 60
        if delta < 0:
            # wat
            logger.warn("Now - lastaction for admiral {} negative?".format(
                user.nickname))
            return
        delta = int(delta)
        g.admiral.resources.add(*((delta * 3) for _ in range(3)),
                                baux=delta * 2)
        # Update action time
        g.admiral.last_action = curr_t
        db.session.add(g.admiral)
        db.session.commit()

    # --> Set up blueprints
    from kancolle.api import api_actions

    api_actions.before_request(admiral_load)

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

    from kancolle.api import api_member

    api_member.before_request(admiral_load)

    app.register_blueprint(api_member, url_prefix='/kcsapi/api_get_member')

    from kancolle.api import api_init

    api_init.before_request(admiral_load)

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

    from kancolle.api import api_user

    api_user.before_request(admiral_load)

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

    from kancolle.api import api_mission

    api_mission.before_request(admiral_load)

    app.register_blueprint(api_mission, url_prefix='/kcsapi/api_req_mission')

    @app.route('/play')
    def p_index():
        if hasattr(current_user, 'api_token'):
            api_token = current_user.api_token
            return render_template('play/index.html', api_token=api_token)
        else:
            return redirect('/account/login')

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

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

    # --> Signals
    @user_logged_in.connect_via(app)
    def u_logged_in(sender, user):
        """
        Regenerate the API token every login.
        """
        user.api_token = generate_api_token()
Esempio n. 19
0
from city_lang.core.datastore import MongoSetUserDatastore
from flask import Blueprint, current_app
from flask.ext.security import Security

from werkzeug.local import LocalProxy

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

import views
import models

user_datastore = MongoSetUserDatastore(mongo, models.User, models.Role)
Security(current_app, user_datastore)
Esempio n. 20
0
                                           GET_MANY=[auth_func]))

# Create API endpoints, which will be available at /api/<tablename> by
# default. Allowed HTTP methods can be specified as well.
apimanager.create_api(models.User,
                      methods=['GET', 'POST', 'DELETE'],
                      exclude_columns=['password'])
apimanager.create_api(models.Processed,
                      methods=['GET', 'DELETE'],
                      collection_name='history')
apimanager.create_api(models.RecentlyAdded,
                      methods=['GET', 'DELETE'],
                      collection_name='recently-added')

security = Security(app,
                    views.user_datastore,
                    register_form=forms.ExtendedRegisterForm2,
                    login_form=forms.Login)

#fix lazy_gettext json encoding ...
from flask.json import JSONEncoder as BaseEncoder
from speaklater import _LazyString


class JSONEncoder(BaseEncoder):
    def default(self, o):
        if isinstance(o, _LazyString):
            return str(o)

        return BaseEncoder.default(self, o)

Esempio n. 21
0
def register_extensions(app):
    oauth.init_app(app)
    babel.init_app(app)
    security = Security(app, user_datastore)
Esempio n. 22
0
    def remove_from_van(self, user):
        self.van_teams.remove(user)
        return self


class Emergency(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    msg = db.Column(db.String(1000))
    time = db.Column(db.DateTime())
    phone_number = db.Column(db.String(15))


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

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


#methods
def id_generator(size=10, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.SystemRandom().choice(chars) for _ in range(size))

Esempio n. 23
0
user_datastore = SQLAlchemyUserDatastore(db, User, Role)


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

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

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

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

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

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

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

# Trigger templatetag register.
from mhn.common.templatetags import format_date
mhn.jinja_env.filters['fdate'] = format_date
Esempio n. 24
0
def create_app(config=None):
    if config is None:
        config = {}

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

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

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

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

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

    app.config.update(config)

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

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

    app.logger.info("Started")

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

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

    from . import models

    models.db.init_app(app)

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

    Security(app, user_datastore, register_blueprint=False)

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

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

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

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

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

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

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

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

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

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

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

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

    # Initialise i18n
    babel = Babel(app)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            login_user(user)

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

        return response

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

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

    return app
Esempio n. 26
0
    def validate(self):
        if not super(LoginForm, self).validate():
            return False
        if self.username.data.strip() == '':
            return False
        self.user = db_session.query(User).filter(
            User.username == self.username.data).first()
        if self.user is None:
            return False
        if self.password.data == self.user.password:
            return True
        return False


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


@login_required
@roles_required('privileged_user')
@app.route('/testroles')
def TestLogin():
    if current_user.is_authenticated:
        if current_user.has_role('privileged_user'):
            context = {'user_name': get_current_user_first_name()}
            return render_template('testroles.html', **context)
        else:
            return make_response("Unauthorized User")
    else:
        return redirect('/login')
Esempio n. 27
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.mail import Mail
from flask.ext.security import Security, SQLAlchemyUserDatastore
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.pagedown import PageDown

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

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

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

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

from .admin import admin as admin_blueprint
app.register_blueprint(admin_blueprint, url_prefix='/admin')
Esempio n. 28
0
from flask.ext.security import Security, SQLAlchemyUserDatastore
from .. import app
from ..models.roles import db, Role
from ..models.users import User
from .register import ExtendedConfirmRegisterForm

user_datastore = SQLAlchemyUserDatastore(db, User, Role)

security = Security(app,
                    user_datastore,
                    confirm_register_form=ExtendedConfirmRegisterForm)
Esempio n. 29
0
db = SQLAlchemy(app)


# Custom login.
@app.route('/login', methods=['GET', 'POST'])
def login():
    """Must be defined upper setup flask-security."""
    from budgetfamily.auth.views import flask_login
    return flask_login()


# Setup flask-security.
from budgetfamily.auth.models import User, Role
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)

from budgetfamily.core import views as core_views

# control Index page
control = admin.Admin(app,
                      url='/admin',
                      index_view=core_views.ControlIndexView(url='/admin',
                                                             name=u'Бюджет'),
                      name=u'admin',
                      base_template='layout.html',
                      template_mode='bootstrap3')

# Payment app
from budgetfamily.payment import views as payment_views
Esempio n. 30
0
from flask import Flask
from flask.ext.login import LoginManager
from flask.ext.security import AnonymousUser, Security, SQLAlchemyUserDatastore
from flask.ext.sqlalchemy import SQLAlchemy
from flask_mail import Mail

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

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

from .security.forms import RegisterForm
security = Security(app, user_datastore, confirm_register_form=RegisterForm)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.anonymous_user = AnonymousUser


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


mail = Mail(app)

from app.views import bp_container
app.register_blueprint(bp_container)