Beispiel #1
0
def _check_client_can_submit_file(client_ip="",
                                  metafile="",
                                  req=None,
                                  webupload=0,
                                  ln=CFG_SITE_LANG):
    """
    Is this client able to upload such a FILENAME?
    check 980 $a values and collection tags in the file to see if they are among the
    permitted ones as specified by CFG_BATCHUPLOADER_WEB_ROBOT_RIGHTS and ACC_AUTHORIZE_ACTION.
    Useful to make sure that the client does not override other records by
    mistake.
    """
    _ = gettext_set_language(ln)
    recs = create_records(metafile, 0, 0)
    user_info = collect_user_info(req)

    permitted_dbcollids = _get_client_authorized_collections(client_ip)
    if '*' in permitted_dbcollids:
        if not webupload:
            return True
        else:
            return (0, " ")

    filename_tag980_values = _detect_980_values_from_marcxml_file(recs)
    for filename_tag980_value in filename_tag980_values:
        if not filename_tag980_value:
            if not webupload:
                return False
            else:
                return (1, "Invalid collection in tag 980")
        if not webupload:
            if not filename_tag980_value in permitted_dbcollids:
                return False
        else:
            auth_code, auth_message = acc_authorize_action(
                req, 'runbatchuploader', collection=filename_tag980_value)
            if auth_code != 0:
                error_msg = _("The user '%(x_user)s' is not authorized to modify collection '%(x_coll)s'") % \
                            {'x_user': user_info['nickname'], 'x_coll': filename_tag980_value}
                return (auth_code, error_msg)

    filename_rec_id_collections = _detect_collections_from_marcxml_file(recs)

    for filename_rec_id_collection in filename_rec_id_collections:
        if not webupload:
            if not filename_rec_id_collection in permitted_dbcollids:
                return False
        else:
            auth_code, auth_message = acc_authorize_action(
                req, 'runbatchuploader', collection=filename_rec_id_collection)
            if auth_code != 0:
                error_msg = _("The user '%(x_user)s' is not authorized to modify collection '%(x_coll)s'") % \
                            {'x_user': user_info['nickname'], 'x_coll': filename_rec_id_collection}
                return (auth_code, error_msg)
    if not webupload:
        return True
    else:
        return (0, " ")
Beispiel #2
0
    def __call__(self, req, form):
        argd = wash_search_urlargd(form)
        argd['recid'] = self.recid

        if self.format is not None:
            argd['of'] = self.format
        req.argd = argd
        uid = getUid(req)
        if uid == -1:
            return page_not_authorized(req, "../",
                text="You are not authorized to view this record.",
                                       navmenuid='search')
        elif uid > 0:
            pref = get_user_preferences(uid)
            try:
                if 'rg' not in form:
                    # fetch user rg preference only if not overridden via URL
                    argd['rg'] = int(pref['websearch_group_records'])
            except (KeyError, ValueError):
                pass

        # Check if the record belongs to a restricted primary
        # collection.  If yes, redirect to the authenticated URL.
        user_info = collect_user_info(req)
        (auth_code, auth_msg) = check_user_can_view_record(user_info, self.recid)

        if argd['rg'] > CFG_WEBSEARCH_MAX_RECORDS_IN_GROUPS and acc_authorize_action(req, 'runbibedit')[0] != 0:
            argd['rg'] = CFG_WEBSEARCH_MAX_RECORDS_IN_GROUPS

        #check if the user has rights to set a high wildcard limit
        #if not, reduce the limit set by user, with the default one
        if CFG_WEBSEARCH_WILDCARD_LIMIT > 0 and (argd['wl'] > CFG_WEBSEARCH_WILDCARD_LIMIT or argd['wl'] == 0):
            if acc_authorize_action(req, 'runbibedit')[0] != 0:
                argd['wl'] = CFG_WEBSEARCH_WILDCARD_LIMIT

        # only superadmins can use verbose parameter for obtaining debug information
        if not isUserSuperAdmin(user_info):
            argd['verbose'] = 0

        if auth_code and user_info['email'] == 'guest':
            cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : guess_primary_collection_of_a_record(self.recid)})
            target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                    make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri}, {})
            return redirect_to_url(req, target, norobot=True)
        elif auth_code:
            return page_not_authorized(req, "../", \
                text=auth_msg, \
                navmenuid='search')

        # mod_python does not like to return [] in case when of=id:
        out = perform_request_search(req, **argd)
        if isinstance(out, intbitset):
            return out.fastdump()
        elif out == []:
            return str(out)
        else:
            return out
Beispiel #3
0
    def __call__(self, req, form):
        argd = wash_search_urlargd(form)
        argd['recid'] = self.recid
        if self.format is not None:
            argd['of'] = self.format

        req.argd = argd

        uid = getUid(req)
        user_info = collect_user_info(req)
        if uid == -1:
            return page_not_authorized(req, "../",
                text="You are not authorized to view this record.",
                                       navmenuid='search')
        elif uid > 0:
            pref = get_user_preferences(uid)
            try:
                if 'rg' not in form:
                    # fetch user rg preference only if not overridden via URL
                    argd['rg'] = int(pref['websearch_group_records'])
            except (KeyError, ValueError):
                pass

        if argd['rg'] > CFG_WEBSEARCH_MAX_RECORDS_IN_GROUPS and acc_authorize_action(req, 'runbibedit')[0] != 0:
            argd['rg'] = CFG_WEBSEARCH_MAX_RECORDS_IN_GROUPS

        #check if the user has rights to set a high wildcard limit
        #if not, reduce the limit set by user, with the default one
        if CFG_WEBSEARCH_WILDCARD_LIMIT > 0 and (argd['wl'] > CFG_WEBSEARCH_WILDCARD_LIMIT or argd['wl'] == 0):
            if acc_authorize_action(req, 'runbibedit')[0] != 0:
                argd['wl'] = CFG_WEBSEARCH_WILDCARD_LIMIT

        # only superadmins can use verbose parameter for obtaining debug information
        if not isUserSuperAdmin(user_info):
            argd['verbose'] = 0

        record_primary_collection = guess_primary_collection_of_a_record(self.recid)

        if collection_restricted_p(record_primary_collection):
            (auth_code, dummy) = acc_authorize_action(user_info, VIEWRESTRCOLL, collection=record_primary_collection)
            if auth_code:
                return page_not_authorized(req, "../",
                    text="You are not authorized to view this record.",
                    navmenuid='search')

        # Keep all the arguments, they might be reused in the
        # record page itself to derivate other queries
        req.argd = argd

        # mod_python does not like to return [] in case when of=id:
        out = perform_request_search(req, **argd)
        if isinstance(out, intbitset):
            return out.fastdump()
        elif out == []:
            return str(out)
        else:
            return out
