Exemple #1
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))
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()
Exemple #3
0
def delete_user(username):
    """
    Seriously? What did you expect?
    """
    user_datastore = SQLAlchemyUserDatastore(DB, User, Role)
    user = user_datastore.find_user(email=username)
    user_datastore.delete_user(user)
    DB.session.commit()
def register_examples(manager: Manager, user_datastore: SQLAlchemyUserDatastore, butler: User) -> None:
    """Insert example graphs."""
    for graph in (sialic_acid_graph, egf_graph, statin_graph, homology_graph):
        if not manager.has_name_version(graph.name, graph.version):
            logger.info('uploading public example graph: %s', graph)
            insert_graph(manager, graph, user=butler, public=True)

    test_user = user_datastore.find_user(email='*****@*****.**')
    if test_user:
        for graph in (braf_graph,):
            if not manager.has_name_version(graph.name, graph.version):
                logger.info('uploading internal example graph: %s', graph)
                insert_graph(manager, graph, user=test_user, public=False)
Exemple #5
0
def make_admin(manager, email):
    """Make a pre-existing user an admin."""
    # Example: python3 -m compath make_admin [email protected]

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

    if user is None:
        click.echo('User not found')
        sys.exit(0)

    admin = ds.find_or_create_role('admin')

    ds.add_role_to_user(user, admin)
    ds.commit()
    click.echo('User {} is now admin'.format(email))
Exemple #6
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))
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)
Exemple #8
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 #9
0
def add_or_update_user(username, password, is_admin=False, active=True):
    """
    :param username: username or email --> unique identification
    :param password: the password may be passed in cleartext (yeah I just \
    wrote that) as it is encrypted internally.
    :param is_admin: determines whether the account receives the 'admin' role
    :param active: determines whether users will be able to login in with the\
    account
    """
    user_datastore = SQLAlchemyUserDatastore(DB, User, Role)
    existing_user = user_datastore.find_user(email=username)
    if existing_user:
        user = User.query.filter_by(email=username).first()
        user.email = username
        user.password = encrypt_password(password)
        user.active = active
    else:
        user = user_datastore.create_user(email=username,
                                          password=encrypt_password(password),
                                          active=active)

    if is_admin:
        user_datastore.add_role_to_user(user, 'admin')
    DB.session.commit()
Exemple #10
0
def test_uuid(app, request, tmpdir, realdburl):
    """Test that UUID extension of postgresql works as a primary id for users"""
    import uuid
    from flask_sqlalchemy import SQLAlchemy
    from sqlalchemy import Boolean, Column, DateTime, Integer, ForeignKey, String
    from sqlalchemy.dialects.postgresql import UUID
    from sqlalchemy.orm import relationship, backref

    from flask_security import SQLAlchemyUserDatastore
    from tests.conftest import _setup_realdb, _teardown_realdb

    # UUID type only supported by postgres - not sqlite.
    if not realdburl or "postgresql" not in realdburl:
        skip("This test only works on postgres")
    db_url, db_info = _setup_realdb(realdburl)
    app.config["SQLALCHEMY_DATABASE_URI"] = db_url

    db = SQLAlchemy(app)

    class RolesUsers(db.Model):
        __tablename__ = "roles_users"
        id = Column(Integer(), primary_key=True)
        user_id = Column("user_id", UUID(as_uuid=True), ForeignKey("user.id"))
        role_id = Column("role_id", UUID(as_uuid=True), ForeignKey("role.id"))

    class User(db.Model, UserMixin):
        __tablename__ = "user"
        id = Column(UUID(as_uuid=True),
                    primary_key=True,
                    default=uuid.uuid4,
                    index=True)
        email = Column(String(255), unique=True)
        fs_uniquifier = Column(String(64), unique=True, nullable=False)
        first_name = Column(String(255), index=True)
        last_name = Column(String(255), index=True)
        username = Column(String(255), unique=True, nullable=True)
        password = Column(String(255))
        active = Column(Boolean())
        created_at = Column(DateTime, default=datetime.datetime.utcnow)
        confirmed_at = Column(DateTime())
        roles = relationship("Role",
                             secondary="roles_users",
                             backref=backref("users", lazy="dynamic"))

    class Role(db.Model, RoleMixin):
        __tablename__ = "role"
        id = Column(UUID(as_uuid=True),
                    primary_key=True,
                    default=uuid.uuid4,
                    index=True)
        name = Column(String(80), unique=True)
        description = Column(String(255))

        # __hash__ is required to avoid the exception
        # TypeError: unhashable type: 'Role' when saving a User
        def __hash__(self):
            return hash(self.name)

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

    def tear_down():
        db.drop_all()
        _teardown_realdb(db_info)

    request.addfinalizer(tear_down)

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

    with app.app_context():
        user = ds.find_user(email="*****@*****.**")
        assert not user
Exemple #11
0
def rm(ctx, email):
    """Deletes a user"""
    ds = SQLAlchemyUserDatastore(ctx.obj, User, Role)
    u = ds.find_user(email=email)
    ds.delete_user(u)
    ds.commit()
 def find_user(self, **kwargs):
     return _wrap_user(SQLAlchemyUserDatastore.find_user(self, **kwargs))