Beispiel #1
0
def create_userprofile_for(email, username, full_name):
    """Create a fake user profile."""
    user = User.query.filter_by(email=email).one_or_none()
    if user:
        profile = UserProfile(user_id=int(user.get_id()))
        profile.username = username
        profile.full_name = full_name
        db.session.add(profile)
        db.session.commit()
Beispiel #2
0
def test_case_preserving_username(app):
    """Test that username preserves the case."""
    with app.app_context():
        with db.session.begin_nested():
            u1 = User(email='*****@*****.**')
            db.session.add(u1)
        db.session.add(UserProfile(user=u1, username="******"))
        db.session.commit()
        profile = UserProfile.get_by_username('info')
        assert profile.username == 'InFo'
Beispiel #3
0
def test_case_insensitive_username(app):
    """Test case-insensitive uniqueness."""
    with app.app_context():
        with db.session.begin_nested():
            u1 = User(email='*****@*****.**')
            u2 = User(email='*****@*****.**')
            db.session.add(u1, u2)
        profile1 = UserProfile(user=u1, username="******")
        profile2 = UserProfile(user=u2, username="******")
        db.session.add(profile1)
        db.session.add(profile2)
        pytest.raises(IntegrityError, db.session.commit)
Beispiel #4
0
def create_userprofile_for(email, username, full_name):
    """Create a fake user profile."""
    user = User.query.filter_by(email=email).one_or_none()
    if user:
        profile = UserProfile(user_id=int(user.get_id()))
        profile.username = username
        profile.full_name = full_name
        db.session.add(profile)
        db.session.commit()
        click.secho("User profile created for {}".format(email), fg="green")
    else:
        click.secho("ERROR: user {} does not exist".format(email), fg="red")
Beispiel #5
0
def test_delete_cascade(app):
    """Test that deletion of user, also removes profile."""
    with app.app_context():
        with db.session.begin_nested():
            u = User(email='*****@*****.**')
            db.session.add(u)
        p = UserProfile(user=u, username="******")
        db.session.add(p)
        db.session.commit()

        assert UserProfile.get_by_userid(u.id) is not None
        db.session.delete(u)
        db.session.commit()

        assert UserProfile.get_by_userid(u.id) is None
def test_delete_cascade(app):
    """Test that deletion of user, also removes profile."""
    with app.app_context():
        with db.session.begin_nested():
            u = User(email='*****@*****.**')
            db.session.add(u)
        p = UserProfile(user=u, username="******")
        db.session.add(p)
        db.session.commit()

        assert UserProfile.get_by_userid(u.id) is not None
        db.session.delete(u)
        db.session.commit()

        assert UserProfile.get_by_userid(u.id) is None
Beispiel #7
0
def notify_submission_created(record, coordinator_id, uploader, reviewer):
    coordinator = get_user_from_id(coordinator_id)

    if not coordinator:
        return

    site_url = current_app.config.get('SITE_URL', 'https://www.hepdata.net')

    name = coordinator.email
    coordinator_profile = UserProfile.get_by_userid(coordinator_id)
    if coordinator_profile:
        name = coordinator_profile.full_name

    collaboration = _get_collaboration(coordinator_id)

    message_body = render_template('hepdata_theme/email/created.html',
                                   name=name,
                                   actor=coordinator.email,
                                   collaboration=collaboration,
                                   uploader=uploader,
                                   reviewer=reviewer,
                                   article=record['recid'],
                                   title=record['title'],
                                   site_url=site_url,
                                   link=site_url +
                                   "/record/{0}".format(record['recid']))

    create_send_email_task(
        coordinator.email,
        '[HEPData] Submission {0} has been created'.format(record['recid']),
        message_body)
Beispiel #8
0
def user_rest(app_rest_with_userprofiles):
    """Create users."""
    with db.session.begin_nested():
        datastore = app_rest_with_userprofiles.extensions['security'].datastore
        user1 = datastore.create_user(email='*****@*****.**',
                                      password='******', active=True)
        profile = UserProfile(username='******', user=user1)
        db.session.add(profile)
    db.session.commit()
    return user1