Beispiel #4
0
    def authenticate(self, req, form):
        """Restricted search results pages."""

        argd = wash_search_urlargd(form)

        user_info = collect_user_info(req)
        for coll in argd['c'] + [argd['cc']]:
            if collection_restricted_p(coll):
                (auth_code, auth_msg) = acc_authorize_action(user_info, VIEWRESTRCOLL, collection=coll)
                if auth_code and user_info['email'] == 'guest':
                    cookie = mail_cookie_create_authorize_action(VIEWRESTRCOLL, {'collection' : coll})
                    target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                            make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri}, {})
                    return redirect_to_url(req, target, norobot=True)
                elif auth_code:
                    return page_not_authorized(req, "../", \
                        text=auth_msg, \
                        navmenuid='search')

        #check if the user has rights to set a high wildcard limit
        #if not, reduce the limit set by user, with the default one
        if CFG_WEBSEARCH_WILDCARD_LIMIT > 0 and (argd['wl'] > CFG_WEBSEARCH_WILDCARD_LIMIT or argd['wl'] == 0):
            auth_code, auth_message = acc_authorize_action(req, 'runbibedit')
            if auth_code != 0:
                argd['wl'] = CFG_WEBSEARCH_WILDCARD_LIMIT

        # only superadmins can use verbose parameter for obtaining debug information
        if not isUserSuperAdmin(user_info):
            argd['verbose'] = 0

        # Keep all the arguments, they might be reused in the
        # search_engine itself to derivate other queries
        req.argd = argd

        uid = getUid(req)
        if uid > 0:
            pref = get_user_preferences(uid)
            try:
                if 'rg' not in form:
                    # fetch user rg preference only if not overridden via URL
                    argd['rg'] = int(pref['websearch_group_records'])
            except (KeyError, ValueError):
                pass


        # mod_python does not like to return [] in case when of=id:
        out = perform_request_search(req, **argd)
        if isinstance(out, intbitset):
            return out.fastdump()
        elif out == []:
            return str(out)
        else:
            return out
Beispiel #5
0
def _check_client_can_submit_file(client_ip="", metafile="", req=None, webupload=0, ln=CFG_SITE_LANG):
    """
    Is this client able to upload such a FILENAME?
    check 980 $a values and collection tags in the file to see if they are among the
    permitted ones as specified by CFG_BATCHUPLOADER_WEB_ROBOT_RIGHTS and ACC_AUTHORIZE_ACTION.
    Useful to make sure that the client does not override other records by
    mistake.
    """
    _ = gettext_set_language(ln)
    recs = create_records(metafile, 0, 0)
    user_info = collect_user_info(req)

    permitted_dbcollids = _get_client_authorized_collections(client_ip)
    if '*' in permitted_dbcollids:
        if not webupload:
            return True
        else:
            return (0, " ")

    filename_tag980_values = _detect_980_values_from_marcxml_file(recs)
    for filename_tag980_value in filename_tag980_values:
        if not filename_tag980_value:
            if not webupload:
                return False
            else:
                return(1, "Invalid collection in tag 980")
        if not webupload:
            if not filename_tag980_value in permitted_dbcollids:
                return False
        else:
            auth_code, auth_message = acc_authorize_action(req, 'runbatchuploader', collection=filename_tag980_value)
            if auth_code != 0:
                error_msg = _("The user '%(x_user)s' is not authorized to modify collection '%(x_coll)s'") % \
                            {'x_user': user_info['nickname'], 'x_coll': filename_tag980_value}
                return (auth_code, error_msg)

    filename_rec_id_collections = _detect_collections_from_marcxml_file(recs)

    for filename_rec_id_collection in filename_rec_id_collections:
        if not webupload:
            if not filename_rec_id_collection in permitted_dbcollids:
                return False
        else:
            auth_code, auth_message = acc_authorize_action(req, 'runbatchuploader', collection=filename_rec_id_collection)
            if auth_code != 0:
                error_msg = _("The user '%(x_user)s' is not authorized to modify collection '%(x_coll)s'") % \
                            {'x_user': user_info['nickname'], 'x_coll': filename_rec_id_collection}
                return (auth_code, error_msg)
    if not webupload:
        return True
    else:
        return (0, " ")
Beispiel #6
0
def index(req, ln=CFG_SITE_LANG, journal_name=None, action=""):
    """
    Main administration page.

    Lists the journals, and offers options to edit them, delete them
    or add new journals
    """
    navtrail_previous_links = wjn.getnavtrail()

    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    try:
        journal_name = wash_journal_name(ln, journal_name)
        action = wash_url_argument(action, 'str')
    except InvenioWebJournalNoJournalOnServerError as e:
        # Ok, no journal. Let the admin add one...
        pass
    except InvenioWebJournalNoNameError as e:
        register_exception(req=req)
        return e.user_box()
    if action in ['delete', 'askDelete']:
        # To perform these, one must be authorized
        auth = acc_authorize_action(getUid(req),
                                    'cfgwebjournal',
                                    name=journal_name,
                                    with_editor_rights='yes')
    else:
        auth = acc_authorize_action(getUid(req), 'cfgwebjournal')
    if auth[0] == 0:
        return page(title=_('WebJournal Admin'),
                    body=wjn.perform_index(ln=ln,
                                           journal_name=journal_name,
                                           action=action,
                                           uid=getUid(req)),
                    uid=uid,
                    language=ln,
                    req=req,
                    navtrail=navtrail_previous_links,
                    lastupdated=__lastupdated__)
    else:
        return page_not_authorized(req=req,
                                   text=auth[1],
                                   navtrail=navtrail_previous_links)
Beispiel #7
0
    def compare_revisions(self, req, form):
        """Handle the compare revisions request"""
        argd = wash_urlargd(form, { \
                'ln': (str, CFG_SITE_LANG), \
                'rev1' : (str, ''), \
                'rev2' : (str, ''), \
                'recid': (int, 0)})

        ln = argd['ln']
        uid = current_user.get_id()
        _ = gettext_set_language(ln)

        # Checking if currently logged user has permission to perform this request

        auth_code, auth_message = acc_authorize_action(req, 'runbibedit')
        if auth_code != 0:
            return page_not_authorized(req=req, referer="/edit",
                                       text=auth_message, navtrail=navtrail)
        recid = argd['recid']
        rev1 = argd['rev1']
        rev2 = argd['rev2']
        ln = argd['ln']

        body, errors, warnings = perform_request_compare(ln, recid, rev1, rev2)

        return page(title = _("Comparing two record revisions"),
                    body =  body,
                    errors = errors,
                    warnings = warnings,
                    uid = uid,
                    language = ln,
                    navtrail    = navtrail,
                    lastupdated = __lastupdated__,
                    req         = req,
                    body_css_classes = ['bibedit'])
Beispiel #8
0
def Is_Referee(parameters, curdir, form, user_info=None):
    """
    This function checks whether the currently logged user is a
    referee for this document.
    """
    global uid_email,sysno,rn,uid
    doctype = form['doctype']
    # Get document category
    res = run_sql("SELECT categ FROM sbmAPPROVAL WHERE rn=%s", (rn,))
    if len(res) >0:
        categ = res[0][0]
        if categ == "unknown":
            ## FIXME: This was necessary for document types without categories,
            ## such as DEMOBOO:
            categ = "*"
    else:
        categ=""
    # Try to retrieve the referee's email from the referee's database
    (auth_code, auth_message) = acc_authorize_action(user_info, "referee",doctype=doctype, categ=categ)
    if auth_code != 0:
        raise InvenioWebSubmitFunctionStop("""
<SCRIPT>
        document.forms[0].action="/submit";
        document.forms[0].curpage.value = 1;
        document.forms[0].step.value = 0;
        user_must_confirm_before_leaving_page = false;
        alert('Sorry you (%s) have not been recognized as a referee for this type of document.\\nIf you think this is an error, please contact %s');
        document.forms[0].submit();
</SCRIPT>""" % (uid_email,CFG_SITE_SUPPORT_EMAIL))
    return ""
Beispiel #9
0
def index(req, c=CFG_SITE_NAME, ln=CFG_SITE_LANG):
    """Approval web Interface.
    GET params:

    """
    uid = getUid(req)
    (auth_code, auth_message) = acc_authorize_action(uid, 'submit')
    if auth_code > 0 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
        return page_not_authorized(req,
                                   "../approve.py/index",
                                   navmenuid='yourapprovals',
                                   text=auth_message)

    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    args = wash_urlargd(req.form, {'access': (str, '')})
    if args['access'] == "":
        return warning_page(
            _("approve.py: cannot determine document reference"), req, ln)
    url_params = get_approval_url_parameters(args['access'])
    if not url_params:
        return warning_page(_("approve.py: cannot find document in database"),
                            req, ln)
    url_params['ln'] = ln
    url = "%s/submit/direct?%s" % (CFG_SITE_SECURE_URL,
                                   urllib.urlencode(url_params))
    redirect_to_url(req, url)
