Beispiel #1
0
def test_save_patron(get_uuid_pid_by_email, reindex, record_indexer, url_for1,
                     url_for2, send_email, confirm_user, app, db,
                     minimal_patron_only_record):
    """Test save patron"""

    # Convenient references
    security = LocalProxy(lambda: app.extensions['security'])
    datastore = LocalProxy(lambda: security.datastore)
    datastore.create_role(name='patrons')

    # hack the return value
    get_uuid_pid_by_email.return_value = None, None

    email = '*****@*****.**'
    u1 = datastore.create_user(email=email,
                               active=False,
                               password=hash_password('aafaf4as5fa'))
    datastore.commit()
    u2 = datastore.find_user(email=email)
    assert u1 == u2
    assert 1 == User.query.filter_by(email=email).count()
    email = minimal_patron_only_record.get('email')
    assert datastore.get_user(email) is None

    save_patron(minimal_patron_only_record, Patron.provider.pid_type,
                Patron.fetcher, Patron.minter, record_indexer, Patron, None)
    email = minimal_patron_only_record.get('email')

    # Verify that user exists in app's datastore
    user_ds = datastore.get_user(email)
    assert user_ds
    assert user_ds.email == email
def access_request(pid, record, template):
    """Create an access request."""
    recid = int(pid.pid_value)
    datastore = LocalProxy(
        lambda: current_app.extensions['security'].datastore)

    # Record must be in restricted access mode.
    if record.get('access_right') != 'restricted' or \
       not record.get('access_conditions'):
        abort(404)

    # Record must have an owner and owner must still exists.
    owners = record.get('owners', [])
    record_owners = [datastore.find_user(id=owner_id) for owner_id in owners]
    if not record_owners:
        abort(404)

    sender = None
    initialdata = dict()

    # Prepare initial form data
    if current_user.is_authenticated:
        sender = current_user
        initialdata['email'] = current_user.email
        if current_user.profile:
            initialdata['full_name'] = current_user.profile.full_name

    # Normal form validation
    form = AccessRequestForm(formdata=request.form, **initialdata)

    if form.validate_on_submit():
        accreq = AccessRequest.create(
            recid=recid,
            receiver=record_owners[0],
            sender_full_name=form.data['full_name'],
            sender_email=form.data['email'],
            justification=form.data['justification'],
            sender=sender
        )
        db.session.commit()

        if accreq.status == RequestStatus.EMAIL_VALIDATION:
            flash(_(
                "Email confirmation needed: We have sent you an email to "
                "verify your address. Please check the email and follow the "
                "instructions to complete the access request."),
                category='info')
        else:
            flash(_("Access request submitted."), category='info')
        return redirect(url_for('invenio_records_ui.recid', pid_value=recid))

    return render_template(
        template,
        pid=pid,
        record=record,
        form=form,
        owners=record_owners,
    )
def access_request(pid, record, template, **kwargs):
    """Create an access request."""
    recid = int(pid.pid_value)
    datastore = LocalProxy(
        lambda: current_app.extensions['security'].datastore)

    # Record must be in restricted access mode.
    if record.get('access_right') != 'restricted' or \
       not record.get('access_conditions'):
        abort(404)

    # Record must have an owner and owner must still exists.
    owners = record.get('owners', [])
    record_owners = [datastore.find_user(id=owner_id) for owner_id in owners]
    if not record_owners:
        abort(404)

    sender = None
    initialdata = dict()

    # Prepare initial form data
    if current_user.is_authenticated:
        sender = current_user
        initialdata['email'] = current_user.email
        if current_user.profile:
            initialdata['full_name'] = current_user.profile.full_name

    # Normal form validation
    form = AccessRequestForm(formdata=request.form, **initialdata)

    if form.validate_on_submit():
        accreq = AccessRequest.create(
            recid=recid,
            receiver=record_owners[0],
            sender_full_name=form.data['full_name'],
            sender_email=form.data['email'],
            justification=form.data['justification'],
            sender=sender
        )
        db.session.commit()

        if accreq.status == RequestStatus.EMAIL_VALIDATION:
            flash(_(
                "Email confirmation needed: We have sent you an email to "
                "verify your address. Please check the email and follow the "
                "instructions to complete the access request."),
                category='info')
        else:
            flash(_("Access request submitted."), category='info')
        return redirect(url_for('invenio_records_ui.recid', pid_value=recid))

    return render_template(
        template,
        pid=pid,
        record=record,
        form=form,
        owners=record_owners,
    )
Beispiel #4
0
 def delete_by_email(cls, email, deluser=False, delindex=False):
     """Delete user by email."""
     patron = cls.get_patron_by_email(email)
     if patron:
         patron.delete(delindex)
     datastore = LocalProxy(
         lambda: current_app.extensions['security'].datastore)
     user = datastore.find_user(email=email)
     if user:
         datastore.delete_user(user)
         datastore.commit()
Beispiel #5
0
def shib_login():
    """Get shibboleth user login page.

    :return: confirm user page when relation is empty
    """
    try:
        shib_session_id = request.args.get('SHIB_ATTR_SESSION_ID', None)

        if not shib_session_id:
            current_app.logger.error(_("Missing SHIB_ATTR_SESSION_ID!"))
            flash(_("Missing SHIB_ATTR_SESSION_ID!"), category='error')
            return _redirect_method()

        datastore = RedisStore(
            redis.StrictRedis.from_url(current_app.config['CACHE_REDIS_URL']))
        cache_key = current_app.config[
            'WEKO_ACCOUNTS_SHIB_CACHE_PREFIX'] + shib_session_id

        if not datastore.redis.exists(cache_key):
            current_app.logger.error(_("Missing SHIB_CACHE_PREFIX!"))
            flash(_("Missing SHIB_CACHE_PREFIX!"), category='error')
            return _redirect_method()

        cache_val = datastore.get(cache_key)

        if not cache_val:
            current_app.logger.error(_("Missing SHIB_ATTR!"))
            flash(_("Missing SHIB_ATTR!"), category='error')
            datastore.delete(cache_key)
            return _redirect_method()

        cache_val = json.loads(str(cache_val, encoding='utf-8'))
        session['shib_session_id'] = shib_session_id
        csrf_random = generate_random_str(length=64)
        session['csrf_random'] = csrf_random

        _datastore = LocalProxy(
            lambda: current_app.extensions['security'].datastore)
        user = _datastore.find_user(email=cache_val.get('shib_mail'))

        return render_template(
            current_app.config['WEKO_ACCOUNTS_CONFIRM_USER_TEMPLATE'],
            csrf_random=csrf_random,
            email=user.email if user else '')
    except BaseException:
        current_app.logger.error('Unexpected error: ', sys.exc_info()[0])
    return abort(400)
Beispiel #6
0
    next_url = request.args.get('next', None)
    post_logout_url = get_url(_security.post_logout_view)
    return redirect(next_url or post_logout_url)


@anonymous_user_required
def register():
    """View function which handles a registration request."""

    form = RegisterForm(csrf_enabled=not app.testing)

<<<<<<< HEAD
    if form.validate_on_submit():
        u = None
        try:
            u  = _datastore.find_user(email=form.data.get('email'))
            if u is not None:
                _logger.debug('User %s exists' % u)
                form.email.errors.append('A user with that email already exists')
                return render_template('security/registrations/new.html',
                           register_user_form=form)
        except:
            # Create user
            u = _datastore.create_user(**form.to_dict())
=======
    if not form.validate_on_submit():
        return render_template('security/register.html',
                               register_user_form=form,
                               **_ctx('register'))
>>>>>>> 8919129c95bb1e27e30a925240811cf63e13ece9