Example #1
0
def tag_edit(id_tag):
    """List of documents attached to this tag."""
    id_user = current_user.get_id()
    tag = WtgTAG.query.get(id_tag)

    if not tag:
        flash(_("Invalid tag id"), "error")
        return redirect(url_for(".display_cloud"))

    if tag.id_user != id_user:
        flash(_("You are not authorized to view this tag"), "error")
        return redirect(url_for(".display_cloud"))

    form = EditTagForm(request.values, csrf_enabled=False, obj=tag)

    if form.validate_on_submit():
        form.populate_obj(tag)

        name_count = db.session.query(WtgTAG).filter_by(id_user=id_user, name=tag.name).count()

        if name_count == 1:
            db.session.add(tag)
            db.session.commit()
            flash(_("Tag Successfully edited."), "success")

        else:
            flash(_("Tag name") + " <strong>" + tag.name + "</strong> " + _("is already in use."), "error")

    return dict(tag=tag, form=form)
Example #2
0
def resetpassword(reset_key):
    """Reset password form (loaded after asked new password)."""
    email = None
    try:
        email = EmailConfirmationSerializer().load_token(
            reset_key
        )['data']['email']
    except KeyError:
        flash(
            _('This request for resetting a password has already been used.'),
            'error'
        )
    except (BadData, SignatureExpired):
        flash(_('This request for resetting a password is not valid or is '
                'expired.'), 'error')

    if email is None or cfg['CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS'] >= 3:
        return redirect(url_for('webaccount.index'))

    form = ResetPasswordForm(request.values)

    if form.validate_on_submit():
        password = request.values['password']

        # change password
        user = User.query.filter_by(email=email).one()
        user.password = password
        db.session.merge(user)
        db.session.commit()

        flash(_("The password was correctly reset."), 'success')
        return redirect(url_for('webaccount.index'))

    return render_template('accounts/resetpassword.html', form=form)
Example #3
0
def validate_tag_name(dummy_form, field):
    """Check validity of tag name."""
    max_len = cfg['CFG_TAGS_NAME_MAX_LENGTH']
    max_char = cfg['CFG_TAGS_MAX_CHARACTER']

    if field.data:
        suggested_silent = wash_tag_silent(field.data)
        suggested = wash_tag_blocking(suggested_silent)

        field.data = suggested_silent

        if suggested != suggested_silent:
            raise validators.ValidationError(
                _('Forbidden characters. Try ') + suggested + '.')

        if len(suggested) <= 0:
            raise validators.ValidationError(
                _('The name must contain valid characters.'))

        if len(suggested_silent) > max_len:
            raise validators.ValidationError(
                _('The name cannot exeed %(x_max_len)d characters.',
                  x_max_len=max_len))

        if max(ord(letter) for letter in suggested_silent) > max_char:
            raise validators.ValidationError(_('Forbidden character.'))
Example #4
0
def send_reset_password_email(email):
    """Reset password by sending a email with the unique link."""
    expires_in = cfg.get('CFG_WEBSESSION_ADDRESS_ACTIVATION_EXPIRE_IN_DAYS')

    reset_key = EmailConfirmationSerializer(
        expires_in=timedelta(days=expires_in).total_seconds()
    ).create_token(email, {'email': email})

    if not reset_key:
        raise AccountSecurityError(
            _('Something goes wrong when the cookie has been generated')
        )

    email_text = render_template(
        'accounts/email_reset_password.html',
        reset_key=reset_key, email=email
    )

    return send_email(
        fromaddr=cfg['CFG_SITE_SUPPORT_EMAIL'],
        subject=_("Password reset request for %(website)s",
                  website=cfg['CFG_SITE_URL']),
        toaddr=email,
        content=email_text
    )
Example #5
0
def manage(group_id):
    """Manage your group."""
    group = Group.query.get_or_404(group_id)
    form = GroupForm(request.form, obj=group)

    if form.validate_on_submit():
        if group.can_edit(current_user):
            try:
                group.update(**form.data)
                flash(_('Group "%(name)s" was updated', name=group.name),
                      'success')
            except Exception as e:
                flash(str(e), 'error')
                return render_template(
                    "groups/new.html",
                    form=form,
                    group=group,
                )
        else:
            flash(
                _(
                    'You cannot edit group %(group_name)s',
                    group_name=group.name
                ),
                'error'
            )

    return render_template(
        "groups/new.html",
        form=form,
        group=group,
    )
Example #6
0
 def inner(*args, **kwargs):
     try:
         return f(*args, **kwargs)
     except InvalidDepositionType:
         if request.is_xhr:
             abort(400)
         flash(_("Invalid deposition type."), "danger")
         return redirect(url_for(endpoint))
     except (DepositionDoesNotExists,):
         flash(_("Deposition does not exists."), "danger")
         return redirect(url_for(endpoint))
     except (DepositionNotDeletable,):
         flash(_("Deposition cannot be deleted."), "danger")
         return redirect(url_for(endpoint))
     except (InvalidDepositionAction,):
         flash(_("Invalid action."), "warning")
         return redirect(url_for(endpoint))
     except (DraftDoesNotExists,):
         abort(400)
     except (FormDoesNotExists,):
         abort(400)
     except (UploadError,):
         abort(400)
     except (ForbiddenAction,):
         flash(_("Not allowed."), "danger")
         return redirect(url_for(endpoint))
     except (UploadError,):
         abort(400)
Example #7
0
def new_member(group_id):
    """Add (invite) new member."""
    group = Group.query.get_or_404(group_id)

    if group.can_invite_others(current_user):
        form = NewMemberForm()

        if form.validate_on_submit():
            emails = filter(None, form.data['emails'].splitlines())
            group.invite_by_emails(emails)
            flash(_('Requests sent!'), 'success')
            return redirect(url_for('.members', group_id=group.id))

        return render_template(
            "groups/new_member.html",
            group=group,
            form=form
        )

    flash(
        _(
            'You cannot invite user or yourself (i.e. join) to the group '
            '%(group_name)s',
            group_name=group.name
        ),
        'error'
    )
    return redirect(url_for('.index'))