Beispiel #10
0
def user_can_view_CMP(uid):
    action = bconfig.CLAIMPAPER_VIEW_PID_UNIVERSE
    auth = acc_authorize_action(uid, action)
    if auth[0] == 0:
        return True
    else:
        return False
Beispiel #11
0
def format_element(bfo, remote_server_id, style, css_class, link_label="Push via Sword",):
    """
    Print link to push an entry to a remote server through SWORD

    @param remote_server_id: ID of the remove server to link to. When
                             not specified, link to BibSword page
                             allowing to select server.
    """
    CFG_SITE_URL = current_app.config['CFG_SITE_URL']

    user_info = bfo.user_info
    auth_code, auth_message = acc_authorize_action(user_info, 'runbibswordclient')
    if auth_code != 0:
        return ""

    sword_arguments = {'ln': bfo.lang,
                       'recid': bfo.recID}

    if remote_server_id:
        sword_arguments['id_remote_server'] = remote_server_id
    else:
        sword_arguments['status'] = 'select_server'

    linkattrd = {}
    if style != '':
        linkattrd['style'] = style
    if css_class != '':
        linkattrd['class'] = css_class

    return create_html_link(CFG_SITE_URL + '/bibsword',
                            sword_arguments,
                            link_label,
                            linkattrd=linkattrd)
def Is_Original_Submitter(parameters, curdir, form, user_info=None):
    """
    This function compares the current logged in user email with the
    email of the original submitter of the record. If it is the same
    (or if the current user has superuser rights), we go on. If it
    differs, an error message is issued.
    """
    global uid_email,sysno,uid
    doctype = form['doctype']
    act = form['act']
    email = Get_Field("8560_f",sysno)
    email = re.sub("[\n\r ]+","",email)
    uid_email = re.sub("[\n\r ]+","",uid_email)
    (auth_code, auth_message) = acc_authorize_action(user_info, "submit",verbose=0,doctype=doctype, act=act)
    if re.search(uid_email,email,re.IGNORECASE) is None and auth_code != 0:
        raise InvenioWebSubmitFunctionStop("""
<SCRIPT>
   document.forms[0].action="/submit";
   document.forms[0].curpage.value = 1;
   document.forms[0].step.value = 0;
   user_must_confirm_before_leaving_page = false;
   alert('Only the submitter of this document has the right to do this action. \\nYour login (%s) is different from the one of the submitter (%s).');
   document.forms[0].submit();
</SCRIPT>""" % (uid_email,email))
    elif re.search(uid_email,email, re.IGNORECASE) is None and \
             auth_code == 0:
        if not os.path.exists(os.path.join(curdir, 'is_original_submitter_warning')):
            write_file(os.path.join(curdir, 'is_original_submitter_warning'), '')
            return ("""
<SCRIPT>
alert('Only the submitter of this document has the right to do this action. \\nYour login (%s) is different from the one of the submitter (%s).\\n\\nAnyway, as you have a special authorization for this type of documents,\\nyou are allowed to proceed! Watch out your actions!');
</SCRIPT>""" % (uid_email,email))

    return ""
Beispiel #13
0
def issue_control(req,
                  journal_name="",
                  issue=[],
                  ln=CFG_SITE_LANG,
                  action="cfg"):
    """
    Page that allows full control over creating, backtracing, adding to,
    removing from issues.
    """
    navtrail_previous_links = wjn.getnavtrail(
        ' &gt; <a class="navtrail" href="%s/admin/webjournal/webjournaladmin.py">WebJournal Admin</a> &gt; <a class="navtrail" href="%s/admin/webjournal/webjournaladmin.py/administrate?journal_name=%s">%s</a>'
        % (CFG_SITE_URL, CFG_SITE_URL, journal_name, journal_name))

    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)
    try:
        journal_name = wash_journal_name(ln, journal_name)
        action = wash_url_argument(action, 'str')
        issue = wash_url_argument(issue, 'list')
        issues = [wash_issue_number(ln,journal_name, _issue) \
                  for _issue in issue \
                  if _issue != "ww/YYYY"]
    except InvenioWebJournalNoJournalOnServerError as e:
        register_exception(req=req)
        return e.user_box()
    except InvenioWebJournalNoNameError as e:
        register_exception(req=req)
        return e.user_box()
    except InvenioWebJournalNoCurrentIssueError as e:
        register_exception(req=req)
        return e.user_box()
    except InvenioWebJournalIssueNumberBadlyFormedError as e:
        register_exception(req=req)
        return e.user_box()

    auth = acc_authorize_action(getUid(req),
                                'cfgwebjournal',
                                name="%s" % journal_name,
                                with_editor_rights='yes')
    if auth[0] == 0:
        return page(title=_("Publishing Interface"),
                    body=wjn.perform_request_issue_control(
                        journal_name=journal_name,
                        issues=issues,
                        ln=ln,
                        action=action),
                    uid=uid,
                    language=ln,
                    req=req,
                    navtrail=navtrail_previous_links,
                    lastupdated=__lastupdated__)
    else:
        return page_not_authorized(req=req,
                                   text=auth[1],
                                   navtrail=navtrail_previous_links)
Beispiel #14
0
def moderatelist(req, url, action, listtype=None, ln=CFG_SITE_LANG):
    """
    Add URL to list
    @param url: url
    @param listType: of CFG_WEBLINKBACK_LIST_TYPE
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = get_navtrail()
    navtrail_previous_links += ' &gt; <a class="navtrail" href="%s/admin/weblinkback/weblinkbackadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebLinkback Admin") + '</a>'

    user_info = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(user_info, 'cfgweblinkback')
    if auth_code:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
    else:
        url_field_value, return_code = perform_moderate_url(req=req,
                                                            url=url,
                                                            action=action,
                                                            list_type=listtype)
        return lists(req=req,
                     urlfieldvalue=url_field_value,
                     returncode=return_code,
                     ln=ln)
Beispiel #15
0
def lists(req,
          urlfieldvalue='',
          returncode=CFG_WEBLINKBACK_ACTION_RETURN_CODE['OK'],
          ln=CFG_SITE_LANG):
    """
    Display whitelist and blacklist
    @param urlFieldValue: value of the url input field
    @return_code: might indicate errors from a previous action, of CFG_WEBLINKBACK_ACTION_RETURN_CODE
    @param ln: language
    """
    # is passed as a string, must be an integer
    return_code = int(returncode)
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = get_navtrail()
    navtrail_previous_links += ' &gt; <a class="navtrail" href="%s/admin/weblinkback/weblinkbackadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebLinkback Admin") + '</a>'

    uid = getUid(req)
    userInfo = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(userInfo, 'cfgweblinkback')
    if auth_code:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
    else:
        return page(title=_("Linkback Whitelist/Blacklist Manager"),
                    body=perform_request_display_list(
                        return_code=return_code,
                        url_field_value=urlfieldvalue,
                        ln=ln),
                    uid=uid,
                    language=ln,
                    navtrail=navtrail_previous_links,
                    req=req)
Beispiel #16
0
def index(req, ln=CFG_SITE_LANG):
    """
    Menu of admin options
    @param ln: language
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = get_navtrail()
    navtrail_previous_links += ' &gt; <a class="navtrail" href="%s/admin/weblinkback/weblinkbackadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebLinkback Admin") + '</a>'

    uid = getUid(req)
    user_info = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(user_info, 'cfgweblinkback')
    if auth_code:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
    else:
        return page(title=_("WebLinkback Admin"),
                    body=perform_request_index(ln=ln),
                    uid=uid,
                    language=ln,
                    navtrail=navtrail_previous_links,
                    req=req)
