Beispiel #1
4
    def create_test_user(self, email, password):
        user_datastore = SQLAlchemyUserDatastore(db, User, Role)
        user = user_datastore.create_user(email=email, password=encrypt_password(password), confirmed_at=datetime.now())
        user.role = 'Admin'
        user.active = True

        db.session.add(user)
        db.session.commit()
        db.session.refresh(user)
Beispiel #2
0
def create_init_user(user_datastore: SQLAlchemyUserDatastore) -> None:
    """
    TODO in doc:
    在这里创建初始的角色和管理用户。
    """
    user_datastore.find_or_create_role(name='root', description='系统管理员')
    user_datastore.find_or_create_role(name='admin', description='管理员')
    user_datastore.find_or_create_role(name='user', description='用户')

    if not user_datastore.get_user('*****@*****.**'):
        user_datastore.create_user(
            email='*****@*****.**',
            password=security_utils.encrypt_password('default_password'))

    # TODO in doc:
    # 如果还需要更多的初始用户,在这里创建

    db.session.commit()  # 在给用户分配角色前,必须commit这个User对象

    user_datastore.add_role_to_user('*****@*****.**', 'root')

    # TODO in doc:
    # 在这里分配其他角色给初始用户

    db.session.commit()
Beispiel #3
0
def api_server(custom_settings=None):

    # init server
    server = Flask(__name__)
    # init settings
    server.config.from_object("settings.default")
    server.config.from_envvar("SETTINGS", silent=True)
    server.config.from_object(custom_settings)

    # init db
    db.init_app(server)
    # init user
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(server, user_datastore)

    # import features
    server.register_blueprint(index)
    server.register_blueprint(dreams)

    # render context
    with server.app_context():
        db.create_all()
        if not User.query.first():
            user_datastore.create_user(email="*****@*****.**", password=encrypt_password("user"))
            db.session.commit()

    return server
Beispiel #4
0
def add_users(app, db, session):
    """ Adds a test user to db """
    from flask_security import SQLAlchemyUserDatastore

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)

    user1 = '*****@*****.**'
    pass1 = 'test1'

    user2 = '*****@*****.**'
    pass2 = 'test2'

    user_datastore.create_user(email=user1,
                               password=encrypt_password(pass1),
                               confirmed_at=datetime.datetime.now())
    session.commit()
    id_1 = user_datastore.find_user(email=user1).id

    user_datastore.create_user(email=user2,
                               password=encrypt_password(pass2),
                               confirmed_at=datetime.datetime.now())
    session.commit()
    id_2 = user_datastore.find_user(email=user2).id

    yield (id_1, id_2), ((user1, pass1), (user2, pass2))
Beispiel #5
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()
Beispiel #6
0
def create_fs_admin(name='admin'):
    """ create initial flask security admin """

    # find role admin
    r = models.Role.query.filter_by(name='admin').first()
    if not r:
        r = models.Role(name='admin', description='admin role')
        try:
            db.session.add(r)
            db.session.commit()
        except:
            print("cannot create role")

    u = models.User.query.filter_by(name=name).first()
    if not u:
        user_datastore = SQLAlchemyUserDatastore(db, models.User, models.Role)
        email = "*****@*****.**" % name
        user_datastore.create_user(email=email, 
                name='admin',
                is_admin=True,
                password='******',
                roles=['admin'])
        try:
            db.session.commit()
            print("admin name: %s was created!" % name)
        except Exception as e:
            print(e.message)
    else:
        print("admin name: %s already existed" % name)
Beispiel #7
0
def create_app(config=Config):
    app = Flask(__name__,
                template_folder='../templates',
                static_folder='../static')
    app.config.from_object(config)
    config.init_app(app)
    mail.init_app(app)
    db.init_app(app)
    admin.init_app(app)
    pagedown.init_app(app)
    migrate.init_app(app, db)
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    Security(app, datastore=user_datastore, login_form=ExtendedLoginForm)

    with app.test_request_context():
        db.create_all()
        user_datastore.find_or_create_role(name='admin',
                                           description='Administrator')
        if not user_datastore.get_user(app.config['ADMIN_EMAIL']):
            user_datastore.create_user(email=app.config['ADMIN_EMAIL'],
                                       password=app.config['ADMIN_PASSWORD'])
        db.session.commit()
        user_datastore.add_role_to_user(app.config['ADMIN_EMAIL'], 'admin')
        db.session.commit()

    return app