Example #8
0
def access():
    """Access."""
    try:
        email = EmailConfirmationSerializer().load_token(
            request.values['mailcookie']
        )['data']['email']

        u = User.query.filter(User.email == email).one()
        u.note = 1
        try:
            db.session.commit()
        except SQLAlchemyError:
            db.session.rollback()
            flash(_('Authorization failled.'), 'error')
            redirect('/')

        if current_user.is_authenticated:
            current_user.reload()
            flash(_('Your email address has been validated'), 'success')
        else:
            UserInfo(u.id).reload()
            flash(
                _('Your email address has been validated, and you can '
                  'now proceed to sign-in.'),
                'success'
            )
    except Exception:
        current_app.logger.exception("Authorization failed.")
        flash(_('The authorization token is invalid.'), 'error')
    return redirect('/')
Example #9
0
def check_for_software_updates(flash_message=False):
    """Check for a new release of Invenio.

    :return: True if you have latest version, else False if you need to upgrade
             or None if server was not reachable.
    """
    from invenio_base.globals import cfg
    from invenio_base.i18n import _
    try:
        find = re.compile('Invenio v[0-9]+.[0-9]+.[0-9]+(\-rc[0-9])?'
                          ' is released')

        release_notes = 'https://raw.githubusercontent.com/' \
            'inveniosoftware/invenio/master/RELEASE-NOTES'

        webFile = urllib.request.urlopen(release_notes)

        temp = ""
        version = ""
        version1 = ""
        while True:
            temp = webFile.readline()
            match1 = find.match(temp)
            try:
                version = match1.group()
                break
            except Exception:
                pass
            if not temp:
                break

        webFile.close()
        submatch = re.compile('[0-9]+.[0-9]+.[0-9]+(\-rc[0-9])?')
        version1 = submatch.search(version)
        web_version = version1.group().split(".")

        local_version = cfg['CFG_VERSION'].split(".")

        if (web_version[0] > local_version[0] or
                web_version[0] == local_version[0] and
                web_version[1] > local_version[1] or
                web_version[0] == local_version[0] and
                web_version[1] == local_version[1] and
                web_version[2] > local_version[2]):
            if flash_message:
                flash(_('A newer version of Invenio is available for '
                        'download. You may want to visit '
                        '<a href="%(wiki)s">%()s</a>',
                        wiki='<a href=\"http://inveniosoftware.org/wiki/'
                             '/Installation/Download'), 'warning(html_safe)')

            return False
    except Exception as e:
        print(e)
        if flash_message:
            flash(_('Cannot download or parse release notes '
                    'from %(release_notes)s', release_notes=release_notes),
                  'error')
        return None
    return True
Example #10
0
def login(nickname=None, password=None, login_method=None,
          remember=False, referer=None):
    """Login."""
    if cfg.get('CFG_ACCESS_CONTROL_LEVEL_SITE') > 0:
        return abort(401)  # page is not authorized

    if 'action' in request.values:
        warnings.warn('Action argument "{}" is not used anymore.'.format(
            request.values['action']), DeprecationWarning)
    form = LoginForm(CombinedMultiDict(
        [ImmutableMultiDict({'referer': referer, 'login_method': 'Local'}
                            if referer else {'login_method': 'Local'}),
         request.values]), csrf_enabled=False)

    if request.method == "POST":
        try:
            if login_method == 'Local' and form.validate_on_submit() and \
               authenticate(nickname, password, login_method=login_method,
                            remember=remember):
                flash(
                    _("You are logged in as %(nick)s.", nick=nickname),
                    "success"
                )
                return login_redirect(referer)

            else:
                flash(_("Invalid credentials."), "error")
        except Exception as e:
            current_app.logger.error(
                'Exception during login process: %s', str(e)
            )
            flash(_("Problem with login."), "error")

    return render_template('accounts/login.html', form=form), 401
Example #11
0
def approve(group_id, user_id):
    """Approve a user."""
    membership = Membership.query.get_or_404((user_id, group_id))
    group = membership.group

    if group.can_edit(current_user):
        try:
            membership.accept()
        except Exception as e:
            flash(str(e), 'error')
            return redirect(url_for('.requests', group_id=membership.group.id))

        flash(_('%(user)s accepted to %(name)s group.',
                user=membership.user.email,
                name=membership.group.name), 'success')
        return redirect(url_for('.requests', group_id=membership.group.id))

    flash(
        _(
            'You cannot approve memberships for the group %(group_name)s',
            group_name=group.name
        ),
        'error'
    )
    return redirect(url_for('.index'))
Example #12
0
def leave(group_id):
    """Leave group."""
    group = Group.query.get_or_404(group_id)

    if group.can_leave(current_user):
        try:
            group.remove_member(current_user)
        except Exception as e:
            flash(str(e), "error")
            return redirect(url_for('.index'))

        flash(
            _(
                'You have successfully left %(group_name)s group.',
                group_name=group.name
            ),
            'success'
        )
        return redirect(url_for('.index'))

    flash(
        _(
            'You cannot leave the group %(group_name)s',
            group_name=group.name
        ),
        'error'
    )
    return redirect(url_for('.index'))
Example #13
0
 def formatoptions(self):
     """Return list of format options."""
     if len(self._formatoptions):
         return [dict(f) for f in self._formatoptions]
     else:
         return [{'code': u'hb',
                  'name': _("HTML %(format)s", format=_("brief")),
                  'content_type': u'text/html'}]
