Exemple #1
0
def setup(email, username, password):
    """ Setup UserDatastore and Roles. Add -a <email> to create default admin user with email and password=password
    """

    from datetime import datetime
    from app import models, db
    from flask_security import SQLAlchemyUserDatastore

    # create roles
    with app.app_context():
        db.create_all()
        store = SQLAlchemyUserDatastore(db, models.User, models.Role)

        # Add roles
        for name, description in [
            ("Admin", "Administration"),
        ]:
            try:
                store.create_role(name=name, description=description)
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                print(e)

            # optional: add admin user
            if email or username or password:
                store.create_user(username=username,
                                  email=email,
                                  password=password,
                                  roles=["Admin"])
                models.User.get_user("admin").confirmed_at = datetime.now()
                db.session.commit()
Exemple #2
0
def _init_users():
    """Initialize Afterglow user datastore if AUTH_ENABLED = True"""
    # noinspection PyUnresolvedReferences
    from .. import oauth2  # register oauth token-related models

    # All imports put here to avoid unnecessary loading of packages on startup
    # if user auth is disabled
    from alembic import (config as alembic_config, context as alembic_context)
    from alembic.script import ScriptDirectory
    from alembic.runtime.environment import EnvironmentContext

    global user_datastore, security

    user_datastore = SQLAlchemyUserDatastore(db, DbUser, DbRole)
    security = Security(app, user_datastore, register_blueprint=False)

    # Make sure that the database directory exists
    try:
        os.makedirs(os.path.abspath(app.config['DATA_ROOT']))
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

    # Create/upgrade tables via Alembic
    cfg = alembic_config.Config()
    cfg.set_main_option(
        'script_location',
        os.path.abspath(
            os.path.join(__file__, '../..', 'db_migration', 'users')))
    script = ScriptDirectory.from_config(cfg)

    # noinspection PyProtectedMember
    with EnvironmentContext(
            cfg,
            script,
            fn=lambda rev, _: script._upgrade_revs('head', rev),
            as_sql=False,
            starting_rev=None,
            destination_rev='head',
            tag=None,
    ), db.engine.connect() as connection:
        alembic_context.configure(connection=connection)

        with alembic_context.begin_transaction():
            alembic_context.run_migrations()

    # Initialize user roles if missing
    try:
        roles_created = False
        for name, descr in [('admin', 'Afterglow Administrator'),
                            ('user', 'Afterglow User')]:
            if not user_datastore.find_role(name):
                user_datastore.create_role(name=name, description=descr)
                roles_created = True
        if roles_created:
            user_datastore.commit()
    except Exception:
        db.session.rollback()
        raise
Exemple #3
0
def add(ctx, name, description):
    """Creates a new role"""
    ds = SQLAlchemyUserDatastore(ctx.obj, User, Role)
    try:
        ds.create_role(name=name, description=description)
        ds.commit()
    except:
        log.exception("Couldn't create role")
Exemple #4
0
def load(ctx, file):
    """Dump stuff for loading later (in lieu of having proper migrations)"""
    ds = SQLAlchemyUserDatastore(ctx.obj, User, Role)
    for line in file:
        email, first, last, roles, password = line.strip().split('\t')
        u = ds.find_user(email=email)

        if not u:
            u = ds.create_user(email=email,
                               first_name=first,
                               last_name=last,
                               password=password)
            log.info('added %s', u)
            ds.commit()
        for role_name in roles.strip().split(','):
            r = ds.find_role(role_name)
            if not r:
                r = ds.create_role(name=role_name)
                ds.commit()
            if not u.has_role(r):
                ds.add_role_to_user(u, r)

    ds.commit()