Beispiel #17
0
def moderatelinkback(req, action, linkbackid, ln=CFG_SITE_LANG):
    """
    Moderate linkbacks
    @param linkbackId: linkback id
    @param action: of CFG_WEBLINKBACK_ADMIN_MODERATION_ACTION
    """
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = get_navtrail()
    navtrail_previous_links += ' &gt; <a class="navtrail" href="%s/admin/weblinkback/weblinkbackadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebLinkback Admin") + '</a>'

    user_info = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(user_info, 'cfgweblinkback')
    if auth_code:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
    else:
        return_code = perform_moderate_linkback(req=req,
                                                linkbackid=linkbackid,
                                                action=action)
        return linkbacks(req=req,
                         status=CFG_WEBLINKBACK_STATUS['PENDING'],
                         returncode=return_code,
                         ln=ln)
Beispiel #18
0
def linkbacks(req,
              status,
              returncode=CFG_WEBLINKBACK_ACTION_RETURN_CODE['OK'],
              ln=CFG_SITE_LANG):
    """
    Display linkbacks
    @param ln: language
    @param status: of CFG_WEBLINKBACK_STATUS, currently only CFG_WEBLINKBACK_STATUS['PENDING'] is supported
    """
    return_code = int(returncode)
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = get_navtrail()
    navtrail_previous_links += ' &gt; <a class="navtrail" href="%s/admin/weblinkback/weblinkbackadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebLinkback Admin") + '</a>'

    uid = getUid(req)
    user_info = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(user_info, 'cfgweblinkback')
    if auth_code:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
    else:
        return page(title=_("Pending Linkbacks"),
                    body=perform_request_display_linkbacks(
                        return_code=return_code, status=status, ln=ln),
                    uid=uid,
                    language=ln,
                    navtrail=navtrail_previous_links,
                    req=req)
Beispiel #19
0
 def new_ticket(self, req, form):
     """handle a edit/new_ticket request"""
     argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG), 'recid': (int, 0)})
     ln = argd['ln']
     _ = gettext_set_language(ln)
     auth_code, auth_message = acc_authorize_action(req, 'runbibedit')
     if auth_code != 0:
         return page_not_authorized(req=req, referer="/edit",
                                    text=auth_message, navtrail=navtrail)
     uid = current_user.get_id()
     if argd['recid']:
         (errmsg, url) = perform_request_newticket(argd['recid'], uid)
         if errmsg:
             return page(title       = _("Failed to create a ticket"),
                         body        = _("Error")+": "+errmsg,
                         errors      = [],
                         warnings    = [],
                         uid         = uid,
                         language    = ln,
                         navtrail    = navtrail,
                         lastupdated = __lastupdated__,
                         req         = req,
                         body_css_classes = ['bibedit'])
         else:
             #redirect..
             redirect_to_url(req, url)
Beispiel #20
0
def format_element(bfo, remote_server_id, style, css_class, link_label="Push via Sword",):
    """
    Print link to push an entry to a remote server through SWORD

    @param remote_server_id: ID of the remove server to link to. When
                             not specified, link to BibSword page
                             allowing to select server.
    """
    CFG_SITE_URL = current_app.config['CFG_SITE_URL']

    user_info = bfo.user_info
    auth_code, auth_message = acc_authorize_action(user_info, 'runbibswordclient')
    if auth_code != 0:
        return ""

    sword_arguments = {'ln': bfo.lang,
                       'recid': bfo.recID}

    if remote_server_id:
        sword_arguments['id_remote_server'] = remote_server_id
    else:
        sword_arguments['status'] = 'select_server'

    linkattrd = {}
    if style != '':
        linkattrd['style'] = style
    if css_class != '':
        linkattrd['class'] = css_class

    return create_html_link(CFG_SITE_URL + '/bibsword',
                            sword_arguments,
                            link_label,
                            linkattrd=linkattrd)
Beispiel #21
0
def format_element(bfo, style, css_class):
    """
    Prints a link to simple file management interface (BibDocFile), if
    authorization is granted.

    @param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    (auth_code, auth_message) = acc_authorize_action(user_info,
                                                     'runbibdocfile')
    if auth_code == 0:
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style
        if css_class != '':
            linkattrd['class'] = css_class
        out += create_html_link(
            current_app.config['CFG_SITE_SECURE_URL'] +
            '/%s/managedocfiles' % current_app.config['CFG_SITE_RECORD'],
            urlargd={
                'ln': bfo.lang,
                'recid': str(bfo.recID)
            },
            link_label="""<i class="icon-file"></i> %s""" % _("Manage Files"),
            linkattrd=linkattrd)
    return out
Beispiel #22
0
def linkbacks(req, status, returncode=CFG_WEBLINKBACK_ACTION_RETURN_CODE['OK'], ln=CFG_SITE_LANG):
    """
    Display linkbacks
    @param ln: language
    @param status: of CFG_WEBLINKBACK_STATUS, currently only CFG_WEBLINKBACK_STATUS['PENDING'] is supported
    """
    return_code = int(returncode)
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = get_navtrail()
    navtrail_previous_links +=' &gt; <a class="navtrail" href="%s/admin/weblinkback/weblinkbackadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebLinkback Admin") + '</a>'

    uid = getUid(req)
    user_info = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(user_info, 'cfgweblinkback')
    if auth_code:
        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
    else:
        return page(title=_("Pending Linkbacks"),
                    body=perform_request_display_linkbacks(return_code=return_code, status=status, ln=ln),
                    uid=uid,
                    language=ln,
                    navtrail = navtrail_previous_links,
                    req=req)
Beispiel #23
0
    def index(self, req, form):
        """ The function called by default"""

        argd = wash_urlargd(form, {
                                   self._JSON_DATA_KEY: (str, ""),
                                   })

        # load the right message language
        language = argd["ln"]
        _ = gettext_set_language(language)

        # check user credentials
        (auth_code, auth_msg) = acc_authorize_action(req, "runbibeditmulti")
        if 0 != auth_code:
            return page_not_authorized(req = req,
                                       ln = language,
                                       text = auth_msg)

        if argd[self._JSON_DATA_KEY]:
            return self._process_json_request(form, req)

        body = multi_edit_engine.perform_request_index(language)
        title = _("Multi-Record Editor")
        metaheaderadd = multi_edit_engine.get_scripts()
        metaheaderadd = metaheaderadd + multi_edit_engine.get_css()

        return page(title = title,
            metaheaderadd = metaheaderadd,
            body = body,
            req = req,
            language = language)
Beispiel #24
0
def format_element(bfo, style, css_class):
    """
    Prints a link to simple file management interface (BibDocFile), if
    authorization is granted.

    @param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    (auth_code, auth_message) = acc_authorize_action(user_info,
                                                     'runbibdocfile')
    if auth_code == 0:
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style
        if css_class != '':
            linkattrd['class'] = css_class
        out += create_html_link(current_app.config['CFG_SITE_URL'] + '/%s/managedocfiles' % current_app.config['CFG_SITE_RECORD'],
                         urlargd={'ln': bfo.lang,
                                  'recid': str(bfo.recID)},
                         link_label= """<i class="icon-file"></i> %s""" % _("Manage Files"),
                         linkattrd=linkattrd)
    return out