Example #14
0
def notes(recid):
    """Note page."""
    """View for the record notes extracted from comments"""

    if not cfg["ANNOTATIONS_NOTES_ENABLED"]:
        return redirect(url_for("comments.comments", recid=recid))

    from invenio_access.local_config import VIEWRESTRCOLL
    from invenio_access.mailcookie import mail_cookie_create_authorize_action
    from invenio_comments.api import check_user_can_view_comments

    auth_code, auth_msg = check_user_can_view_comments(current_user, recid)
    if auth_code and current_user.is_guest:
        cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {"collection": g.collection})
        url_args = {"action": cookie, "ln": g.ln, "referer": request.referrer}
        flash(_("Authorization failure"), "error")
        return redirect(url_for("webaccount.login", **url_args))
    elif auth_code:
        flash(auth_msg, "error")
        abort(401)

    page = request.args.get("page", type=int)
    if cfg["ANNOTATIONS_PREVIEW_ENABLED"] and not request.is_xhr:
        # the notes will be requested again via AJAX
        notes = []
    elif page is None or page == -1:
        notes = prepare_notes(get_annotations({"where.record": recid}))
    else:
        import re

        rgx = re.compile("^P\.([0-9]*?\,)*?" + str(page) + "(,|$|[_]\.*)")
        notes = prepare_notes(get_annotations({"where.marker": rgx, "where.record": recid}))

    if request.is_xhr:
        template = "annotations/notes_fragment.html"
    else:
        template = "annotations/notes.html"
        flash(
            _(
                'This is a summary of all the comments that includes only the \
                 existing annotations. The full discussion is available \
                 <a href="'
                + url_for("comments.comments", recid=recid)
                + '">here</a>.'
            ),
            "info",
        )

    return render_template(
        template,
        notes=notes,
        option="notes",
        get_note_title=get_note_title,
        note_is_collapsed=note_is_collapsed,
        get_original_comment=get_original_comment,
        wash_html_id=wash_html_id,
    )
def validate_tag_exists(dummy_form, field):
    """Check if id_tag matches a tag in database."""
    if field.data:
        try:
            field.data = int(field.data)
        except ValueError:
            raise validators.ValidationError(_("Tag ID must be an integer."))

        if not db.session.query(WtgTAG).get(field.data):
            raise validators.ValidationError(_("Tag does not exist."))
Example #16
0
def subscribe(recid):
    uid = current_user.get_id()
    subscription = CmtSUBSCRIPTION(id_bibrec=recid, id_user=uid,
                                   creation_time=datetime.now())
    try:
        db.session.add(subscription)
        db.session.commit()
        flash(_('You have been successfully subscribed'), 'success')
    except:
        flash(_('You are already subscribed'), 'error')
    return redirect(url_for('.comments', recid=recid))
Example #17
0
def current_user_password_validator(form, field):
    """Validate password field if is the password of the user."""
    id_user = current_user.get_id()
    if not id_user:
        raise validators.ValidationError(
            _("Nobody is currently logged-in."))

    user = User.query.filter_by(id=id_user).one()
    if not user.verify_password(field.data):
        raise validators.ValidationError(
            _('The password inserted is not valid.')
        )
Example #18
0
def report(recid, id):
    if CommentRights(id).can_perform_action():
        CmtRECORDCOMMENT.query.filter(CmtRECORDCOMMENT.id == id).update(dict(
            nb_abuse_reports=CmtRECORDCOMMENT.nb_abuse_reports + 1),
            synchronize_session='fetch')

        log_comment_action(cfg['CFG_WEBCOMMENT_ACTION_CODE']['REPORT_ABUSE'],
                           id, recid)
        flash(_('Comment has been reported.'), 'success')
    else:
        flash(_('Comment has been already reported.'), 'error')

    return redirect(url_for('comments.comments', recid=recid))
Example #19
0
def delete_all(confirmed=0):
    """
    Delete every message belonging a logged user.
    @param confirmed: 0 will produce a confirmation message.
    """
    uid = current_user.get_id()
    if confirmed != 1:
        return render_template('messages/confirm_delete.html')

    if dbquery.delete_all_messages(uid):
        flash(_("Your mailbox has been emptied."), "info")
    else:
        flash(_("Could not empty your mailbox."), "warning")
    return redirect(url_for('.index'))
Example #20
0
def vote(recid, id, value):
    if CommentRights(id).can_perform_action():
        value = 1 if int(value) > 0 else 0
        CmtRECORDCOMMENT.query.filter(CmtRECORDCOMMENT.id == id).update(dict(
            nb_votes_total=CmtRECORDCOMMENT.nb_votes_total + 1,
            nb_votes_yes=CmtRECORDCOMMENT.nb_votes_yes + value),
            synchronize_session='fetch')

        log_comment_action(cfg['CFG_WEBCOMMENT_ACTION_CODE']['VOTE'], id,
                           recid)
        flash(_('Thank you for your vote.'), 'success')
    else:
        flash(_('You can not vote for this comment.'), 'error')

    return redirect(url_for('comments.comments', recid=recid))
Example #21
0
def lost():
    """Lost."""
    form = LostPasswordForm(request.values)

    if form.validate_on_submit():
        email = request.values["email"]
        try:
            if send_reset_password_email(email=email):
                flash(_("A password reset link has been sent to %(whom)s", whom=email), "success")
            else:
                flash(_("Error happen when the email was send. " "Please contact the administrator."), "error")
        except AccountSecurityError as e:
            flash(e, "error")

    return render_template("accounts/lost.html", form=form)
Example #22
0
def create_year_selectbox(name, from_year=-1, length=10, selected_year=0,
                          ln=None):
    """Creates an HTML menu (dropdownbox) for year selection.

    @param name: name of control( i.e. name of the variable you'll get)
    @param from_year: year on which to begin. if <0 assume it is current year
    @param length: number of items in menu
    @param selected_year: initial selected year (if in range), else: label is
                          selected
    @param ln: language
    @return: html as string
    """
    ln = default_ln(ln)
    _ = gettext_set_language(ln)
    if from_year < 0:
        from_year = time.localtime()[0]
    out = "<select name=\"%s\">\n" % name
    out += '  <option value="0"'
    if selected_year == 0:
        out += ' selected="selected"'
    out += ">%s</option>\n" % _("Year")
    for i in range(from_year, from_year + length):
        out += "<option value=\"%i\"" % i
        if (i == selected_year):
            out += " selected=\"selected\""
        out += ">%i</option>\n" % i
    out += "</select>\n"
    return out