Beispiel #8
0
def seed_user(email, role, dept, password):
    '''
    Creates a new user in the database.
    '''
    from purchasing.users.models import User, Department, Role
    from flask_security import SQLAlchemyUserDatastore
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    seed_email = email if email else app.config.get('SEED_EMAIL')
    user_exists = User.query.filter(User.email == seed_email).first()
    department = Department.query.filter(
        Department.name == db.func.lower(dept)).first()
    if user_exists:
        print 'User {email} already exists'.format(email=seed_email)
    else:
        try:
            user_datastore.create_user(
                email=seed_email,
                created_at=datetime.datetime.utcnow(),
                department=department if department else None,
                password=password,
                roles=[Role.query.get(int(role))],
                confirmed_at=datetime.datetime.now())
            db.session.commit()
            print 'User {email} successfully created!'.format(email=seed_email)
        except Exception, e:
            print 'Something went wrong: {exception}'.format(
                exception=e.message)
Beispiel #9
0
def seed_user(email, role, dept, password):
    """
    Creates a new user in the database.
    """
    from beacon.models.users import User, Role, Department
    from flask_security import SQLAlchemyUserDatastore

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    seed_email = email if email else app.config.get("SEED_EMAIL")
    user_exists = User.query.filter(User.email == seed_email).first()
    department = Department.query.filter(Department.name == db.func.lower(dept)).first()
    if user_exists:
        print "User {email} already exists".format(email=seed_email)
    else:
        try:
            user_datastore.create_user(
                email=seed_email,
                created_at=datetime.datetime.utcnow(),
                department=department if department else None,
                password=password,
                roles=[Role.query.get(int(role))],
                confirmed_at=datetime.datetime.now(),
            )
            db.session.commit()
            print "User {email} successfully created!".format(email=seed_email)
        except Exception, e:
            print "Something went wrong: {exception}".format(exception=e.message)
Beispiel #10
0
def api_server(custom_settings=None):

    # init server
    server = Flask(__name__)
    # init settings
    server.config.from_object('settings.default')
    server.config.from_envvar('SETTINGS', silent=True)
    server.config.from_object(custom_settings)

    # init db
    db.init_app(server)
    # init user
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(server, user_datastore)

    # import features
    server.register_blueprint(index)
    server.register_blueprint(dreams)

    # render context
    with server.app_context():
        db.create_all()
        if not User.query.first():
            user_datastore.create_user(email='*****@*****.**',
                                       password=encrypt_password('user'))
            db.session.commit()

    return server
Beispiel #11
0
def add(ctx, email, password):
    """Creates a new user"""
    ds = SQLAlchemyUserDatastore(ctx.obj, User, Role)
    try:
        ds.create_user(email=email, password=password)
        ds.commit()
    except:
        log.exception("Couldn't create user")