def test_case_preserving_username(app):
    """Test that username preserves the case."""
    with app.app_context():
        with db.session.begin_nested():
            u1 = User(email='*****@*****.**')
            db.session.add(u1)
        db.session.add(UserProfile(user=u1, username="******"))
        db.session.commit()
        profile = UserProfile.get_by_username('info')
        assert profile.username == 'InFo'
Beispiel #10
0
def user(userprofiles_app):
    """Create users."""
    with db.session.begin_nested():
        datastore = userprofiles_app.extensions['security'].datastore
        user1 = datastore.create_user(email='*****@*****.**',
                                      password='******',
                                      active=True)
        profile = UserProfile(username='******', user=user1)
        db.session.add(profile)
    db.session.commit()
    return user1
Beispiel #11
0
def prepare(record_uuid: str, presentation: Presentation):
    if current_user.is_anonymous:
        user_meta = {
            'id': None,
            'email': None,
            'login_ip': None,
            'current_ip': str(request.remote_addr),
            'roles': [],
            'full_name': 'Anonymous',
            'username': None
        }
    else:
        profile_meta = {}
        profile: UserProfile = UserProfile.get_by_userid(current_user.id)
        if profile:
            profile_meta = {
                'full_name': profile.full_name,
                'username': profile.username,
            }
        user_meta = {
            'id':
            current_user.id,
            'email':
            current_user.email,
            'current_ip':
            str(request.remote_addr),
            'login_ip':
            str(current_user.current_login_ip),
            'roles': [{
                'id': role.id,
                'name': role.name
            } for role in current_user.roles]
        }
        user_meta.update(profile_meta)
    headers = {k: v for k, v in request.headers}

    try:
        result = presentation.prepare(record_uuid,
                                      user_meta,
                                      headers,
                                      delayed=True)
        if isinstance(result, AsyncResult):
            return jsonify({'job_id': result.task_id})
        else:
            return jsonify({'job_id': result})
    except WorkflowsPermissionError as e:
        logger.exception('Exception detected in prepare')
        abort(403, e)
    except WorkflowDefinitionError:
        logger.exception('Exception detected in prepare')
        abort(
            400, 'There was an error in the {} workflow definition'.format(
                presentation.name))
Beispiel #12
0
    def success_response(self, user):
        """Return response with current user's information."""
        from invenio_app_ils.proxies import current_app_ils

        user_payload = default_user_payload(user)
        user_payload["roles"] = self.get_user_roles()
        # fetch user profile for extra info
        user_profile = UserProfile.get_by_userid(user.id)

        loc_pid_value, _ = current_app_ils.get_default_location_pid
        user_payload.update(
            dict(
                username=user_profile.username,
                full_name=user_profile.full_name,
                location_pid=loc_pid_value,
            ))
        return jsonify(user_payload), 200
Beispiel #13
0
def test_profile_updating(base_app):
    base_app.config.update(USERPROFILES_EXTEND_SECURITY_FORMS=True)
    InvenioUserProfiles(base_app)
    app = base_app

    with app.app_context():
        user = User(email='lollorosso', password='******')
        db.session.add(user)
        db.session.commit()

        assert user.profile is None

        profile = UserProfile(username='******', full_name='Test T. User')
        user.profile = profile
        user.profile.username = '******'
        assert user.profile.username == 'Different_Name'
        assert profile.username == 'Different_Name'
Beispiel #14
0
def test_userprofiles(app):
    """Test UserProfile model."""
    profile = UserProfile()

    # Check the username validator works on the model
    profile.username = test_usernames['valid']
    with pytest.raises(ValueError):
        profile.username = test_usernames['invalid_characters']
    with pytest.raises(ValueError):
        profile.username = test_usernames['invalid_begins_with_number']

    # Test non-validated attributes
    profile.first_name = 'Test'
    profile.last_name = 'User'
    assert profile.first_name == 'Test'
    assert profile.last_name == 'User'