Example #23
0
    def edit_form(self, obj=None):
        """Edit form."""
        kbtype = request.args['kbtype'] if 'kbtype' in request.args else 'w'

        if kbtype == KnwKB.KNWKB_TYPES['written_as']:
            self.form = WrittenAsKnowledgeForm
        elif kbtype == KnwKB.KNWKB_TYPES['dynamic']:
            self.form = DynamicKnowledgeForm
        else:
            self.form = TaxonomyKnowledgeForm

        form = self.form(obj=obj)

        if not form.is_submitted():
            # load extra data: obj => form
            if kbtype == KnwKB.KNWKB_TYPES['dynamic']:
                if obj.kbdefs:
                    form.id_collection.data = obj.kbdefs.id_collection
                    form.output_tag.data = obj.kbdefs.output_tag
                    form.search_expression.data = obj.kbdefs.search_expression

            if kbtype == KnwKB.KNWKB_TYPES['taxonomy']:
                file_name = obj.get_filename()
                if os.path.isfile(file_name):
                    form.tfile.label.text = form.tfile.label.text + " *"
                    # TODO add the possibility to download the file
                    form.tfile.description = _("Already uploaded %(name)s",
                                               name=obj.get_filename())

        form.kbtype.data = kbtype

        return form
def restart_record_prev(objectid):
    """Restart the last task for current object."""
    continue_oid_delayed(oid=objectid, start_point="restart_task")
    return jsonify(dict(
        category="success",
        message=_("Object restarted task successfully.")
    ))
def delete_from_db(objectid):
    """Delete the object from the db."""
    BibWorkflowObject.delete(objectid)
    return jsonify(dict(
        category="success",
        message=_("Object deleted successfully.")
    ))
Example #26
0
def index(p, so, page):
    """Index page with uploader and list of existing depositions."""
    ctx = mycommunities_ctx()

    if not so:
        so = cfg.get('COMMUNITIES_DEFAULT_SORTING_OPTION')

    communities = Community.filter_communities(p, so)
    featured_community = FeaturedCommunity.get_current()
    form = SearchForm(p=p)
    per_page = cfg.get('COMMUNITIES_DISPLAYED_PER_PAGE', 10)
    page = max(page, 1)
    p = Pagination(page, per_page, communities.count())

    ctx.update({
        'r_from': max(p.per_page * (p.page - 1), 0),
        'r_to': min(p.per_page * p.page, p.total_count),
        'r_total': p.total_count,
        'pagination': p,
        'form': form,
        'title': _('Community Collections'),
        'communities': communities.slice(
            per_page * (page - 1), per_page * page).all(),
        'featured_community': featured_community,
        'format_record': format_record,
    })

    return render_template(
        "communities/index.html",
        **ctx
    )
Example #27
0
def delete():
    """Delete a tag."""
    response = {}
    response["action"] = "delete"

    id_tags = request.values.getlist("id_tag", type=int)

    # Validate
    for id_tag in id_tags:
        try:
            field = Field("data", id_tag)
            validate_tag_exists(None, field)
            validate_user_owns_tag(None, field)
        except validators.ValidationError as ex:
            flash(ex.message, "error")

    for id_tag in id_tags:
        tag = WtgTAG.query.get(id_tag)
        db.session.delete(tag)

    db.session.commit()

    # WtgTAG.query\
    #    .filter(WtgTAG.id.in_(id_tags))\
    #    .delete(synchronize_session=False)

    flash(_("Successfully deleted tags."), "success")

    return redirect(url_for(".display_list"))
Example #28
0
    def __iter__(self):
        """Get all the output formats."""
        from invenio_formatter import registry

        yield ('', _('Default'))
        for code, format_ in iteritems(registry.output_formats):
            yield (code, format_['name'])
def continue_record(objectid):
    """Continue workflow for current object."""
    continue_oid_delayed(oid=objectid, start_point='continue_next')
    return jsonify(dict(
        category="success",
        message=_("Object continued with next task successfully.")
    ))
Example #30
0
def create(deposition_type=None):
    """Create a new deposition."""
    if request.is_xhr and request.method != "POST":
        return ("", 405)

    deposition_type = DepositionType.get_default() if deposition_type is None else deposition_type

    if deposition_type is None:
        flash(_("Invalid deposition type."), "error")
        return ("", 400) if request.is_xhr else redirect(url_for(".index"))

    deposition = Deposition.create(current_user, type=deposition_type)
    deposition.save()

    return (
        (str(deposition.id), 200)
        if request.is_xhr
        else redirect(
            url_for(
                ".run",
                deposition_type=(None if deposition.type.is_default() else deposition.type.get_identifier()),
                uuid=deposition.id,
            )
        )
    )
Example #31
0
def collection_breadcrumbs(collection, endpoint=None):
    """TODO."""
    b = []
    if endpoint is None:
        endpoint = request.endpoint
    if collection.id > 1:
        qargs = request.values.to_dict()
        k = 'cc' if 'cc' in qargs else 'c'
        del qargs[k]
        b = [(_('Home'), endpoint, qargs)] + collection.breadcrumbs(
            builder=crumb_builder(endpoint), ln=g.ln)[1:]
    return b
Example #32
0
class EasySearchForm(InvenioBaseForm):
    """Defines form for easy seach popup."""

    author = AutocompleteField(_('Author'),
                               data_provide="typeahead-url",
                               data_source=lambda: url_for(
                                   'search.autocomplete', field='exactauthor'))
    title = StringField(_('Title'))
    rn = AutocompleteField(_('Report number'),
                           data_provide="typeahead-url",
                           data_source=lambda: url_for('search.autocomplete',
                                                       field='reportnumber'))
    aff = AutocompleteField(_('Affiliation'),
                            data_provide="typeahead-url",
                            data_source=lambda: url_for('search.autocomplete',
                                                        field='affiliation'))
    cn = AutocompleteField(_('Collaboration'),
                           data_provide="typeahead-url",
                           data_source=lambda: url_for('search.autocomplete',
                                                       field='collaboration'))
    k = AutocompleteField(
        _('Keywords'),
        data_provide="typeahead-url",
        data_source=lambda: url_for('search.autocomplete', field='keyword'))
    journal = FormField(JournalForm,
                        widget=RowWidget(classes={
                            0: 'col-xs-6',
                            1: 'col-xs-3',
                            2: 'col-xs-3'
                        }))