Beispiel #25
0
def hot(req, ln=CFG_SITE_LANG, comments=1, top=10, collection=""):
    """
    View most active comments/reviews
    @param req: request object to obtain user information
    @param ln: language
    @param comments: boolean enabled for comments, disabled for reviews
    @param top: number of results to be shown
    @param collection: filter results by collection
    """
    ln = wash_language(ln)
    collection = wash_url_argument(collection, 'str')
    _ = gettext_set_language(ln)
    navtrail_previous_links = getnavtrail()
    navtrail_previous_links += ' &gt; <a class="navtrail" href="%s/admin/webcomment/webcommentadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebComment Admin") + '</a>'

    user_info = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(user_info, 'cfgwebcomment')
    if auth_code:
        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
    return page(title=(comments=='0' and _("View most reviewed records") or
                           _("View most commented records")),
                    body=perform_request_hot(req, ln=ln, comments=comments, top=top, collection=collection),
                    uid=user_info['uid'],
                    language=ln,
                    navtrail = navtrail_previous_links,
                    lastupdated=__lastupdated__,
                    req=req)
Beispiel #26
0
    def decorated(*args, **kwargs):
        uid = current_user.get_id()
        name = name_getter()
        if name:
            g.collection = collection = Collection.query.filter(
                Collection.name == name).first_or_404()
        elif default_collection:
            g.collection = collection = Collection.query.get_or_404(1)
        else:
            return abort(404)

        if collection.is_restricted:
            from invenio.modules.access.engine import acc_authorize_action
            from invenio.modules.access.local_config import VIEWRESTRCOLL
            (auth_code,
             auth_msg) = acc_authorize_action(uid,
                                              VIEWRESTRCOLL,
                                              collection=collection.name)
            if auth_code:
                flash(_('This collection is restricted.'), 'error')
            if auth_code and current_user.is_guest:
                return redirect(
                    url_for('webaccount.login', referer=request.url))
            elif auth_code:
                return abort(401)

        return method(collection, *args, **kwargs)
Beispiel #27
0
    def check_authorization_moderatelinkbacks(self, req, argd):
        """
        Check if user has authorization moderate linkbacks
        @return if yes: nothing, if guest: login redirect, otherwise page_not_authorized
        """
        # Check authorization
        uid = getUid(req)
        user_info = collect_user_info(req)

        (auth_code, auth_msg) = acc_authorize_action(
            req,
            'moderatelinkbacks',
            collection=guess_primary_collection_of_a_record(self.recid))
        if auth_code and user_info['email'] == 'guest':
            # Ask to login
            target = CFG_SITE_SECURE_URL + '/youraccount/login' + \
                     make_canonical_urlargd({'ln': argd['ln'],
                                             'referer': CFG_SITE_URL + user_info['uri']}, {})
            return redirect_to_url(req, target)
        elif auth_code:
            return page_not_authorized(req,
                                       referer="../",
                                       uid=uid,
                                       text=auth_msg,
                                       ln=argd['ln'])
Beispiel #28
0
def format_element(bfo, style):
    """
    Prints a link to simple file management interface (BibDocFile), if
    authorization is granted.

    @param style: the CSS style to be applied to the link.
    """
    _ = gettext_set_language(bfo.lang)

    out = ""

    user_info = bfo.user_info
    (auth_code, auth_message) = acc_authorize_action(user_info,
                                                     'runbibdocfile')
    if auth_code == 0:
        linkattrd = {}
        if style != '':
            linkattrd['style'] = style

        out += create_html_link(CFG_BASE_URL + '/%s/managedocfiles' % CFG_SITE_RECORD,
                                urlargd={'ln': bfo.lang,
                                         'recid': str(bfo.recID)},
                                link_label=_("Manage Files of This Record"),
                                linkattrd=linkattrd)
    return out
Beispiel #29
0
def hot(req, ln=CFG_SITE_LANG, comments=1, top=10, collection=""):
    """
    View most active comments/reviews
    @param req: request object to obtain user information
    @param ln: language
    @param comments: boolean enabled for comments, disabled for reviews
    @param top: number of results to be shown
    @param collection: filter results by collection
    """
    ln = wash_language(ln)
    collection = wash_url_argument(collection, 'str')
    _ = gettext_set_language(ln)
    navtrail_previous_links = getnavtrail()
    navtrail_previous_links += ' &gt; <a class="navtrail" href="%s/admin/webcomment/webcommentadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebComment Admin") + '</a>'

    user_info = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(user_info, 'cfgwebcomment')
    if auth_code:
        return page_not_authorized(req=req,
                                   text=auth_msg,
                                   navtrail=navtrail_previous_links)
    return page(title=(comments == '0' and _("View most reviewed records")
                       or _("View most commented records")),
                body=perform_request_hot(req,
                                         ln=ln,
                                         comments=comments,
                                         top=top,
                                         collection=collection),
                uid=user_info['uid'],
                language=ln,
                navtrail=navtrail_previous_links,
                lastupdated=__lastupdated__,
                req=req)
Beispiel #30
0
def lists(req, urlfieldvalue='', returncode=CFG_WEBLINKBACK_ACTION_RETURN_CODE['OK'], ln=CFG_SITE_LANG):
    """
    Display whitelist and blacklist
    @param urlFieldValue: value of the url input field
    @return_code: might indicate errors from a previous action, of CFG_WEBLINKBACK_ACTION_RETURN_CODE
    @param ln: language
    """
    # is passed as a string, must be an integer
    return_code = int(returncode)
    ln = wash_language(ln)
    _ = gettext_set_language(ln)
    navtrail_previous_links = get_navtrail()
    navtrail_previous_links +=' &gt; <a class="navtrail" href="%s/admin/weblinkback/weblinkbackadmin.py/">' % CFG_SITE_URL
    navtrail_previous_links += _("WebLinkback Admin") + '</a>'

    uid = getUid(req)
    userInfo = collect_user_info(req)
    (auth_code, auth_msg) = acc_authorize_action(userInfo, 'cfgweblinkback')
    if auth_code:
        return page_not_authorized(req=req, text=auth_msg, navtrail=navtrail_previous_links)
    else:
        return page(title=_("Linkback Whitelist/Blacklist Manager"),
                    body=perform_request_display_list(return_code=return_code, url_field_value=urlfieldvalue, ln=ln),
                    uid=uid,
                    language=ln,
                    navtrail = navtrail_previous_links,
                    req=req)
Beispiel #31
0
    def decorated(*args, **kwargs):
        uid = current_user.get_id()
        name = name_getter()
        if name:
            g.collection = collection = Collection.query.filter(
                Collection.name == name).first_or_404()
        elif default_collection:
            g.collection = collection = Collection.query.get_or_404(1)
        else:
            return abort(404)

        if collection.is_restricted:
            from invenio.modules.access.engine import acc_authorize_action
            from invenio.modules.access.local_config import VIEWRESTRCOLL
            (auth_code, auth_msg) = acc_authorize_action(
                uid,
                VIEWRESTRCOLL,
                collection=collection.name
            )
            if auth_code:
                flash(_('This collection is restricted.'), 'error')
            if auth_code and current_user.is_guest:
                return redirect(url_for('webaccount.login',
                                        referer=request.url))
            elif auth_code:
                return abort(401)

        return method(collection, *args, **kwargs)