Beispiel #12
0
def test_auth_uniquifier(app):
    # If add fs_token_uniquifier to user model - change password shouldn't invalidate
    # auth tokens.
    from sqlalchemy import Column, String
    from flask_sqlalchemy import SQLAlchemy
    from flask_security.models import fsqla_v2 as fsqla
    from flask_security import Security, SQLAlchemyUserDatastore

    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
    db = SQLAlchemy(app)

    fsqla.FsModels.set_db_info(db)

    class Role(db.Model, fsqla.FsRoleMixin):
        pass

    class User(db.Model, fsqla.FsUserMixin):
        fs_token_uniquifier = Column(String(64), unique=True, nullable=False)

    with app.app_context():
        db.create_all()

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

    with app.app_context():
        ds.create_user(
            email="*****@*****.**",
            password=hash_password("password"),
        )
        ds.commit()

        client = app.test_client()

        # standard login with auth token
        response = json_authenticate(client)
        token = response.json["response"]["user"]["authentication_token"]
        headers = {"Authentication-Token": token}
        # make sure can access restricted page
        response = client.get("/token", headers=headers)
        assert b"Token Authentication" in response.data

        # change password
        response = client.post(
            "/change",
            data={
                "password": "******",
                "new_password": "******",
                "new_password_confirm": "new strong password",
            },
            follow_redirects=True,
        )
        assert response.status_code == 200

        # authtoken should still be valid
        response = client.get("/token", headers=headers)
        assert response.status_code == 200
Beispiel #13
0
def create_user(email: str, password: str):
    datastore = SQLAlchemyUserDatastore(db, User, Role)

    if not datastore.get_user(email):
        datastore.create_user(email=email, password=hash_password(password))
        db.session.commit()

        return jsonify(
            User.query.filter(User.email == email).first().to_dict())
    return jsonify(User.query.filter(User.email == email).first().to_dict())
Beispiel #14
0
def test_replace_send_code(app, get_message):
    # replace tf_send_code - and have it return an error to check that.
    from flask_sqlalchemy import SQLAlchemy
    from flask_security.models import fsqla_v2 as fsqla
    from flask_security import Security, hash_password

    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
    db = SQLAlchemy(app)

    fsqla.FsModels.set_db_info(db)

    class Role(db.Model, fsqla.FsRoleMixin):
        pass

    class User(db.Model, fsqla.FsUserMixin):
        rv = [None, "That didnt work out as we planned", "Failed Again"]

        def tf_send_security_token(self, method, **kwargs):
            return User.rv.pop(0)

    with app.app_context():
        db.create_all()

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

    with app.app_context():
        client = app.test_client()

        ds.create_user(
            email="*****@*****.**",
            password=hash_password("password"),
            tf_primary_method="sms",
            tf_totp_secret=app.security._totp_factory.generate_totp_secret(),
        )
        ds.commit()

        data = dict(email="*****@*****.**", password="******")
        response = client.post("/login", data=data, follow_redirects=True)
        assert b"Please enter your authentication code" in response.data
        rescue_data = dict(help_setup="lost_device")
        response = client.post("/tf-rescue",
                               data=rescue_data,
                               follow_redirects=True)
        assert b"That didnt work out as we planned" in response.data

        # Test JSON
        headers = {
            "Accept": "application/json",
            "Content-Type": "application/json"
        }
        response = client.post("/tf-rescue", json=rescue_data, headers=headers)
        assert response.status_code == 500
        assert response.json["response"]["errors"]["help_setup"][
            0] == "Failed Again"
Beispiel #15
0
def add_user():
    user = User.query.order_by(User.id.desc()).first()
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    if request.method == 'POST':
        if 'email' in request.form:
            email = request.form.get('email')
        if 'password' in request.form:
            password = request.form.get('password')
        if 'name' in request.form:
            name = request.form.get('name')
        if 'firstname' in request.form:
            firstname = request.form.get('firstname')
        if 'phone' in request.form:
            phone = request.form.get('phone')
        if 'signing' in request.files:
            filename = str(user.id + 1) + '.jpg'
            signing = request.files.get('signing')
            path = f"APPLICATION/{admin.app['MODULES_FOLDER']}/{'admin'}/{'signing'}"
            pathlib.Path(path).mkdir(parents=True, exist_ok=True)
            try:
                signing.save(os.path.join(path, filename))
            except PermissionError:
                admin.log.error(
                    "Permission Error to create / save file to uploads folder")

        exists = db.session.query(
            db.exists().where(User.email == email)).scalar()
        if exists:
            flash("Utilisateur existe déja", "error")
            return redirect(url_for('admin.index'))

        encrypted_password = utils.hash_password(password)

        if not user_datastore.get_user(email):
            user_datastore.create_user(email=email,
                                       password=encrypted_password,
                                       last_name=name,
                                       first_name=firstname,
                                       phone=phone,
                                       signing=filename)

        try:
            db.session.commit()
        except OperationalError:
            admin.logger.error("Operational Error permission access database")
        user_datastore.add_role_to_user(email,
                                        'user')  # set Role to the new User
        try:
            db.session.commit()
        except OperationalError:
            admin.logger.error("Operational Error permission access database")
    flash("Utilisateur créer", "success")
    return redirect(url_for('admin.index'))