def tag_details(id_tag):
    """List of documents attached to this tag."""
    if not id_tag:
        flash(_('Invalid tag id'), "error")
        return redirect(url_for('.display_cloud'))

    tag = WtgTAG.query.get(id_tag)

    if not tag:
        flash(_('Invalid tag id'), "error")
        return redirect(url_for('.display_cloud'))

    if tag.id_user != current_user.get_id():
        flash(_('You are not authorized to view this tag'), "error")
        return redirect(url_for('.display_cloud'))

    if not tag.records:
        flash(_('There are no documents tagged with ') + tag.name)
        return redirect(url_for('.display_cloud'))

    return response_formated_records([bibrec.id for bibrec in tag.records],
                                     Collection.query.get(1), 'hb')
Example #34
0
def validate_bibrec_exists(dummy_form, field):
    """Check if id_bibrec matches a bibrec in database."""
    if field.data:
        try:
            field.data = int(field.data)
        except ValueError:
            raise validators.ValidationError(
                _('Record ID must be an integer.'))

        record = db.session.query(Record).get(field.data)

        if (not record):
            raise validators.ValidationError(_('Record does not exist.'))

        # Switch to merged record if present
        merged_id = record.merged_recid_final
        if merged_id != record.id:
            record = db.session.query(Record).get(merged_id)
            field.data = merged_id

        if record.deleted:
            raise validators.ValidationError(_('Record has been deleted.'))
Example #35
0
class CreateTagForm(InvenioBaseForm):
    """Defines form for creating a new tag."""

    name = StringField(_('Name'), [
        validators.DataRequired(), validate_tag_name, validate_name_available
    ])

    # Ajax requests only:
    # Send a record ID if the tag should be attached to the record
    # right after creation
    id_bibrec = HiddenField(
        'Tagged record',
        [validate_bibrec_exists, validate_user_can_see_bibrec])
Example #36
0
    def __iter__(self):
        """Iter function."""
        id_user = current_user.get_id()

        options = [('0', _('Private'))]

        options += db.session.query(Group.id, Group.name)\
            .join(Membership)\
            .filter(Membership.id_user == id_user)\
            .all()

        for (gid, name) in options:
            yield (str(gid), name)
Example #37
0
def add_comment(recid):
    uid = current_user.get_id()
    in_reply = request.args.get('in_reply', type=int)
    if in_reply is not None:
        comment = CmtRECORDCOMMENT.query.get(in_reply)

        if comment.id_bibrec != recid or comment.is_deleted:
            abort(401)

        if comment is not None:
            c = CmtRECORDCOMMENT()
            c.title = _('Re: ') + comment.title
            c.body = email_quote_txt(comment.body or '')
            c.in_reply_to_id_cmtRECORDCOMMENT = in_reply
            form = AddCmtRECORDCOMMENTForm(request.form, obj=c)
            return render_template('comments/add.html', form=form)

    form = AddCmtRECORDCOMMENTForm(request.values)
    if form.validate_on_submit():
        c = CmtRECORDCOMMENT()
        form.populate_obj(c)
        c.id_bibrec = recid
        c.id_user = uid
        c.date_creation = datetime.now()
        c.star_score = 0
        try:
            db.session.add(c)
            db.session.commit()
            flash(_('Comment was sent'), "info")
            from urlparse import urlparse
            if 'notes' in urlparse(request.referrer).path:
                return redirect(url_for('comments.notes', recid=recid) +
                                '#' + form.pdf_page.data)
            return redirect(url_for('comments.comments', recid=recid))
        except:
            db.session.rollback()

    return render_template('comments/add.html', form=form)
Example #38
0
def login(nickname=None,
          password=None,
          login_method=None,
          remember=False,
          referer=None):
    """Login."""
    if cfg.get('CFG_ACCESS_CONTROL_LEVEL_SITE') > 0:
        return abort(401)  # page is not authorized

    if 'action' in request.values:
        warnings.warn(
            'Action argument "{}" is not used anymore.'.format(
                request.values['action']), DeprecationWarning)
    form = LoginForm(CombinedMultiDict([
        ImmutableMultiDict({
            'referer': referer,
            'login_method': 'Local'
        } if referer else {'login_method': 'Local'}), request.values
    ]),
                     csrf_enabled=False)

    if request.method == "POST":
        try:
            if login_method == 'Local' and form.validate_on_submit() and \
               authenticate(nickname, password, login_method=login_method,
                            remember=remember):
                flash(_("You are logged in as %(nick)s.", nick=nickname),
                      "success")
                return login_redirect(referer)

            else:
                flash(_("Invalid credentials."), "error")
        except Exception as e:
            current_app.logger.error('Exception during login process: %s',
                                     str(e))
            flash(_("Problem with login."), "error")

    return render_template('accounts/login.html', form=form), 401
Example #39
0
class KnwKBRVALForm(Form):

    """KnwKBRVAL Form."""

    m_key = StringField(label="Map From")
    m_value = StringField(label="To")
    id_knwKB = SelectField(
        label=_('Knowledge'),
        choices=LocalProxy(lambda: [
            (k.id, k.name) for k in
            query_get_kb_by_type('written_as').all()]
        ),
        coerce=int,
    )
class AddCmtRECORDCOMMENTFormReview(AddCmtRECORDCOMMENTForm):

    """Define form for record comment review."""

    star_score = SelectField(_('Stars'), choices=[('1', _('*')),
                                                  ('2', _('**')),
                                                  ('3', _('***')),
                                                  ('4', _('****')),
                                                  ('5', _('*****'))])
Example #41
0
def add_kb(kb_name=u"Untitled", kb_type=None, tries=10):
    """Add a new kb in database, return the id.

    Add a new kb in database, and returns its id
    The name of the kb will be 'Untitled#'
    such that it is unique.

    :param kb_name: the name of the kb
    :param kb_type: the type of the kb, incl 'taxonomy' and 'dynamic'.
                   None for typical (leftside-rightside).
    :param tries: exit after <n> retry
    :return: the id of the newly created kb
    """
    created = False
    name = kb_name
    i = 0
    while (i < tries and created is False):
        try:
            kb = models.KnwKB(name=name, description="", kbtype=kb_type)
            created = True
            db.session.add(kb)
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
            # get the highest id to calculate the new name
            result = db.session.execute(
                db.select([models.KnwKB.id]).order_by(db.desc(
                    models.KnwKB.id)).limit(1)).first()
            index = result[0] + 1 if result is not None else 1
            name = kb_name + " " + str(index)
            i = i + 1
            created = False
        except Exception:
            db.session.rollback()
            raise

    if created is False:
        # TODO raise the right exception
        raise Exception(
            _(
                "Can't create knowledge base \"%(name)s\".\n"
                "Probabily the server is busy! "
                "Try again later.",
                name=kb_name))

    return kb.id