Exemple #5
0
def load_all_fixtures(db, app):

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)

    # Load default fixtures
    role = user_datastore.create_role(name=app.config['VOXO_ROLE_USER'],
                                      description='User role')
    admin_role = user_datastore.create_role(name=app.config['VOXO_ROLE_ADMIN'],
                                            description='Admin role')
    server_role = user_datastore.create_role(
        name=app.config['VOXO_ROLE_SERVER'], description='Server role')

    user_vjousse = registerable.register_user(email='*****@*****.**',
                                              password='******')
    user_datastore.add_role_to_user(user_vjousse, role)

    print("{user} with token {token} created.".format(
        user=user_vjousse.email, token=user_vjousse.get_auth_token()))

    user = registerable.register_user(email='*****@*****.**',
                                      password='******')
    user_datastore.add_role_to_user(user, admin_role)
    user_datastore.add_role_to_user(user, role)

    print("{user} with token {token} created.".format(
        user=user.email, token=user.get_auth_token()))

    server = registerable.register_user(email='*****@*****.**',
                                        password='******')
    user_datastore.add_role_to_user(server, server_role)

    print("{user} with token {token} created.".format(
        user=server.email, token=server.get_auth_token()))

    asr_model_french = AsrModel(name="french.studio.fr_FR",
                                description="General purpose french model")

    asr_model_french.users.append(user_vjousse)

    db.session.add(asr_model_french)
    db.session.flush()

    asr_model_english = AsrModel(name="english.studio",
                                 description="General purpose english model")

    asr_model_english.users.append(user_vjousse)

    db.session.add(asr_model_english)
    db.session.flush()

    media_file = MediaFile(filename='fixture_file.wav',
                           status=FileStatus.Success,
                           user_id=user_vjousse.id,
                           size=2500,
                           generated_filename='fixture_file_UUID.wav',
                           duration=70)

    db.session.add(media_file)
    db.session.flush()

    process = Process(
        file_id=media_file.id,
        status=DecodeStatus.Queued,
    )

    db.session.add(process)
    db.session.flush()

    transcription = Transcription(
        auto_filename='transcription.xml',
        ref_filename='transcription.txt',
        user_id=user_vjousse.id,
    )

    db.session.add(transcription)
    db.session.flush()

    process = Process(file_id=media_file.id,
                      status=DecodeStatus.Queued,
                      type=ProcessType.TranscriptionAlignment,
                      transcription_id=transcription.id)

    db.session.add(process)
    db.session.flush()

    db.session.commit()
Exemple #6
0
from app import app,db
from app.models.Roles import Role,User
from flask_security import SQLAlchemyUserDatastore,Security

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


admin = user_datastore.create_user(username='******', password='******',active=True)
user_datastore.create_role(name='User', description='Generic user role')

admin_role = user_datastore.create_role(name='Admin', description='Admin user role')

user_datastore.add_role_to_user(admin, admin_role)
db.session.commit()
Anna = user_datastore.create_user(username="******",
                                  password="******",
                                  name="Anna",
                                  surname="Trishyna",
                                  email="*****@*****.**",
                                  birthday="17.12.1998",
                                  group="KM-63",
                                  hobby="travel",
                                  grades="C",
                                  proglanguage="Python, Javascript",
                                  specialization="113",
                                  subject="Математика")


Admin = user_datastore.create_role(name="Admin")

User = user_datastore.create_role(name="User")

Dima.roles.append(User)
Vlad.roles.append(User)
Anna.roles.append(Admin)


Oleg = user_datastore.create_user(teacher_id = '0000000300871028',
                                  teacher_username = '******',
                                  teacher_name = 'Олег',
                                  teacher_lastname = 'Чертов',
                                  teacher_birthday =  '00.00.0000',
                                  teacher_position = 'Завідувач кафедри',
                                  teacher_subject = 'Математика',
Exemple #8
0
def do_setup(app):
    """Create a new settings database from scratch"""

    if config.SERVER_MODE is False:
        print(u"NOTE: Configuring authentication for DESKTOP mode.")
        email = config.DESKTOP_USER
        p1 = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(32)
        ])

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

        if all(value in os.environ
               for value in ['PGADMIN_SETUP_EMAIL', 'PGADMIN_SETUP_PASSWORD']):
            email = ''
            p1 = ''
            if os.environ['PGADMIN_SETUP_EMAIL'] and os.environ[
                    'PGADMIN_SETUP_PASSWORD']:
                email = os.environ['PGADMIN_SETUP_EMAIL']
                p1 = os.environ['PGADMIN_SETUP_PASSWORD']
        else:
            # Prompt the user for their default username and password.
            print(
                u"Enter the email address and password to use for the initial "
                u"pgAdmin user account:\n")

            email_filter = re.compile(
                "^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9]"
                "(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9]"
                "(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")

            email = input("Email address: ")
            while email == '' or not email_filter.match(email):
                print(u'Invalid email address. Please try again.')
                email = input("Email address: ")

            def pprompt():
                return getpass.getpass(), getpass.getpass('Retype password:'******'Passwords do not match. Please try again.')
                else:
                    print(
                        u'Password must be at least 6 characters. Please try again.'
                    )
                p1, p2 = pprompt()

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

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

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

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

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

        # Create the keys
        key = Keys(name='CSRF_SESSION_KEY', value=config.CSRF_SESSION_KEY)
        db.session.merge(key)

        key = Keys(name='SECRET_KEY', value=config.SECRET_KEY)
        db.session.merge(key)

        key = Keys(name='SECURITY_PASSWORD_SALT',
                   value=config.SECURITY_PASSWORD_SALT)
        db.session.merge(key)

        db.session.commit()

    # Done!
    print(u"")
    print(u"The configuration database has been created at {0}".format(
        config.SQLITE_PATH))
    createDate      = db.Column(db.DateTime)
    seasonId        = db.Column(db.Integer, db.ForeignKey('season.id'))
    season          = db.relationship('Season', backref=db.backref('user_payment_season', order_by=id))
    userId          = db.Column(db.Integer, db.ForeignKey('user.id'))
    User            = db.relationship('User', backref=db.backref('user_payment_user', order_by=id))
    