Beispiel #16
0
def insert_data():
    """Inserts default data into the database, such as an admin user"""
    from flask_app.models import User, Role
    from flask_security import utils, SQLAlchemyUserDatastore

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)

    if not User.query.first():
        user_datastore.create_user(email=app.config['ADMIN_USER'],
                                   password=utils.encrypt_password(
                                       app.config['ADMIN_PASSWORD']))
        db.session.commit()
Beispiel #17
0
def build_sample_db():
    """
    Populate a small db with some example entries.
    """

    import string
    import random

    db.drop_all()
    db.create_all()

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

    with app.app_context():
        user_role = Role(name='user')
        super_user_role = Role(name='superuser')
        db.session.add(user_role)
        db.session.add(super_user_role)
        db.session.commit()

        test_user = user_datastore.create_user(
            first_name='Admin',
            email='admin',
            password=encrypt_password('admin'),
            roles=[user_role, super_user_role]
        )

        first_names = [
            'Harry', 'Amelia', 'Oliver', 'Jack', 'Isabella', 'Charlie', 'Sophie', 'Mia',
            'Jacob', 'Thomas', 'Emily', 'Lily', 'Ava', 'Isla', 'Alfie', 'Olivia', 'Jessica',
            'Riley', 'William', 'James', 'Geoffrey', 'Lisa', 'Benjamin', 'Stacey', 'Lucy'
        ]
        last_names = [
            'Brown', 'Smith', 'Patel', 'Jones', 'Williams', 'Johnson', 'Taylor', 'Thomas',
            'Roberts', 'Khan', 'Lewis', 'Jackson', 'Clarke', 'James', 'Phillips', 'Wilson',
            'Ali', 'Mason', 'Mitchell', 'Rose', 'Davis', 'Davies', 'Rodriguez', 'Cox', 'Alexander'
        ]

        for i in range(len(first_names)):
            tmp_email = first_names[i].lower() + "." + last_names[i].lower() + "@example.com"
            tmp_pass = ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(10))
            user_datastore.create_user(
                first_name=first_names[i],
                last_name=last_names[i],
                email=tmp_email,
                password=encrypt_password(tmp_pass),
                roles=[user_role, ]
            )
        db.session.commit()
    return
Beispiel #18
0
def setup(app):
    """
    Setup Flask Security
    :param app: The Flask Application Object
    :return: None
    """
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app, user_datastore)

    if app.config["DEBUG"]:
        if not user_datastore.get_user('*****@*****.**'):
            user_datastore.create_user(email='*****@*****.**',
                                       password=hash_password('signmeup'))
            db.session.commit()
Beispiel #19
0
def test_change_token_uniquifier(app):
    # make sure that existing token no longer works once we change the token uniquifier
    from sqlalchemy import Column, String
    from flask_sqlalchemy import SQLAlchemy
    from flask_security.models import fsqla_v2 as fsqla
    from flask_security import Security, SQLAlchemyUserDatastore

    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
    db = SQLAlchemy(app)

    fsqla.FsModels.set_db_info(db)

    class Role(db.Model, fsqla.FsRoleMixin):
        pass

    class User(db.Model, fsqla.FsUserMixin):
        fs_token_uniquifier = Column(String(64), unique=True, nullable=False)

    with app.app_context():
        db.create_all()

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

    with app.app_context():
        ds.create_user(
            email="*****@*****.**",
            password=hash_password("password"),
        )
        ds.commit()

        client_nc = app.test_client(use_cookies=False)

        response = json_authenticate(client_nc)
        token = response.json["response"]["user"]["authentication_token"]
        verify_token(client_nc, token)

        # now change uniquifier
        with app.test_request_context("/"):
            user = app.security.datastore.find_user(email="*****@*****.**")
            app.security.datastore.reset_user_access(user)
            app.security.datastore.commit()

        verify_token(client_nc, token, status=401)

        # get new token and verify it works
        response = json_authenticate(client_nc)
        token = response.json["response"]["user"]["authentication_token"]
        verify_token(client_nc, token)