Example #42
0
class WebSearchUserSettingsForm(InvenioBaseForm):
    """User settings for search."""

    rg = SelectField(_('Results per page'),
                     choices=[('10', '10'), ('25', '25'), ('50', '50'),
                              ('100', '100')])
    websearch_hotkeys = SelectField(_('Hotkeys'),
                                    choices=[('0', _('Disable')),
                                             ('1', _('Enable'))])

    c = SelectMultipleField(_('Collections'), choices=GetCollections())
    of = SelectField(_('Personal output format'), choices=GetOutputFormats())
Example #43
0
def add_review(recid):
    uid = current_user.get_id()
    form = AddCmtRECORDCOMMENTFormReview(request.values)
    if form.validate_on_submit():
        c = CmtRECORDCOMMENT()
        form.populate_obj(c)
        c.id_bibrec = recid
        c.id_user = uid
        c.date_creation = datetime.now()
        try:
            db.session.add(c)
            db.session.commit()
            flash(_('Review was sent'), "info")
            return redirect(url_for('comments.reviews', recid=recid))
        except:
            db.session.rollback()

    return render_template('comments/add_review.html', form=form)
Example #44
0
    def validate_email(self, field):
        """Validate email address.

        Ensures that the email address is not already registered.
        """
        field.data = field.data.lower()
        validate_email(field.data.lower())

        try:
            User.query.filter(User.email == field.data).one()
            raise validators.ValidationError(
                _(
                    "Email address %(addr)s already exists in the"
                    " database. If this is your address, please sign-in and go"
                    " to Profile > Linked Accounts to link your account.",
                    addr=field.data))
        except SQLAlchemyError:
            pass
Example #45
0
def create(deposition_type=None):
    """Create a new deposition."""
    if request.is_xhr and request.method != 'POST':
        return ('', 405)

    deposition_type = DepositionType.get_default() if deposition_type is None \
        else deposition_type

    if deposition_type is None:
        flash(_('Invalid deposition type.'), 'error')
        return ('', 400) if request.is_xhr else redirect(url_for('.index'))

    deposition = Deposition.create(current_user, type=deposition_type)
    deposition.save()

    return (str(deposition.id), 200) if request.is_xhr else redirect(
        url_for(".run",
                deposition_type=(None if deposition.type.is_default() else
                                 deposition.type.get_identifier()),
                uuid=deposition.id))
 class SimpleRecordTestForm(WebDepositForm):
     keywords = fields.DynamicFieldList(
         fields.StringField(
             widget_classes='form-control',
             widget=field_widgets.ColumnInput(class_="col-xs-10"),
         ),
         label='Keywords',
         add_label='Add another keyword',
         icon='fa fa-tags fa-fw',
         widget_classes='',
         min_entries=1,
     )
     publication_date = fields.Date(
         label=_('Publication date'),
         icon='fa fa-calendar fa-fw',
         description='Required. Format: YYYY-MM-DD.',
         default=date.today(),
         validators=[],
         widget=field_widgets.date_widget,
         widget_classes='input-sm',
         export_key='imprint.date',
     )
Example #47
0
def reviews(recid):
    """Display reviews."""
    from invenio_access.local_config import VIEWRESTRCOLL
    from invenio_access.mailcookie import \
        mail_cookie_create_authorize_action
    from .api import check_user_can_view_comments
    auth_code, auth_msg = check_user_can_view_comments(current_user, recid)
    if auth_code and current_user.is_guest:
        cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {
            'collection': g.collection})
        url_args = {'action': cookie, 'ln': g.ln, 'referer': request.referrer}
        flash(_("Authorization failure"), 'error')
        return redirect(url_for('webaccount.login', **url_args))
    elif auth_code:
        flash(auth_msg, 'error')
        abort(401)

    comments = CmtRECORDCOMMENT.query.filter(db.and_(
        CmtRECORDCOMMENT.id_bibrec == recid,
        CmtRECORDCOMMENT.in_reply_to_id_cmtRECORDCOMMENT == 0,
        CmtRECORDCOMMENT.star_score > 0
    )).order_by(CmtRECORDCOMMENT.date_creation).all()
    return render_template('comments/reviews.html', comments=comments)
Example #48
0
        return decorated

    return wrapper


#
# Views
#
@blueprint.route("/", methods=['GET', 'POST'])
@ssl_required
@login_required
@register_menu(
    blueprint,
    'settings.applications',
    _('%(icon)s Applications', icon='<i class="fa fa-shield fa-fw"></i>'),
    order=5,
    active_when=lambda: request.endpoint.startswith("oauth2server_settings."))
@register_breadcrumb(blueprint, 'breadcrumbs.settings.applications',
                     _('Applications'))