Beispiel #32
0
def Is_Referee(parameters, curdir, form, user_info=None):
    """
    This function checks whether the currently logged user is a
    referee for this document.
    """
    global uid_email, sysno, rn, uid
    doctype = form['doctype']
    # Get document category
    res = run_sql("SELECT categ FROM sbmAPPROVAL WHERE rn=%s", (rn, ))
    if len(res) > 0:
        categ = res[0][0]
        if categ == "unknown":
            ## FIXME: This was necessary for document types without categories,
            ## such as DEMOBOO:
            categ = "*"
    else:
        categ = ""
    # Try to retrieve the referee's email from the referee's database
    (auth_code, auth_message) = acc_authorize_action(user_info,
                                                     "referee",
                                                     doctype=doctype,
                                                     categ=categ)
    if auth_code != 0:
        raise InvenioWebSubmitFunctionStop("""
<SCRIPT>
        document.forms[0].action="/submit";
        document.forms[0].curpage.value = 1;
        document.forms[0].step.value = 0;
        user_must_confirm_before_leaving_page = false;
        alert('Sorry you (%s) have not been recognized as a referee for this type of document.\\nIf you think this is an error, please contact %s');
        document.forms[0].submit();
</SCRIPT>""" % (uid_email, CFG_SITE_SUPPORT_EMAIL))
    return ""
Beispiel #33
0
def administrate(req, journal_name, ln=CFG_SITE_LANG):
    """
    Shows the settings of a journal
    """
    navtrail_previous_links = wjn.getnavtrail(
        ' &gt; <a class="navtrail" href="%s/admin/webjournal/webjournaladmin.py">WebJournal Admin</a>'
        % CFG_SITE_URL)

    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    try:
        journal_name = wash_journal_name(ln, journal_name)
    except InvenioWebJournalNoJournalOnServerError as e:
        register_exception(req=req)
        return e.user_box()
    except InvenioWebJournalNoNameError as e:
        register_exception(req=req)
        return e.user_box()
    auth = acc_authorize_action(getUid(req),
                                'cfgwebjournal',
                                name="%s" % journal_name)
    if auth[0] == 0:
        as_editor = acc_authorize_action(getUid(req),
                                         'cfgwebjournal',
                                         name="%s" % journal_name,
                                         with_editor_rights='yes')[0] == 0

        return page(title=_('Administrate %(journal_name)s' %
                            {'journal_name': journal_name}),
                    body=wjn.perform_administrate(ln=ln,
                                                  journal_name=journal_name,
                                                  as_editor=as_editor),
                    uid=uid,
                    language=ln,
                    req=req,
                    navtrail=navtrail_previous_links,
                    lastupdated=__lastupdated__)
    else:
        return page_not_authorized(req=req,
                                   text=auth[1],
                                   navtrail=navtrail_previous_links)
Beispiel #34
0
def perform_request_comments(req=None, ln=CFG_SITE_LANG, uid="", comID="", recID="", reviews=0, abuse=False, collection=""):
    """
    Display the list of comments/reviews along with information about the comment.

    Display the comment given by its ID, or the list of comments for
    the given record ID.
    If abuse == True, only list records reported as abuse.
    If comID and recID are not provided, list all comments, or all
    abused comments (check parameter 'abuse')
    """
    ln = wash_language(ln)
    uid = wash_url_argument(uid, 'int')
    comID = wash_url_argument(comID, 'int')
    recID = wash_url_argument(recID, 'int')
    reviews = wash_url_argument(reviews, 'int')
    collection = wash_url_argument(collection, 'str')

    user_info = collect_user_info(req)
    user_collections = ['Show all']
    user_collections.extend(get_user_collections(req))
    if collection and collection != 'Show all':
        (auth_code, auth_msg) = acc_authorize_action(req, 'moderatecomments', collection=collection)
        if auth_code:
            return webcomment_templates.tmpl_admin_comments(ln=ln, uid=uid,
                                                            comID=comID,
                                                            recID=recID,
                                                            comment_data=None,
                                                            reviews=reviews,
                                                            error=1,
                                                            user_collections=user_collections,
                                                            collection=collection)
    if collection:
        if recID or uid:
            comments = query_get_comments(uid, comID, recID, reviews, ln, abuse=abuse, user_collections=user_collections, collection=collection)
        else:
            comments = query_get_comments('', comID, '', reviews, ln, abuse=abuse, user_collections=user_collections, collection=collection)
    else:
        if recID or uid:
            comments = query_get_comments(uid, comID, recID, reviews, ln, abuse=abuse, user_collections=user_collections, collection=user_collections[0])
        else:
            comments = query_get_comments('', comID, '', reviews, ln, abuse=abuse, user_collections=user_collections, collection=user_collections[0])
    if comments:
        return webcomment_templates.tmpl_admin_comments(ln=ln, uid=uid,
                                                        comID=comID,
                                                        recID=recID,
                                                        comment_data=comments,
                                                        reviews=reviews,
                                                        error=0,
                                                        user_collections=user_collections,
                                                        collection=collection)
    else:
        return webcomment_templates.tmpl_admin_comments(ln=ln, uid=uid,
                                                        comID=comID,
                                                        recID=recID,
                                                        comment_data=comments,
                                                        reviews=reviews,
                                                        error=2,
                                                        user_collections=user_collections,
                                                        collection=collection)
Beispiel #35
0
def check_user(req, role, authorized=0):
    """
    Checks if the user is authorized to access the admin area.
    """
    auth_code, auth_message = acc_authorize_action(req, role)
    if not authorized and auth_code != 0:
        return ("false", auth_message)
    return ("", auth_message)
Beispiel #36
0
def check_user(req, role, authorized=0):
    """
    Checks if the user is authorized to access the admin area.
    """
    auth_code, auth_message = acc_authorize_action(req, role)
    if not authorized and auth_code != 0:
        return ("false", auth_message)
    return ("", auth_message)
Beispiel #37
0
    def check_credential(self, req):
        '''
            This method check if the user has the right to get into this
            function
        '''

        auth_code, auth_message = acc_authorize_action(req, 'runbibswordclient')
        return (auth_code, auth_message)
Beispiel #38
0
    def check_credential(self, req):
        '''
            This method check if the user has the right to get into this
            function
        '''

        auth_code, auth_message = acc_authorize_action(req, 'runbibswordclient')
        return (auth_code, auth_message)
Beispiel #39
0
def get_authorized_deposition_types(user_info):
    """Return a list of allowed deposition types for a certain user."""
    from invenio.modules.access.engine import acc_authorize_action

    return {
        key for key in deposit_types.mapping().keys()
        if acc_authorize_action(user_info, usedeposit.name, type=key)[0] == 0
    }
Beispiel #40
0
    def edit(self, req, form):
        args = wash_urlargd(form, {"verbose" : (int, 0)})
        uid = webuser.getUid(req)

        # load the right message language
        _ = gettext_set_language(args['ln'])

        if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1:
            return webuser.page_not_authorized(req, "../youraccount/edit",
                                               navmenuid='youraccount')

        if webuser.isGuestUser(uid):
            return webuser.page_not_authorized(req, "../youraccount/edit",
                                               text=_("This functionality is forbidden to guest users."),
                                               navmenuid='youraccount')
        body = ''

        user_info = webuser.collect_user_info(req)
        if args['verbose'] == 9:
            keys = user_info.keys()
            keys.sort()
            for key in keys:
                body += "<b>%s</b>:%s<br />" % (key, user_info[key])

        # set CSRF token:
        csrf_token, dummy_csrf_token_time = webuser.regenerate_csrf_token_if_needed(req)

        #check if the user should see bibcatalog user name / passwd in the settings
        can_config_bibcatalog = (acc_authorize_action(user_info, 'runbibedit')[0] == 0)
        can_config_profiling = (acc_authorize_action(user_info, 'profiling')[0] == 0)
        return page(title= _("Your Settings"),
                    body=body+webaccount.perform_set(webuser.get_email(uid),
                                                     args['ln'],
                                                     can_config_bibcatalog,
                                                     can_config_profiling,
                                                     verbose=args['verbose'],
                                                     csrf_token=csrf_token),
                    navtrail="""<a class="navtrail" href="%s/youraccount/display?ln=%s">""" % (CFG_SITE_SECURE_URL, args['ln']) + _("Your Account") + """</a>""",
                    description=_("%(x_name)s Personalize, Your Settings", x_name=CFG_SITE_NAME_INTL.get(args['ln'], CFG_SITE_NAME)),
                    keywords=_("%(x_name)s, personalize", x_name=CFG_SITE_NAME_INTL.get(args['ln'], CFG_SITE_NAME)),
                    uid=uid,
                    req=req,
                    secure_page_p = 1,
                    language=args['ln'],
                    lastupdated='',
                    navmenuid='youraccount')