Beispiel #20
0
def seed_database():
    app.config.from_object(get_config())
    db.init_app(app)
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)
    user_datastore.create_user(email='*****@*****.**', password='******')
    user = db.session.query(User).first()
    post = Post()
    post.user = user
    post.title = "Test Title"
    post.content = 'This is the post content.'
    post.post_image = 'https://source.unsplash.com/random'
    post.post_image_alt = 'Unsplashed Image'
    db.session.add(post)
    db.session.commit()
Beispiel #21
0
def create_admin():
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)

    parameters = (
        'username',
        'email',
        'first_name',
        'last_name',
        'institution',
    )

    user_details = {}
    for parameter in parameters:
        user_details[parameter] = input(f'{parameter}: ')

    user_details.update(password=get_password(),
                        active=True,
                        approved=True,
                        confirmed_at=datetime.datetime.now())

    admin_user = user_datastore.create_user(**user_details)
    admin_user.roles.append(admin_role)

    db.session.commit()

    print('New admin user successfully created.')
Beispiel #22
0
def make_user(manager, email, password):
    """Create a pre-existing user an admin."""
    # Example: python3 -m compath make_admin [email protected] password

    ds = SQLAlchemyUserDatastore(manager, User, Role)
    user = ds.find_user(email=email)

    if user is None:
        ds.create_user(email=email,
                       password=password,
                       confirmed_at=datetime.datetime.utcnow())
        ds.commit()
        click.echo('User {} was successfully created'.format(email))

    else:
        click.echo('User {} already exists'.format(email))
Beispiel #23
0
def create_user(email, role):
    from flask_security import SQLAlchemyUserDatastore
    from security_monkey.datastore import User
    from security_monkey.datastore import Role
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)

    ROLES = ['View', 'Comment', 'Justify', 'Admin']
    if role not in ROLES:
        sys.stderr.write('[!] Role must be one of [{0}].\n'.format(' '.join(ROLES)))
        sys.exit(1)

    users = User.query.filter(User.email == email)

    if users.count() == 0:
        password1 = prompt_pass("Password")
        password2 = prompt_pass("Confirm Password")

        if password1 != password2:
            sys.stderr.write("[!] Passwords do not match\n")
            sys.exit(1)

        user = user_datastore.create_user(email=email, password=password1, confirmed_at=datetime.now())
    else:
        sys.stdout.write("[+] Updating existing user\n")
        user = users.first()

    user.role = role

    db.session.add(user)
    db.session.commit()
Beispiel #24
0
def create_user(email, role):
    from flask_security import SQLAlchemyUserDatastore
    from security_monkey.datastore import User
    from security_monkey.datastore import Role
    from flask_security.utils import encrypt_password

    user_datastore = SQLAlchemyUserDatastore(db, User, Role)

    ROLES = ['View', 'Comment', 'Justify', 'Admin']
    if role not in ROLES:
        sys.stderr.write('[!] Role must be one of [{0}].\n'.format(
            ' '.join(ROLES)))
        sys.exit(1)

    users = User.query.filter(User.email == email)

    if users.count() == 0:
        password1 = prompt_pass("Password")
        password2 = prompt_pass("Confirm Password")

        if password1 != password2:
            sys.stderr.write("[!] Passwords do not match\n")
            sys.exit(1)

        user = user_datastore.create_user(email=email,
                                          password=encrypt_password(password1),
                                          confirmed_at=datetime.now())
    else:
        sys.stdout.write("[+] Updating existing user\n")
        user = users.first()

    user.role = role

    db.session.add(user)
    db.session.commit()