# Setup Flask-Security
userDatastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, userDatastore)
login_manager = LoginManager()
login_manager.setup_app(app)
login_manager.login_view = "login.html"

# Set up the DB
db.create_all()
teamMemberRole  = userDatastore.create_role()
adminRole       = userDatastore.create_role()
teamManagerRole = userDatastore.create_role()

@login_manager.user_loader
def load_user(userid):
    return User.query.filter_by(id=userid).first()

#Routes
    
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        email = method.form['email']
        password = method.form['password']
        
Exemple #10
0

app = create_app()
app.app_context().push()

db.create_all()

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

# admin user
user_datastore.create_user(email='*****@*****.**', password='******')
user = User.query.first()

user_datastore.create_role(name='admin', description='administrator')

role = Role.query.first()
user_datastore.add_role_to_user(user, role)

# ADMIN


class AdminView(ModelView):
    def is_accessible(self):
        return current_user.has_role('admin')

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for('security.login', next=request.url))

Exemple #11
0
def create_app(config_name):
    """An application factory, as explained here:
        http://flask.pocoo.org/docs/patterns/appfactories/

    @param config_name:    The configuration object to use.
    """
    app = Flask(__name__)

    app.config.from_object(config[config_name]
                           or config[os.getenv('BG_CONFIG')])
    app.config.from_envvar('BG_SETTINGS', silent=True)
    config[config_name].init_app(app)

    db.init_app(app)

    # Setup Flask-Security
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    from app.users.forms import ExtendedRegisterForm
    security.init_app(app, user_datastore, register_form=ExtendedRegisterForm)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    migrate.init_app(app, db)

    md = Markdown(app,
                  output_format='html5',
                  extensions=['fenced_code', 'tables', 'abbr', 'footnotes'])

    pages.init_app(app)
    csrf.init_app(app)

    register_adminviews(app)

    app.jinja_env.filters['alert_class'] = alert_class_filter

    # WTForms helpers
    from .utils import add_helpers
    add_helpers(app)

    if not app.debug:
        import logging
        from logging.handlers import SMTPHandler
        mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'],
                                   fromaddr=app.config['ADMINS_FROM_EMAIL'],
                                   toaddrs=app.config['ADMINS_EMAIL'],
                                   subject='Application Error Occurred')
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)

    register_blueprints(app)
    register_commands(app)

    # Create the bg_interface directory if it does not exist
    directory = os.path.join(os.path.dirname(BASE_DIR), 'bg_interface')

    if not os.path.exists(directory):
        os.makedirs(directory)

    with app.app_context():
        db.create_all()
        if not User.query.first():
            # Create a default admin user if there is no user in the database
            user_datastore.create_role(name='admin')
            user_datastore.create_user(name='Administration Account',
                                       email='*****@*****.**',
                                       password=encrypt_password('password'),
                                       roles=['admin'])
            db.session.commit()
            app.logger.info('Created admin user [email protected]')

    return app