Beispiel #41
0
def index(req, ln=CFG_SITE_LANG, journal_name=None, action=""):
    """
    Main administration page.

    Lists the journals, and offers options to edit them, delete them
    or add new journals
    """
    navtrail_previous_links = wjn.getnavtrail()

    ln = wash_language(ln)
    _ = gettext_set_language(ln)

    try:
        uid = getUid(req)
    except:
        return error_page('Error', req)

    try:
        journal_name = wash_journal_name(ln, journal_name)
        action = wash_url_argument(action, 'str')
    except InvenioWebJournalNoJournalOnServerError as e:
        # Ok, no journal. Let the admin add one...
        pass
    except InvenioWebJournalNoNameError as e:
        register_exception(req=req)
        return e.user_box()
    if action in ['delete', 'askDelete']:
        # To perform these, one must be authorized
        auth = acc_authorize_action(getUid(req), 'cfgwebjournal',
                                    name=journal_name, with_editor_rights='yes')
    else:
        auth = acc_authorize_action(getUid(req), 'cfgwebjournal')
    if auth[0] == 0:
        return page(title=_('WebJournal Admin'),
                    body=wjn.perform_index(ln=ln,
                                           journal_name=journal_name,
                                           action=action,
                                           uid=getUid(req)),
                    uid=uid,
                    language=ln,
                    req=req,
                    navtrail = navtrail_previous_links,
                    lastupdated=__lastupdated__)
    else:
        return page_not_authorized(req=req, text=auth[1], navtrail=navtrail_previous_links)
Beispiel #42
0
def perform_index(ln=CFG_SITE_LANG, journal_name=None, action=None, uid=None):
    """
    Index page

    Lists the journals, and offers options to edit them, delete them
    or add new journal.

    Parameters:
        journal_name  -  the journal affected by action, if any
              action  -  one of ['', 'askDelete', _('Delete'), _('Cancel')]
                  ln  -  language
                 uid  -  user id
    """
    _ = gettext_set_language(ln)

    msg = None
    if action == 'askDelete' and journal_name is not None:
        msg = '''<fieldset style="display:inline;margin-left:auto;margin-right:auto;">
        <legend>Delete Journal Configuration</legend><span style="color:#f00">Are you sure you want to delete the configuration of %(journal_name)s?
        <form action="%(CFG_SITE_URL)s/admin/webjournal/webjournaladmin.py">
        <input type="hidden" name="journal_name" value="%(journal_name)s" />
        <input class="formbutton" type="submit" name="action" value="%(delete)s" />
        <input class="formbutton" type="submit" name="action" value="%(cancel)s" />
        </form></span></fieldset>''' % {'CFG_SITE_URL': CFG_SITE_URL,
                                        'journal_name': journal_name,
                                        'delete': _("Delete"),
                                        'cancel': _("Cancel")}

    if action == _("Delete") and journal_name is not None:
        # User confirmed and clicked on "Delete" button
        remove_journal(journal_name)

    journals = get_journals_ids_and_names()
    # Only keep journal that user can view or edit
    journals = [(journal_info, acc_authorize_action(uid,
                                                    'cfgwebjournal',
                                                    name=journal_info['journal_name'],
                                                    with_editor_rights='yes')[0] == 0) \
                 for journal_info in journals \
                 if acc_authorize_action(uid,
                                         'cfgwebjournal',
                                         name=journal_info['journal_name'])[0] == 0]
    return wjt.tmpl_admin_index(ln=ln,
                                journals=journals,
                                msg=msg)
Beispiel #43
0
def perform_index(ln=CFG_SITE_LANG, journal_name=None, action=None, uid=None):
    """
    Index page

    Lists the journals, and offers options to edit them, delete them
    or add new journal.

    Parameters:
        journal_name  -  the journal affected by action, if any
              action  -  one of ['', 'askDelete', _('Delete'), _('Cancel')]
                  ln  -  language
                 uid  -  user id
    """
    _ = gettext_set_language(ln)

    msg = None
    if action == 'askDelete' and journal_name is not None:
        msg = '''<fieldset style="display:inline;margin-left:auto;margin-right:auto;">
        <legend>Delete Journal Configuration</legend><span style="color:#f00">Are you sure you want to delete the configuration of %(journal_name)s?
        <form action="%(CFG_SITE_URL)s/admin/webjournal/webjournaladmin.py">
        <input type="hidden" name="journal_name" value="%(journal_name)s" />
        <input class="formbutton" type="submit" name="action" value="%(delete)s" />
        <input class="formbutton" type="submit" name="action" value="%(cancel)s" />
        </form></span></fieldset>''' % {'CFG_SITE_URL': CFG_SITE_URL,
                                        'journal_name': journal_name,
                                        'delete': _("Delete"),
                                        'cancel': _("Cancel")}

    if action == _("Delete") and journal_name is not None:
        # User confirmed and clicked on "Delete" button
        remove_journal(journal_name)

    journals = get_journals_ids_and_names()
    # Only keep journal that user can view or edit
    journals = [(journal_info, acc_authorize_action(uid,
                                                    'cfgwebjournal',
                                                    name=journal_info['journal_name'],
                                                    with_editor_rights='yes')[0] == 0) \
                 for journal_info in journals \
                 if acc_authorize_action(uid,
                                         'cfgwebjournal',
                                         name=journal_info['journal_name'])[0] == 0]
    return wjt.tmpl_admin_index(ln=ln,
                                journals=journals,
                                msg=msg)
Beispiel #44
0
    def manage(self, req, form):
        """ Web interface for the management of the info space """
        uid = getUid(req)
        argd = wash_urlargd(form, {'ln': (str, CFG_SITE_LANG)})

        # If it is an Ajax request, extract any JSON data.
        ajax_request = False
        if 'jsondata' in form:
            json_data = json.loads(str(form['jsondata']))
            json_data = json_unicode_to_utf8(json_data)
            ajax_request = True
            json_response = {}

        # Authorization.
        user_info = collect_user_info(req)
        if user_info['email'] == 'guest':
            # User is not logged in.
            if not ajax_request:
                # Do not display the introductory recID selection box to guest
                # users (as it used to be with v0.99.0):
                dummy_auth_code, auth_message = acc_authorize_action(
                    req, 'runinfomanager')
                referer = '/info'
                return page_not_authorized(req=req,
                                           referer=referer,
                                           text=auth_message)
            else:
                # Session has most likely timed out.
                json_response.update({'status': "timeout"})
                return json.dumps(json_response)
        # Handle request.
        if not ajax_request:
            body, errors, warnings = perform_request_init_info_interface()
            title = 'Info Space Manager'
            return page(title=title,
                        body=body,
                        errors=errors,
                        warnings=warnings,
                        uid=uid,
                        language=argd['ln'],
                        req=req)
        else:
            # Handle AJAX request.
            if json_data["action"] == "listFiles":
                json_response.update(
                    perform_request_edit_file(json_data["filename"]))
                try:
                    return json.dumps(json_response)
                except UnicodeDecodeError:
                    # Error decoding, the file can be a pdf, image or any kind
                    # of file non-editable
                    return json.dumps({"status": "error_file_not_readable"})

            if json_data["action"] == "saveContent":
                return json.dumps(
                    perform_request_save_file(json_data["filename"],
                                              json_data["filecontent"]))