def register_users_from_manifest(user_datastore: SQLAlchemyUserDatastore, manifest: Dict) -> None:
    """Register the users and roles in a manifest.

    :param user_datastore: A user data store
    :param dict manifest: A manifest dictionary, which contains two keys: ``roles`` and ``users``. The ``roles``
     key corresponds to a list of dictionaries containing ``name`` and ``description`` entries. The ``users`` key
     corresponds to a list of dictionaries containing ``email``, ``password``, and ``name`` entries
     as well as a optional ``roles`` entry with a corresponding list relational to the names in the ``roles``
     entry in the manifest.
    """
    for role in manifest['roles']:
        user_datastore.find_or_create_role(**role)

    for user_manifest in manifest['users']:
        email = user_manifest['email']
        user = user_datastore.find_user(email=email)
        if user is None:
            logger.info(f'creating user: {email}')
            user = user_datastore.create_user(
                confirmed_at=datetime.datetime.now(),
                email=email,
                password=user_manifest['password'],
                name=user_manifest['name'],
            )

        for role_name in user_manifest.get('roles', []):
            if user_datastore.add_role_to_user(user, role_name):
                logger.info(f'registered {user} as {role_name}')

    user_datastore.commit()
def create_admin_user(db, survey, email, password):
    user_datastore = SQLAlchemyUserDatastore(db, WebUser, WebUserRole)
    admin_role = user_datastore.find_or_create_role(name='admin')
    user = user_datastore.create_user(email=email,
                                      password=hash_password(password),
                                      survey_id=survey.id)
    user_datastore.add_role_to_user(user, admin_role)
Beispiel #27
0
def create_roles_users():
    log.info('Insert Role data in database')
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    admin = user_datastore.find_or_create_role(name='Admin',
                                               description='Administrator')
    user_datastore.find_or_create_role(name='api', description='API user')
    user = user_datastore.create_user(email=app.config['ADMIN_EMAIL'],
                                      password=app.config['ADMIN_PASSWORD'])
    user_datastore.add_role_to_user(user, admin)
    db.session.commit()
Beispiel #28
0
def configure_app(app):
    """Configure the app w.r.t Flask-security, databases, loggers."""
    config_name = os.getenv('FLASK_CONFIGURATION', 'default')
    app.config.from_object(CONFIG[config_name])

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

    # set up cross origin handling
    CORS(app, headers=['Content-Type'])

    db.create_all()
    if not User.query.first():
        user_datastore.create_user(email=app.config['ADMIN_USER'],
                                   password=utils.encrypt_password(
                                       app.config['ADMIN_PASSWORD']))
        db.session.commit()
Beispiel #29
0
def test_null_token_uniquifier(app):
    # If existing record has a null fs_token_uniquifier, should be set on first use.
    from sqlalchemy import Column, String
    from flask_sqlalchemy import SQLAlchemy
    from flask_security.models import fsqla_v2 as fsqla
    from flask_security import Security, SQLAlchemyUserDatastore

    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
    db = SQLAlchemy(app)

    fsqla.FsModels.set_db_info(db)

    class Role(db.Model, fsqla.FsRoleMixin):
        pass

    class User(db.Model, fsqla.FsUserMixin):
        fs_token_uniquifier = Column(String(64), unique=True, nullable=True)

    with app.app_context():
        db.create_all()

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

    with app.app_context():
        ds.create_user(
            email="*****@*****.**",
            password=hash_password("password"),
        )
        ds.commit()

        # manually null out fs_token_uniquifier
        user = ds.find_user(email="*****@*****.**")
        user.fs_token_uniquifier = None
        ds.put(user)
        ds.commit()

        client_nc = app.test_client(use_cookies=False)

        response = json_authenticate(client_nc)
        token = response.json["response"]["user"]["authentication_token"]
        verify_token(client_nc, token)
    def create_test_user(self, email, password):
        user_datastore = SQLAlchemyUserDatastore(db, User, Role)
        user = user_datastore.create_user(email=email,
                                          password=password,
                                          confirmed_at=datetime.now())
        user.role = 'Admin'
        user.active = True

        db.session.add(user)
        db.session.commit()
        db.session.refresh(user)