def index():
    clients = Client.query.filter_by(
        user_id=current_user.get_id(),
        is_internal=False,
    ).all()

    tokens = Token.query.options(db.joinedload('client')).filter(
        Token.user_id == current_user.get_id(),
        Token.is_personal == True,  # noqa
        Token.is_internal == False,
        Client.is_internal == True,
Example #49
0
def check_for_software_updates(flash_message=False):
    """Check for a new release of Invenio.

    :return: True if you have latest version, else False if you need to upgrade
             or None if server was not reachable.
    """
    from invenio_base.globals import cfg
    from invenio_base.i18n import _
    try:
        find = re.compile('Invenio v[0-9]+.[0-9]+.[0-9]+(\-rc[0-9])?'
                          ' is released')

        release_notes = 'https://raw.githubusercontent.com/' \
            'inveniosoftware/invenio/master/RELEASE-NOTES'

        webFile = urllib.request.urlopen(release_notes)

        temp = ""
        version = ""
        version1 = ""
        while True:
            temp = webFile.readline()
            match1 = find.match(temp)
            try:
                version = match1.group()
                break
            except Exception:
                pass
            if not temp:
                break

        webFile.close()
        submatch = re.compile('[0-9]+.[0-9]+.[0-9]+(\-rc[0-9])?')
        version1 = submatch.search(version)
        web_version = version1.group().split(".")

        local_version = cfg['CFG_VERSION'].split(".")

        if (web_version[0] > local_version[0]
                or web_version[0] == local_version[0]
                and web_version[1] > local_version[1]
                or web_version[0] == local_version[0] and web_version[1]
                == local_version[1] and web_version[2] > local_version[2]):
            if flash_message:
                flash(
                    _(
                        'A newer version of Invenio is available for '
                        'download. You may want to visit '
                        '<a href="%(wiki)s">%()s</a>',
                        wiki='<a href=\"http://invenio-software.org/wiki/'
                        '/Installation/Download'), 'warning(html_safe)')

            return False
    except Exception as e:
        print(e)
        if flash_message:
            flash(
                _(
                    'Cannot download or parse release notes '
                    'from %(release_notes)s',
                    release_notes=release_notes), 'error')
        return None
    return True
Example #50
0
             ('claimpaperusers', 'claimpaper_view_pid_universe', {}),
             ('claimpaperoperators', 'claimpaper_view_pid_universe', {}),
             ('claimpaperusers', 'claimpaper_claim_own_papers', {}),
             ('claimpaperoperators', 'claimpaper_claim_own_papers', {}),
             ('claimpaperoperators', 'claimpaper_claim_others_papers', {}),
             ('claimpaperusers', 'claimpaper_change_own_data', {}),
             ('claimpaperoperators', 'claimpaper_change_own_data', {}),
             ('claimpaperoperators', 'claimpaper_change_others_data', {}),
             ('holdingpenusers', 'viewholdingpen', {}),
             ('depositusers', 'usedeposit', {}),
             )