Beispiel #15
0
def send_coordinator_notification_email(recid, version, user, message=None):
    """
    :param recid:
    :param user: user object
    :param message: message to send
    :return:
    """

    hepsubmission = get_latest_hepsubmission(publication_recid=recid)
    coordinator = get_user_from_id(hepsubmission.coordinator)

    if not coordinator:
        raise NoParticipantsException()

    site_url = current_app.config.get('SITE_URL', 'https://www.hepdata.net')

    record = get_record_by_id(recid)

    name = coordinator.email
    coordinator_profile = UserProfile.get_by_userid(hepsubmission.coordinator)
    if coordinator_profile:
        name = coordinator_profile.full_name

    collaboration = _get_collaboration(hepsubmission.coordinator)

    message_body = render_template('hepdata_theme/email/passed_review.html',
                                   name=name,
                                   actor=user.email,
                                   collaboration=collaboration,
                                   article=recid,
                                   version=version,
                                   message=message,
                                   title=record['title'],
                                   site_url=site_url,
                                   link=site_url + "/record/{0}".format(recid),
                                   dashboard_link=site_url + "/dashboard")

    create_send_email_task(
        coordinator.email,
        '[HEPData] Submission {0} is ready to be finalised'.format(recid),
        message_body)
def test_userprofiles(app):
    """Test UserProfile model."""
    profile = UserProfile()

    # Check the username validator works on the model
    profile.username = test_usernames['valid']
    with pytest.raises(ValueError):
        profile.username = test_usernames['invalid_characters']
    with pytest.raises(ValueError):
        profile.username = test_usernames['invalid_begins_with_number']

    # Test non-validated attributes
    profile.first_name = 'Test'
    profile.last_name = 'User'
    assert profile.first_name == 'Test'
    assert profile.last_name == 'User'
Beispiel #17
0
def users(app, db):
    """Create admin, librarians and patrons."""
    # with Postgresql, when dropping the User table, the sequence is not
    # automatically reset to 1, causing issues with the tests demo data.
    db.session.execute("ALTER SEQUENCE IF EXISTS accounts_user_id_seq RESTART")
    db.session.commit()

    with db.session.begin_nested():
        datastore = app.extensions["security"].datastore
        # create users
        patron1 = datastore.create_user(email="*****@*****.**",
                                        password="******",
                                        active=True)

        patron2 = datastore.create_user(email="*****@*****.**",
                                        password="******",
                                        active=True)
        patron3 = datastore.create_user(email="*****@*****.**",
                                        password="******",
                                        active=True)
        librarian = datastore.create_user(email="*****@*****.**",
                                          password="******",
                                          active=True)
        librarian2 = datastore.create_user(email="*****@*****.**",
                                           password="******",
                                           active=True)
        admin = datastore.create_user(email="*****@*****.**",
                                      password="******",
                                      active=True)
        # Give role to admin
        admin_role = Role(name="admin")
        db.session.add(
            ActionRoles(action=superuser_access.value, role=admin_role))
        datastore.add_role_to_user(admin, admin_role)
        # Give role to librarian
        librarian_role = Role(name="librarian")
        db.session.add(
            ActionRoles(action=backoffice_access_action.value,
                        role=librarian_role))
        datastore.add_role_to_user(librarian, librarian_role)
        # Give role to librarian2
        db.session.add(
            ActionRoles(action=backoffice_access_action.value,
                        role=librarian_role))
        datastore.add_role_to_user(librarian2, librarian_role)
    db.session.commit()

    for patron, name in [
        (admin, "Admin User"),
        (librarian, "Librarian One"),
        (librarian2, "Librarian Two"),
        (patron1, "Patron One"),
        (patron2, "Patron Two"),
        (patron3, "Patron Three"),
    ]:
        profile = UserProfile(**dict(
            user_id=patron.id,
            _displayname="id_" + str(patron.id),
            full_name=name,
        ))
        db.session.add(profile)
    db.session.commit()

    return {
        "admin": admin,
        "librarian": librarian,
        "librarian2": librarian2,
        "patron1": patron1,
        "patron2": patron2,
        "patron3": patron3,
    }