Beispiel #31
0
def create_app(priority_settings=None):
    app = Flask(__name__, static_url_path='')

    app.config.from_object(settings)
    app.config.from_envvar('TODO_SETTINGS', silent=True)
    app.config.from_object(priority_settings)

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

    app.register_blueprint(index)
    app.register_blueprint(todos)

    with app.app_context():
        db.create_all()
        if not User.query.first():
            user_datastore.create_user(
                email='*****@*****.**',
                password=encrypt_password('password'))
            db.session.commit()
    return app
Beispiel #32
0
    def create_user(self, **kwargs):
        tenant_name = request.form.get('tenant_name', None)

        if tenant_name:
            # lengthy?
            existing_tenant = Base.session.query(Tenant).filter(
                Tenant.name.like(tenant_name))

            if existing_tenant.count():
                kwargs['tenant_id'] = existing_tenant.id
                kwargs['tenant'] = existing_tenant
            else:
                tenant = Tenant(str(uuid.uuid1()), tenant_name)
                # Base.session.add(tenant)
                kwargs['tenant_id'] = tenant.id
                kwargs['tenant'] = tenant

        return SQLAlchemyUserDatastore.create_user(self, **kwargs)
Beispiel #33
0
def db(app):
    _db.app = app
    _db.create_all()

    # Admin role
    if not Role.query.filter_by(name='admin').first():
        admin_role = Role(name='admin')
        _db.session.add(admin_role)

    # Analyst role
    if not Role.query.filter_by(name='analyst').first():
        analyst_role = Role(name='analyst')
        _db.session.add(analyst_role)

    # Inactive user
    if not User.query.filter_by(username='******').first():
        user_datastore = SQLAlchemyUserDatastore(_db, User, Role)
        analyst_role = Role.query.filter_by(name='analyst').first()
        user_datastore.create_user(email='inactive@localhost', password=hash_password('inactive'), username='******',
                                   first_name='Inactive', last_name='Inactive', roles=[analyst_role])
        inactive_user = User.query.filter_by(username='******').first()
        inactive_user.active = False
        inactive_user.apikey = TEST_INACTIVE_APIKEY

    # Admin user
    if not User.query.filter_by(username='******').first():
        user_datastore = SQLAlchemyUserDatastore(_db, User, Role)
        admin_role = Role.query.filter_by(name='admin').first()
        user_datastore.create_user(email='admin@localhost', password=hash_password('admin'), username='******',
                                   first_name='Admin', last_name='Admin', roles=[admin_role])
        admin_user = User.query.filter_by(username='******').first()
        admin_user.apikey = TEST_ADMIN_APIKEY

    # Analyst user
    if not User.query.filter_by(username='******').first():
        user_datastore = SQLAlchemyUserDatastore(_db, User, Role)
        analyst_role = Role.query.filter_by(name='analyst').first()
        user_datastore.create_user(email='analyst@localhost', password=hash_password('analyst'), username='******',
                                   first_name='Analyst', last_name='Analyst', roles=[analyst_role])
        analyst_user = User.query.filter_by(username='******').first()
        analyst_user.apikey = TEST_ANALYST_APIKEY

    _db.session.commit()

    yield _db

    _db.drop_all()