# Activities (i.e. actions) for which exists an administrative web interface.
CFG_ACC_ACTIVITIES_URLS = {
    'runbibedit' : (_("Run Record Editor"), "%s/%s/edit/?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)),
    'runbibdocfile' : (_("Run Document File Manager"), "%s/%s/managedocfiles?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)),
    'runbibmerge' : (_("Run Record Merger"), "%s/%s/merge/?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)),
    'cfgbibknowledge' : (_("Configure BibKnowledge"), "%s/kb?ln=%%s" % CFG_SITE_URL),
    'cfgoaiharvest' : (_("Configure OAI Harvest"), "%s/admin/oaiharvest/oaiharvestadmin.py?ln=%%s" % CFG_SITE_URL),
    'cfgwebaccess' : (_("Configure WebAccess"), "%s/admin/webaccess/webaccessadmin.py?ln=%%s" % CFG_SITE_URL),
    'cfgwebcomment' : (_("Configure WebComment"), "%s/admin/webcomment/webcommentadmin.py?ln=%%s" % CFG_SITE_URL),
    'claimpaper_claim_others_papers' : (_("Run Person/Author Manager"), "%s/author/search?ln=%%s" % CFG_SITE_URL)
}

CFG_WEBACCESS_MSGS = {
    0: 'Try to <a href="%s/youraccount/login?referer=%%s">login</a> with another account.' % (CFG_SITE_SECURE_URL),
    1: '<br />If you think this is not correct, please contact: <a href="mailto:%s">%s</a>' % (CFG_SITE_SUPPORT_EMAIL, CFG_SITE_SUPPORT_EMAIL),
    2: '<br />If you have any questions, please write to <a href="mailto:%s">%s</a>' % (CFG_SITE_SUPPORT_EMAIL, CFG_SITE_SUPPORT_EMAIL),
    3: 'Guest users are not allowed, please <a href="%s/youraccount/login">login</a>.' % CFG_SITE_SECURE_URL,
    4: 'The site is temporarily closed for maintenance.  Please come back soon.',
Example #51
0
    ('statisticsusers', 'viewstatistics', {}),
    ('claimpaperusers', 'claimpaper_view_pid_universe', {}),
    ('claimpaperoperators', 'claimpaper_view_pid_universe', {}),
    ('claimpaperusers', 'claimpaper_claim_own_papers', {}),
    ('claimpaperoperators', 'claimpaper_claim_own_papers', {}),
    ('claimpaperoperators', 'claimpaper_claim_others_papers', {}),
    ('claimpaperusers', 'claimpaper_change_own_data', {}),
    ('claimpaperoperators', 'claimpaper_change_own_data', {}),
    ('claimpaperoperators', 'claimpaper_change_others_data', {}),
    ('holdingpenusers', 'viewholdingpen', {}),
    ('depositusers', 'usedeposit', {}),
)

# Activities (i.e. actions) for which exists an administrative web interface.
CFG_ACC_ACTIVITIES_URLS = {
    'runbibedit': (_("Run Record Editor"),
                   "%s/%s/edit/?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)),
    'runbibdocfile':
    (_("Run Document File Manager"),
     "%s/%s/managedocfiles?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)),
    'runbibmerge': (_("Run Record Merger"),
                    "%s/%s/merge/?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)),
    'cfgbibknowledge': (_("Configure BibKnowledge"),
                        "%s/kb?ln=%%s" % CFG_SITE_URL),
    'cfgoaiharvest':
    (_("Configure OAI Harvest"),
     "%s/admin/oaiharvest/oaiharvestadmin.py?ln=%%s" % CFG_SITE_URL),
    'cfgwebaccess':
    (_("Configure WebAccess"),
     "%s/admin/webaccess/webaccessadmin.py?ln=%%s" % CFG_SITE_URL),
    'cfgwebcomment':
Example #52
0
                      static_url_path='/docs',
                      template_folder='templates',
                      static_folder='static')

from invenio_collections.models import Collection


def _read_markdown_as_html(target):
    input_file = markdown.codecs.open(CURRENT_DIR + target,
                                      mode="r",
                                      encoding="utf-8")
    return markdown.markdown(input_file.read())


@blueprint.route('/b2share-about', methods=['GET'])
@register_breadcrumb(blueprint, 'breadcrumbs.about', _('About'))
def b2share_about():
    html = _read_markdown_as_html("/templates/about.md")
    collection = Collection.query.get_or_404(1)
    return render_template('docs.html',
                           markdown_render=html,
                           collection=collection)


@blueprint.route('/b2share-tou', methods=['GET'])
@register_breadcrumb(blueprint, 'breadcrumbs.tou', _('Terms of Use'))
def b2share_tou():
    html = _read_markdown_as_html("/templates/tou.md")
    collection = Collection.query.get_or_404(1)
    return render_template('docs.html',
                           markdown_render=html,
blueprint = Blueprint('webtag',
                      __name__,
                      url_prefix='/yourtags',
                      template_folder='templates',
                      static_folder='static')

default_breadcrumb_root(blueprint, '.webaccount.tags')


@blueprint.route('/', methods=['GET', 'POST'])
@blueprint.route('/display', methods=['GET', 'POST'])
@blueprint.route('/display/cloud', methods=['GET', 'POST'])
@login_required
@templated('tags/display_cloud.html')
@register_menu(blueprint, 'personalize.tags', _('Your Tags'))
@register_breadcrumb(blueprint, '.', _('Your Tags'))
def display_cloud():
    """List of user's private/group/public tags."""
    user = User.query.get(current_user.get_id())
    tags = user.tags_query.order_by(WtgTAG.name).all()

    # Calculate document count for each tag
    min_count = 0
    max_count = 0
    for tag in tags:
        if tag.record_count > max_count:
            max_count = tag.record_count
        if tag.record_count < min_count:
            min_count = tag.record_count
Example #54
0
    request args and reencode them.
    """
    @wraps(f)
    def decorated(*args, **kwargs):
        if request.args:
            request.url = request.base_url + "?" + url_encode(request.args)
        return f(*args, **kwargs)

    return decorated


#
# Views
#
@blueprint.route('/authorize', methods=['GET', 'POST'])
@register_breadcrumb(blueprint, '.', _('Authorize application'))
@login_required
@error_handler
@urlreencode
@oauth2.authorize_handler
def authorize(*args, **kwargs):
    """View for rendering authorization request."""
    if request.method == 'GET':
        client = Client.query.filter_by(
            client_id=kwargs.get('client_id')).first()

        if not client:
            abort(404)

        ctx = dict(client=client,
                   oauth_request=kwargs.get('request'),
def register_menu_items():
    """Register empty account breadcrumb."""
    item = current_menu.submenu('breadcrumbs.settings')
    item.register('', _('Account'))
@blueprint.route("/")
@ssl_required
@login_required
def index():
    """Index page."""
    return redirect(url_for(".profile"))


@blueprint.route("/profile", methods=['GET', 'POST'])
@ssl_required
@login_required
@register_menu(
    blueprint,
    'settings.profile',
    _('%(icon)s Profile', icon='<i class="fa fa-user fa-fw"></i>'),
    order=0,
    active_when=lambda: request.endpoint.startswith("accounts_settings."))
@register_breadcrumb(blueprint, 'breadcrumbs.settings.profile', _('Profile'))
def profile():
    """Change password form for authenticated users."""
    u = User.query.filter_by(id=current_user.get_id()).first()

    profile_form = ProfileForm(formdata=None, obj=u, prefix="profile")
    verification_form = VerificationForm(formdata=None, prefix="verification")
    password_form = ChangePasswordForm(formdata=None, prefix="password")

    form = request.form.get('submit', None)
    if form == 'password':
        password_form.process(formdata=request.form)
        if password_form.validate_on_submit():
Example #57
0
# from invenio_access.local_config import \
# FIXME
WEBACCESSACTION = 'cfgwebaccess'

blueprint = Blueprint('webaccess_admin', __name__,
                      url_prefix="/admin/webaccess",
                      template_folder='../templates',
                      static_folder='../static')


@blueprint.route('/', methods=['GET', 'POST'])
@login_required
@permission_required(WEBACCESSACTION)
@templated('access/admin/index.html')
@register_breadcrumb(blueprint, 'admin.webaccess_admin', _('WebAccess'))
def index():
    """Index."""
    actions = [
        dict(url=url_for('.rolearea'),
             title=_('Role Area'),
             description=_('Main area to configure administration rights '
                           'and authorization rules.')),
        dict(url=url_for('.actionarea'),
             title=_('Action Area'),
             description=_('Configure administration rights with the '
                           'actions as starting point.')),
        dict(url=url_for('.userarea'),
             title=_('User Area'),
             description=_('Configure administration rights with the '
                           'users as starting point.')),
Example #58
0
def index():
    """Index."""
    actions = [
        dict(url=url_for('.rolearea'),
             title=_('Role Area'),
             description=_('Main area to configure administration rights '
                           'and authorization rules.')),
        dict(url=url_for('.actionarea'),
             title=_('Action Area'),
             description=_('Configure administration rights with the '
                           'actions as starting point.')),
        dict(url=url_for('.userarea'),
             title=_('User Area'),
             description=_('Configure administration rights with the '
                           'users as starting point.')),
        dict(url=url_for('.resetarea'),
             title=_('Reset Area'),
             description=_('Reset roles, actions and authorizations.')),
        dict(url=url_for('.manageaccounts'),
             title=_('Manage Accounts Area'),
             description=_('Manage user accounts.')),
        dict(url=url_for('.delegate_startarea'),
             title=_('Delegate Rights - With Restrictions'),
             description=_('Delegate your rights for some roles.')),
    ]
    return dict(actions=actions)
Example #59
0
 def register_item():
     item = app.extensions['menu'].submenu('main.admin')
     item.register('admin.index',
                   _('Admin'),
                   order=10,
                   visible_when=lambda: current_user.is_admin)
 def __init__(self):
     super(WebTagSettings, self).__init__()
     self.icon = 'tags'
     self.title = _('Tags')
     self.view = url_for('webtag.display_cloud')
     self.edit = url_for('webaccount.edit', name=self.name)