Beispiel #45
0
def perform_request_latest(req=None,
                           ln=CFG_SITE_LANG,
                           comments=1,
                           top=10,
                           collection=""):
    """
    Display the list of latest comments/reviews along with information about the comment.

    @param req: request object for obtaining user information
    @param ln: language
    @param comments: boolean activated if using comments, deactivated for reviews
    @param top: Specify number of results to be shown
    @param collection: filter by collection
    """
    ln = wash_language(ln)
    comments = wash_url_argument(comments, 'int')
    top = wash_url_argument(top, 'int')
    collection = wash_url_argument(collection, 'str')

    user_info = collect_user_info(req)
    user_collections = ['Show all']
    user_collections.extend(get_user_collections(req))
    if collection and collection != 'Show all':
        (auth_code, auth_msg) = acc_authorize_action(req,
                                                     'moderatecomments',
                                                     collection=collection)
        if auth_code:
            return webcomment_templates.tmpl_admin_latest(
                ln=ln,
                comment_data=None,
                comments=comments,
                error=1,
                user_collections=user_collections,
                collection=collection)
    if collection:
        comments_retrieved = query_get_latest(comments, ln, top,
                                              user_collections, collection)
    else:
        comments_retrieved = query_get_latest(comments, ln, top,
                                              user_collections,
                                              user_collections[0])
    if comments_retrieved:
        return webcomment_templates.tmpl_admin_latest(
            ln=ln,
            comment_data=comments_retrieved,
            comments=comments,
            error=0,
            user_collections=user_collections,
            collection=collection)
    else:
        return webcomment_templates.tmpl_admin_latest(
            ln=ln,
            comment_data=comments_retrieved,
            comments=comments,
            error=2,
            user_collections=user_collections,
            collection=collection)
Beispiel #46
0
def restricted_collection(collection):
    from invenio.modules.access.engine import acc_authorize_action
    from invenio.modules.access.local_config import VIEWRESTRCOLL
    from flask_login import current_user
    if not collection.is_restricted:
        return False
    auth, _ = acc_authorize_action(current_user, VIEWRESTRCOLL,
                                   collection=collection.name)
    return auth != 0
Beispiel #47
0
def user_authorization(req, ln):
    """ Check user authorization to visit page """
    auth_code, auth_message = acc_authorize_action(req, 'runbatchuploader')
    if auth_code != 0:
        referer = '/batchuploader/'
        return page_not_authorized(req=req, referer=referer,
                                   text=auth_message, navmenuid="batchuploader")
    else:
        return None
Beispiel #48
0
def __isReferee(req, doctype="", categ="*"):
    (auth_code, auth_message) = acc_authorize_action(req,
                                                     "referee",
                                                     doctype=doctype,
                                                     categ=categ)
    if auth_code == 0:
        return 1
    else:
        return 0
Beispiel #49
0
def user_can_edit_record_collection(req, recid):
    """ Check if user has authorization to modify a collection
    the recid belongs to
    """

    def remove_volatile(field_value):
        """ Remove volatile keyword from field value """
        if field_value.startswith(VOLATILE_PREFIX):
            field_value = field_value[len(VOLATILE_PREFIX) :]
        return field_value

    # Get the collections the record belongs to
    record_collections = get_all_collections_of_a_record(recid)

    user_info = collect_user_info(req)
    uid = user_info["uid"]
    # In case we are creating a new record
    if cache_exists(recid, uid):
        record = get_cache_contents(recid, uid)[2]
        values = record_get_field_values(record, "980", code="a")
        record_collections.extend([remove_volatile(v) for v in values])

    normalized_collections = []
    for collection in record_collections:
        # Get the normalized collection name present in the action table
        res = run_sql(
            """SELECT value FROM "accARGUMENT"
                         WHERE keyword='collection'
                         AND value=%s;""",
            (collection,),
        )
        if res:
            normalized_collections.append(res[0][0])
    if not normalized_collections:
        # Check if user has access to all collections
        auth_code, dummy_message = acc_authorize_action(req, "runbibedit", collection="")
        if auth_code == 0:
            return True
    else:
        for collection in normalized_collections:
            auth_code, dummy_message = acc_authorize_action(req, "runbibedit", collection=collection)
            if auth_code == 0:
                return True
    return False
Beispiel #50
0
    def index(self, req, form):
        """ Display live BibSched queue
        """
        referer = '/admin2/bibsched/'
        navtrail = ' <a class="navtrail" href=\"%s/help/admin\">Admin Area</a> ' % CFG_SITE_URL

        auth_code, auth_message = acc_authorize_action(req, 'cfgbibsched')
        if auth_code != 0:
            return page_not_authorized(req=req, referer=referer,
                                       text=auth_message, navtrail=navtrail)

        bibsched_tasks = get_bibsched_tasks()
        header = ["ID", "Name", "Priority", "User", "Time", "Status",
                  "Progress"]
        map_status_css = {'WAITING': 'task_waiting', 'RUNNING': 'task_running',
                          'DONE WITH ERRORS': 'task_error'}
        bibsched_error = False
        motd_msg = get_motd_msg()
        actions = []
        body_content = ''
        if len(motd_msg) > 0:
            body_content += '<div class="clean_error">' + motd_msg + '</div><br />'
        if 'jsondata' not in form:
            body_content = '<div id="bibsched_table">'
        if bibsched_tasks:
            for task in bibsched_tasks:
                tskid, proc, priority, user, runtime, status, progress = task
                actions.append([tskid, proc, priority, user, runtime,
                               '<span class=%s>' % (status in map_status_css and
                                map_status_css[status] or '') + (status != "" and
                                status or '') + '</span>', (progress != "" and
                                progress or '')])
                if 'ERROR' in status:
                    bibsched_error = True
            body_content += tupletotable(header=header, tuple=actions,
                                         alternate_row_colors_p=True)
        if bibsched_error:
            body_content += '<br /><img src="%s"><span class="bibsched_status"> The queue contains errors</span><br />' % ("/img/aid_reject.png")
        else:
            body_content += '<br /><img src="%s"><span class="bibsched_status"> BibSched is working without errors</span><br />' % ("/img/aid_check.png")
        body_content += '<br /><span class="mode">Mode: %s</span>' % (get_bibsched_mode())
        body_content += '<br /><br /><span class="last_updated">Last updated: %s</span>' % \
                (time.strftime("%a %b %d, %Y  %-I:%M:%S %p",
                 time.localtime(time.time())))
        if 'jsondata' in form:
            json_response = {}
            json_response.update({'bibsched': body_content})
            return json.dumps(json_response)
        else:
            body_content += '</div>'
            return page(title="BibSched live view",
                        body=body_content,
                        errors=[],
                        warnings=[],
                        metaheaderadd=get_javascript() + get_css(),
                        req=req)
Beispiel #51
0
 def allows(self, identity):
     from invenio.modules.access.engine import acc_authorize_action
     auth, message = acc_authorize_action(
         identity.id, self.action, **dict(
             (k, v() if callable(v) else v)
             for (k, v) in iteritems(self.params)))
     if auth == 0:
         return True
     current_app.logger.info(message)
     return False
Beispiel #52
0
    def _authorize_user(obj, dummy_eng):
        from invenio.modules.access.engine import acc_authorize_action

        auth, message = acc_authorize_action(
            current_user.get_id(),
            action,
            **dict((k, v() if callable(v) else v)
                   for (k, v) in params.items()))
        if auth != 0:
            current_app.logger.info(message)
            abort(401)