Beispiel #34
0
def create_user():
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    # db.drop_all()
    # db.create_all()
    # user_datastore.create_user(username='******', password='******')
    # db.session.commit()
    # print user_datastore.find_user(username='******')
    for permissions, (name, desc) in Permission.PERMISSION_MAP.items():
        user_datastore.find_or_create_role(name=name,
                                           description=desc,
                                           permissions=permissions)
    for username, passwd, permissions in (('xjd', '123', (Permission.LOGIN,
                                                          Permission.EDITOR)),
                                          ('xilixjd', '123',
                                           (Permission.ADMINISTER, ))):
        user = user_datastore.create_user(username=username, password=passwd)
        db.session.commit()
        for permission in permissions:
            user_datastore.add_role_to_user(
                user,
                user_datastore.find_role(
                    role=Permission.PERMISSION_MAP[permission][0]))
            db.session.commit()
Beispiel #35
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()
    api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
    # print api
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
db.create_all()


import sys
sys.path.append("..")


from manager import db, app
from admin.admin_models import Role
from admin.admin_models import Manager
from flask_security import SQLAlchemyUserDatastore
from flask_security.utils import encrypt_password
import key
with app.app_context():
	user_role = Role(name='user')
	super_user_role = Role(name='superuser')
	db.session.add(user_role)
	db.session.add(super_user_role)
	db.session.commit()
	user_datastore = SQLAlchemyUserDatastore(db, Manager, Role)
	test_user = user_datastore.create_user(\
		first_name=key.MANAGER_NAME,\
		email=key.MAIL_USERNAME,\
		password=encrypt_password(key.MANAGER_PASSWORD),\
		roles=[user_role, super_user_role])
	db.session.commit()
# Create an admin profile. Useful for setting up the first admin when deployed
# on Heroku.

from flask_security.utils import encrypt_password
from flask_security import SQLAlchemyUserDatastore

from app import app
from app import db

from app.models import Role, User


user_datastore = SQLAlchemyUserDatastore(db, User, Role)

with app.app_context():
    super_user_role = Role(name='superuser')
    user_role = Role(name='user')

    db.session.add(super_user_role)
    db.session.add(user_role)
    db.session.commit()

    first_admin = user_datastore.create_user(
        email='admin',
        password=encrypt_password('admin'),
        roles=[user_role, super_user_role]
    )
    
db.session.add(first_admin)
db.session.commit()
Beispiel #38
0
from models import User, Role
from config import app, db
from flask_security.utils import encrypt_password
from flask_security import Security, SQLAlchemyUserDatastore, \
    UserMixin, RoleMixin, login_required, current_user


db.drop_all()
db.create_all()

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

with app.app_context():
    user_role = Role(name='user')
    super_user_role = Role(name='superuser')
    db.session.add(user_role)
    db.session.add(super_user_role)
    db.session.commit()

    test_user = user_datastore.create_user(
        username='******',
        password=encrypt_password('admin'),
        active=True,
        roles=[user_role, super_user_role],
    )

    db.session.commit()

Beispiel #39
0
db = SQLAlchemy(app)
CSRFProtect(app)

# set up the database model if not already set up
from app import models
db.create_all()
db.session.commit()

# setup the User/Role tables with flask-security, create base users/groups if neccessary
userstore = SQLAlchemyUserDatastore(db, models.User, models.Role)
sec = Security(app, userstore)
try:
    with app.app_context():
        userstore.find_or_create_role(name='admin', description='Administrator')
        userstore.find_or_create_role(name='user', description='General user')
        userstore.create_user(email=FIRST_USER_NAME,
                            password=utils.encrypt_password(FIRST_USER_PASS))
        userstore.add_role_to_user(FIRST_USER_NAME, 'admin')
        db.session.commit()
except: db.session.rollback()

# get the view controllers for the app
from app.views import main, admin, common

# set up main as a blueprint, add as many blueprints as necessary
app.register_blueprint(main.main)

# configure the admin interface, populate it with pages and links
app_admin = Admin(app, 'Flask Skeleton Admin', template_mode='bootstrap3', index_view=admin.AdminIndexView())
app_admin.add_view(admin.UserModelView(models.User, db.session))
app_admin.add_view(admin.RoleModelView(models.Role, db.session))
app_admin.add_link(MenuLink(name='Back to Site', url='/'))