def acc_authorize_action(req, name_action, authorized_if_no_roles=False, batch_args=False, **arguments): """ Given the request object (or the user_info dictionary, or the uid), checks if the user is allowed to run name_action with the given parameters. If authorized_if_no_roles is True and no role exists (different than superadmin) that are authorized to execute the given action, the authorization will be granted. Returns (0, msg) when the authorization is granted, (1, msg) when it's not. """ from invenio.ext.login import UserInfo from werkzeug.local import LocalProxy if isinstance(req, LocalProxy): req = req._get_current_object() if isinstance(req, UserInfo): user_info = req uid = user_info.get_id() elif type(req) is dict: uid = req.get('uid', None) user_info = req elif type(req) not in [int, long]: uid = current_user.get_id() user_info = collect_user_info(uid) # FIXME else: user_info = collect_user_info(req) roles_list = acc_find_possible_roles(name_action, always_add_superadmin=True, batch_args=batch_args, **arguments) if not batch_args: roles_list = [roles_list] result = [] for roles in roles_list: if acc_is_user_in_any_role(user_info, roles): ## User belong to at least one authorized role ## or User is SUPERADMIN ret_val = (0, CFG_WEBACCESS_WARNING_MSGS[0]) elif len(roles) <= 1: ## No role is authorized for the given action/arguments if authorized_if_no_roles: ## User is authorized because no authorization exists for the given ## action/arguments ret_val = (0, CFG_WEBACCESS_WARNING_MSGS[0]) else: ## User is not authorized. ret_val = (20, CFG_WEBACCESS_WARNING_MSGS[20] % cgi.escape(name_action)) else: ## User is not authorized in_a_web_request_p = bool(user_info.get('uri', '')) ret_val = (1, "%s %s" % (CFG_WEBACCESS_WARNING_MSGS[1], (in_a_web_request_p and "%s %s" % (CFG_WEBACCESS_MSGS[0] % quote(user_info.get('uri', '')), CFG_WEBACCESS_MSGS[1]) or ""))) result.append(ret_val) # FIXME removed CERN specific hack! return result if batch_args else result[0]
def perform_moderate_linkback(req, linkbackid, action): """ Moderate linkbacks @param linkbackid: linkback id @param action: of CFG_WEBLINKBACK_ADMIN_MODERATION_ACTION @return CFG_WEBLINKBACK_ACTION_RETURN_CODE """ if action == CFG_WEBLINKBACK_ADMIN_MODERATION_ACTION['APPROVE']: approve_linkback(linkbackid, collect_user_info(req)) elif action == CFG_WEBLINKBACK_ADMIN_MODERATION_ACTION['REJECT']: reject_linkback(linkbackid, collect_user_info(req)) else: return CFG_WEBLINKBACK_ACTION_RETURN_CODE['INVALID_ACTION'] return CFG_WEBLINKBACK_ACTION_RETURN_CODE['OK']
def is_external_user(uid): ''' Check for SSO user and if external claims will affect the decision wether or not the user may use the Invenio claiming platform @param uid: the user ID to check permissions for @type uid: int @return: is user allowed to perform actions? @rtype: boolean ''' #If no EXTERNAL_CLAIMED_RECORDS_KEY we bypass this check if not bconfig.EXTERNAL_CLAIMED_RECORDS_KEY: return False uinfo = collect_user_info(uid) keys = [] for k in bconfig.EXTERNAL_CLAIMED_RECORDS_KEY: if k in uinfo: keys.append(k) full_key = False for k in keys: if uinfo[k]: full_key = True break return full_key
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 += ' > <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)
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 += ' > <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)
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 += ' > <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)
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 += ' > <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)
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 += ' > <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)
def unsubscribe(self, req, form): """ Unsubscribe current user from current discussion. """ argd = wash_urlargd(form, {"referer": (str, None)}) user_info = collect_user_info(req) uid = getUid(req) if isGuestUser(uid): 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 + user_info["uri"]}, {} ) ) return redirect_to_url(req, target, norobot=True) success = unsubscribe_user_from_discussion(self.recid, uid) display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % ( CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, str(-success), argd["ln"], ) redirect_to_url(req, display_url)
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 +=' > <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)
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'])
def display(self, req, form): """ Display approved latest added linkbacks of the invenio instance """ argd = wash_urlargd(form, {'rg': (int, CFG_WEBLINKBACK_LATEST_COUNT_DEFAULT)}) # count must be positive if argd['rg'] < 0: argd['rg'] = -argd['rg'] _ = gettext_set_language(argd['ln']) user_info = collect_user_info(req) body = perform_request_display_approved_latest_added_linkbacks_to_accessible_records(argd['rg'], argd['ln'], user_info, weblinkback_templates=weblinkback_templates) navtrail = 'Recent Linkbacks' mathjaxheader, jqueryheader = weblinkback_templates.tmpl_get_mathjaxheader_jqueryheader() return pageheaderonly(title=navtrail, navtrail=navtrail, verbose=1, metaheaderadd = mathjaxheader + jqueryheader, req=req, language=argd['ln'], navmenuid='search', navtrail_append_title_p=0) + \ websearch_templates.tmpl_search_pagestart(argd['ln']) + \ body + \ websearch_templates.tmpl_search_pageend(argd['ln']) + \ pagefooteronly(language=argd['ln'], req=req)
def subscribe(self, req, form): """ Subscribe current user to receive email notification when new comments are added to current discussion. """ argd = wash_urlargd(form, {'referer': (str, None)}) uid = getUid(req) user_info = collect_user_info(req) (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid) if isGuestUser(uid): 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 + user_info['uri']}, {}) return redirect_to_url(req, target, norobot=True) elif auth_code: return page_not_authorized(req, "../", \ text = auth_msg) success = subscribe_user_to_discussion(self.recid, uid) display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % \ (CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, str(success), argd['ln']) redirect_to_url(req, display_url)
def goto_handler(req, form): ## Let's put what is in the GET query for key, value in dict(form).items(): if key in params_to_pass: params_to_pass[key] = str(value) ## Let's override the params_to_pass to the call with the ## arguments in the configuration configuration_parameters = redirection_data['parameters'] or {} params_to_pass.update(configuration_parameters) ## Let's add default parameters if the plugin expects them if 'component' in params_to_pass: params_to_pass['component'] = component if 'path' in params_to_pass: params_to_pass['path'] = path if 'user_info' in params_to_pass: params_to_pass['user_info'] = collect_user_info(req) if 'req' in params_to_pass: params_to_pass['req'] = req try: new_url = goto_plugin(**params_to_pass) except Exception as err: register_exception(req=req, alert_admin=True) raise SERVER_RETURN(HTTP_NOT_FOUND) if new_url: if new_url.startswith('/'): new_url = CFG_SITE_URL + new_url redirect_to_url(req, new_url) else: raise SERVER_RETURN(HTTP_NOT_FOUND)
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 += ' > <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)
def _upload_file_with_bibupload(file_path, upload_mode, num_records, req): """ Uploads file with bibupload @param file_path: path to the file where the XML will be saved. @param upload_mode: -c for correct or -r for replace @return tuple formed by status of the upload: 0-changes to be made instantly 1-changes to be made only in limited hours 2-user is superadmin. Changes made in limited hours 3-no rights to upload and the upload file path """ if num_records < CFG_BIBEDITMULTI_LIMIT_INSTANT_PROCESSING: task_low_level_submission('bibupload', 'multiedit', '-P', '5', upload_mode, '%s' % file_path) return (0, file_path) elif num_records < CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING: task_low_level_submission('bibupload', 'multiedit', '-P', '5', upload_mode, '-L', CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING_TIME,'%s' % file_path) return (1, file_path) else: user_info = collect_user_info(req) if isUserSuperAdmin(user_info): task_low_level_submission('bibupload', 'multiedit', '-P', '5', upload_mode, '-L', CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING_TIME, '%s' % file_path) return (2, file_path) return (3, file_path)
def check_login(req): """Check that the user is logged in""" user_info = collect_user_info(req) if user_info['email'] == 'guest': # 1. User is guest: must login prior to upload # return 'Please login before uploading file.' pass
def getattachedfile(self, req, form): """ Returns a file uploaded to the submission 'drop box' by the CKEditor. """ argd = wash_urlargd(form, { 'file': (str, None), 'type': (str, None), 'uid': (int, 0) }) # Can user view this record, i.e. can user access its # attachments? uid = getUid(req) user_info = collect_user_info(req) if not argd['file'] is None: # Prepare path to file on disk. Normalize the path so that # ../ and other dangerous components are removed. path = os.path.abspath(CFG_PREFIX + '/var/tmp/attachfile/' + \ '/' + str(argd['uid']) + \ '/' + argd['type'] + '/' + argd['file']) # Check that we are really accessing attachements # directory, for the declared record. if path.startswith(CFG_PREFIX + '/var/tmp/attachfile/' ) and os.path.exists(path): return stream_file(req, path) # Send error 404 in all other cases return (apache.HTTP_NOT_FOUND)
def getattachedfile(self, req, form): """ Returns a file uploaded to the submission 'drop box' by the CKEditor. """ argd = wash_urlargd(form, {'file': (str, None), 'type': (str, None), 'uid': (int, 0)}) # Can user view this record, i.e. can user access its # attachments? uid = getUid(req) user_info = collect_user_info(req) if not argd['file'] is None: # Prepare path to file on disk. Normalize the path so that # ../ and other dangerous components are removed. path = os.path.abspath(CFG_PREFIX + '/var/tmp/attachfile/' + \ '/' + str(argd['uid']) + \ '/' + argd['type'] + '/' + argd['file']) # Check that we are really accessing attachements # directory, for the declared record. if path.startswith(CFG_PREFIX + '/var/tmp/attachfile/') and os.path.exists(path): return stream_file(req, path) # Send error 404 in all other cases return(apache.HTTP_NOT_FOUND)
def subscribe(self, req, form): """ Subscribe current user to receive email notification when new comments are added to current discussion. """ argd = wash_urlargd(form, {"referer": (str, None)}) uid = getUid(req) user_info = collect_user_info(req) (auth_code, auth_msg) = check_user_can_view_comments(user_info, self.recid) if isGuestUser(uid): 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 + user_info["uri"]}, {} ) ) return redirect_to_url(req, target, norobot=True) elif auth_code: return page_not_authorized(req, "../", text=auth_msg) success = subscribe_user_to_discussion(self.recid, uid) display_url = "%s/%s/%s/comments/display?subscribed=%s&ln=%s" % ( CFG_SITE_SECURE_URL, CFG_SITE_RECORD, self.recid, str(success), argd["ln"], ) redirect_to_url(req, display_url)
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 += ' > <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)
def perform_request_contact(req, ln, journal_name, verbose=0): """ Display contact information """ try: contact_page_template = get_journal_template('contact', journal_name, ln) except InvenioWebJournalTemplateNotFoundError as e: register_exception(req=req) return e.user_box(req) user_info = collect_user_info(req) temp_marc = '''<record> <controlfield tag="001">0</controlfield> </record>''' bfo = BibFormatObject(0, ln=ln, xml_record=temp_marc, user_info=user_info) bfo.req = req html = format_with_format_template(contact_page_template, bfo) return html
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 +=' > <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)
def write(self, req, form): """ write(): interface for message composing @param msg_reply_id: if this message is a reply to another, id of the other @param msg_to: if this message is not a reply, nickname of the user it must be delivered to. @param msg_to_group: name of group to send message to @param ln: language @return: the compose page """ argd = wash_urlargd(form, {'msg_reply_id': (int, 0), 'msg_to': (str, ""), 'msg_to_group': (str, ""), 'msg_subject' : (str, ""), 'msg_body' : (str, "")}) # Check if user is logged uid = getUid(req) _ = gettext_set_language(argd['ln']) if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "%s/yourmessages/write" % \ (CFG_SITE_URL,), navmenuid="yourmessages") elif uid == -1 or isGuestUser(uid): return redirect_to_url(req, "%s/youraccount/login%s" % ( CFG_SITE_SECURE_URL, make_canonical_urlargd({ 'referer' : "%s/yourmessages/write%s" % ( CFG_SITE_SECURE_URL, make_canonical_urlargd(argd, {})), "ln" : argd['ln']}, {}))) user_info = collect_user_info(req) if not user_info['precached_usemessages']: return page_not_authorized(req, "../", \ text = _("You are not authorized to use messages.")) # Request the composing page body = perform_request_write( uid=uid, msg_reply_id=argd['msg_reply_id'], msg_to=argd['msg_to'], msg_to_group=argd['msg_to_group'], msg_subject=argd['msg_subject'], msg_body=argd['msg_body'], ln=argd['ln']) title = _("Write a message") return page(title = title, body = body, navtrail = get_navtrail(argd['ln'], title), uid = uid, lastupdated = __lastupdated__, req = req, language = argd['ln'], navmenuid = "yourmessages", secure_page_p=1)
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)
def display(self, req, form): """Display search history page. A misnomer.""" argd = wash_urlargd(form, {'p': (str, "n") }) uid = getUid(req) # load the right language _ = gettext_set_language(argd['ln']) if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "%s/youralerts/display" % \ (CFG_SITE_SECURE_URL,), navmenuid="youralerts") elif uid == -1 or isGuestUser(uid): return redirect_to_url(req, "%s/youraccount/login%s" % ( CFG_SITE_SECURE_URL, make_canonical_urlargd({ 'referer' : "%s/youralerts/display%s" % ( CFG_SITE_SECURE_URL, make_canonical_urlargd(argd, {})), "ln" : argd['ln']}, {}))) user_info = collect_user_info(req) if not user_info['precached_usealerts']: return page_not_authorized(req, "../", \ text = _("You are not authorized to use alerts.")) if argd['p'] == 'y': _title = _("Popular Searches") else: _title = _("Your Searches") # register event in webstat if user_info['email']: user_str = "%s (%d)" % (user_info['email'], user_info['uid']) else: user_str = "" try: register_customevent("alerts", ["display", "", user_str]) except: register_exception(suffix="Do the webstat tables exists? Try with 'webstatadmin --load-config'") return page(title=_title, body=webalert.perform_display(argd['p'], uid, ln=argd['ln']), navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % { 'sitesecureurl' : CFG_SITE_SECURE_URL, 'ln': argd['ln'], 'account' : _("Your Account"), }, description=_("%(sitename)s Personalize, Display searches", sitename=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)), keywords=_("%(sitename)s, personalize", sitename=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)), uid=uid, language=argd['ln'], req=req, lastupdated=__lastupdated__, navmenuid='youralerts', secure_page_p=1)
def test_check_bibdoc_authorization(self): """bibdocfile - check_bibdoc_authorization function""" from invenio.legacy.bibdocfile.api import check_bibdoc_authorization from invenio.legacy.webuser import collect_user_info, get_uid_from_email jekyll = collect_user_info(get_uid_from_email('*****@*****.**')) self.assertEqual(check_bibdoc_authorization(jekyll, 'role:thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertEqual(check_bibdoc_authorization(jekyll, 'role: thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertEqual(check_bibdoc_authorization(jekyll, 'role: thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertEqual(check_bibdoc_authorization(jekyll, 'Role: thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertEqual(check_bibdoc_authorization(jekyll, 'email: [email protected]'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertEqual(check_bibdoc_authorization(jekyll, 'email: [email protected]'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) juliet = collect_user_info(get_uid_from_email('*****@*****.**')) self.assertEqual(check_bibdoc_authorization(juliet, 'restricted_picture'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertEqual(check_bibdoc_authorization(juliet, 'status: restricted_picture'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertNotEqual(check_bibdoc_authorization(juliet, 'restricted_video')[0], 0) self.assertNotEqual(check_bibdoc_authorization(juliet, 'status: restricted_video')[0], 0)
def _index(req, c, ln, doctype, act, startPg, access, mainmenu, fromdir, nextPg, nbPg, curpage, step, mode): auth_args = {} if doctype: auth_args['doctype'] = doctype if act: auth_args['act'] = act uid = getUid(req) if uid == -1 or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "direct", navmenuid='submit') if CFG_CERN_SITE: ## HACK BEGIN: this is a hack for CMS and ATLAS draft user_info = collect_user_info(req) if doctype == 'CMSPUB' and act == "" and 'cds-admin [CERN]' not in user_info['group'] and not user_info['email'].lower() == '*****@*****.**': if isGuestUser(uid): return redirect_to_url(req, "%s/youraccount/login%s" % ( CFG_SITE_SECURE_URL, make_canonical_urlargd({'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri, 'ln' : args['ln']}, {})) , norobot=True) if 'cms-publication-committee-chair [CERN]' not in user_info['group']: return page_not_authorized(req, "../submit", text="In order to access this submission interface you need to be member of the CMS Publication Committee Chair.", navmenuid='submit') elif doctype == 'ATLPUB' and 'cds-admin [CERN]' not in user_info['group'] and not user_info['email'].lower() == '*****@*****.**': if isGuestUser(uid): return redirect_to_url(req, "%s/youraccount/login%s" % ( CFG_SITE_SECURE_URL, make_canonical_urlargd({'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri, 'ln' : args['ln']}, {})) , norobot=True) if 'atlas-gen [CERN]' not in user_info['group']: return page_not_authorized(req, "../submit", text="In order to access this submission interface you need to be member of ATLAS.", navmenuid='submit') ## HACK END if doctype == "": catalogues_text, at_least_one_submission_authorized, submission_exists = makeCataloguesTable(req, ln=CFG_SITE_LANG) if not at_least_one_submission_authorized and submission_exists: if isGuestUser(uid): return redirect_to_url(req, "%s/youraccount/login%s" % ( CFG_SITE_SECURE_URL, make_canonical_urlargd({'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri, 'ln' : args['ln']}, {})) , norobot=True) else: return page_not_authorized(req, "../submit", uid=uid, navmenuid='submit') return home(req, catalogues_text, c, ln) elif act == "": return action(req, c, ln, doctype) elif int(step)==0: return interface(req, c, ln, doctype, act, startPg, access, mainmenu, fromdir, nextPg, nbPg, curpage) else: return endaction(req, c, ln, doctype, act, startPg, access, mainmenu, fromdir, nextPg, nbPg, curpage, step, mode)
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, " ")
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"]))
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)
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
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
def index(self, req, form): """Index page.""" argd = wash_urlargd(form, {'page': (int, 1), 'format': (str, "rc"), 'order_by': (str, "lcf"), 'per_page': (str, "all"), }) # TODO: support also "reviews", by adding new option to show/hide them if needed uid = getUid(req) # load the right language _ = gettext_set_language(argd['ln']) # Is site ready to accept comments? if not CFG_WEBCOMMENT_ALLOW_COMMENTS or CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "%s/yourcomments" % \ (CFG_SITE_SECURE_URL,), text="Comments are currently disabled on this site", navmenuid="yourcomments") elif uid == -1 or isGuestUser(uid): return redirect_to_url(req, "%s/youraccount/login%s" % ( CFG_SITE_SECURE_URL, make_canonical_urlargd({ 'referer' : "%s/yourcomments%s" % ( CFG_SITE_SECURE_URL, make_canonical_urlargd(argd, {})), "ln" : argd['ln']}, {}))) user_info = collect_user_info(req) if not user_info['precached_sendcomments']: # Maybe we should still authorize if user submitted # comments in the past? return page_not_authorized(req, "../", \ text = _("You are not authorized to use comments.")) return page(title=_("Your Comments"), body=perform_display_your_comments(user_info, page_number=argd['page'], selected_order_by_option=argd['order_by'], selected_display_number_option=argd['per_page'], selected_display_format_option=argd['format'], ln=argd['ln']), navtrail= """<a class="navtrail" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(account)s</a>""" % { 'sitesecureurl' : CFG_SITE_SECURE_URL, 'ln': argd['ln'], 'account' : _("Your Account"), }, description=_("%(x_name)s View your previously submitted comments", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)), keywords=_("%(x_name)s, personalize", x_name=CFG_SITE_NAME_INTL.get(argd['ln'], CFG_SITE_NAME)), uid=uid, language=argd['ln'], req=req, lastupdated=__lastupdated__, navmenuid='youralerts', secure_page_p=1)
def is_no_quota_user(uid): """ Return True if the user belongs to any of the no_quota roles. """ no_quota_role_ids = [acc_get_role_id(role) for role in CFG_WEBMESSAGE_ROLES_WITHOUT_QUOTA] res = {} user_info = collect_user_info(uid) for role_id in no_quota_role_ids: if acc_is_user_in_role(user_info, role_id): return True return False
def get_user_document_uploads(req): """Retrieve all document upload history information for a given user""" user_info = collect_user_info(req) upload_list = run_sql("""SELECT DATE_FORMAT(h.submitdate, '%%Y-%%m-%%d %%H:%%i:%%S'), \ h.filename, DATE_FORMAT(h.execdate, '%%Y-%%m-%%d %%H:%%i:%%S'), \ s.status \ FROM hstBATCHUPLOAD h INNER JOIN schTASK s \ ON h.id_schTASK = s.id \ WHERE h.user=%s and h.batch_mode='document' ORDER BY h.submitdate DESC""", (user_info['nickname'],)) return upload_list
def perform_info(req, ln): """Display the main features of CDS personalize""" uid = getUid(req) user_info = collect_user_info(req) return websession_templates.tmpl_account_info( ln=ln, uid=uid, guest=int(user_info['guest']), CFG_CERN_SITE=CFG_CERN_SITE, )
def _get_user_id(self, req): """Return the identifier of the currently loged user. @param req: request as received from apache @return: identifier of currently logged user """ user_info = collect_user_info(req) user_id = user_info['uid'] return user_id
def perform_book_proposal_send(uid, recid, period_from, period_to, remarks, ln=CFG_SITE_LANG): """ The subfield containing the information about the source of importation of the record acts as the marker for the records put up for acquisition proposals. Register the user's book proposal, his period of interest and his remarks in the 'ILLREQUEST' table. Add a new 'dummy' copy for the proposed book. Create a loan(hold) request on behalf of the user for that copy and send a confirmation e-mail to her/him. """ _ = gettext_set_language(ln) user = collect_user_info(uid) if CFG_CERN_SITE: try: borrower = search_user('ccid', user['external_personid']) except: borrower = () else: borrower = search_user('email', user['email']) if borrower != (): if not db.has_copies(recid): tmp_barcode = generate_tmp_barcode() ill_register_request_with_recid(recid, uid, period_from, period_to, remarks, conditions='register_acquisition_suggestion', only_edition='False', barcode=tmp_barcode, ln=CFG_SITE_LANG) db.add_new_copy(tmp_barcode, recid, library_id=CFG_BIBCIRCULATION_DEFAULT_LIBRARY_ID, collection='', location='', description=_("This book was suggested for acquisition"), loan_period='', status=CFG_BIBCIRCULATION_ITEM_STATUS_UNDER_REVIEW, expected_arrival_date='') db.delete_brief_format_cache(recid) return perform_new_request_send_message(uid, recid, period_from, period_to, tmp_barcode, status=CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED, mail_subject='Acquisition Suggestion', mail_template='proposal_notification', mail_remarks=remarks, ln=CFG_SITE_LANG) return _("This item already has copies.") else: if CFG_CERN_SITE: message = bc_templates.tmpl_message_request_send_fail_cern("Borrower ID not found.") else: message = bc_templates.tmpl_message_request_send_fail_other("Borrower ID not found.") body = bc_templates.tmpl_new_request_send(message=message, ln=ln) return body
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"]))
def perform_info(req, ln): """Display the main features of CDS personalize""" uid = getUid(req) user_info = collect_user_info(req) return websession_templates.tmpl_account_info( ln = ln, uid = uid, guest = int(user_info['guest']), CFG_CERN_SITE = CFG_CERN_SITE, )
def perform_request_index(req, journal_name, issue_number, ln, category, editor=False, verbose=0): """ Central logic function for index pages. Brings together format templates and MARC rules from the config, with the requested index page, given by the url parameters. From config: - page template for index pages -> formatting - MARC rule list -> Category Navigation - MARC tag used for issue numbers -> search (later in the format elements) Uses BibFormatObject and format_with_format_template to produce the required HTML. """ current_issue = get_current_issue(ln, journal_name) if not get_release_datetime(issue_number, journal_name): # Unreleased issue. Display latest released issue? unreleased_issues_mode = get_unreleased_issue_hiding_mode(journal_name) if not editor and \ (unreleased_issues_mode == 'all' or \ (unreleased_issues_mode == 'future' and \ issue_is_later_than(issue_number, current_issue))): redirect_to_url(req, "%s/journal/%s/%s/%s?ln=%s" % \ (CFG_SITE_URL, journal_name, current_issue.split('/')[1], current_issue.split('/')[0], ln)) try: index_page_template = get_journal_template('index', journal_name, ln) except InvenioWebJournalTemplateNotFoundError as e: register_exception(req=req) return e.user_box(req) temp_marc = '''<record> <controlfield tag="001">0</controlfield> </record>''' # create a record and get HTML back from bibformat user_info = collect_user_info(req) bfo = BibFormatObject(0, ln=ln, xml_record=temp_marc, user_info=user_info) bfo.req = req verbosity = 0 if editor: # Increase verbosity only for editors/admins verbosity = verbose html = format_with_format_template(index_page_template, bfo, verbose=verbosity) return html
def reject(self, req, form): """ Reject a linkback """ argd = wash_urlargd(form, {'linkbackid': (int, -1)}) authorization = self.check_authorization_moderatelinkbacks(req, argd) if not authorization: reject_linkback(argd['linkbackid'], collect_user_info(req)) return self.display(req, form) else: return authorization
def get_user_collections(req): """ Return collections for which the user is moderator """ user_info = collect_user_info(req) res = [] collections = run_sql('SELECT name FROM collection') for collection in collections: collection_emails = acc_get_authorized_emails('moderatecomments', collection=collection[0]) if user_info['email'] in collection_emails or isUserAdmin(user_info): res.append(collection[0]) return res
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
def get_user_document_uploads(req): """Retrieve all document upload history information for a given user""" user_info = collect_user_info(req) upload_list = run_sql( """SELECT DATE_FORMAT(h.submitdate, '%%Y-%%m-%%d %%H:%%i:%%S'), \ h.filename, DATE_FORMAT(h.execdate, '%%Y-%%m-%%d %%H:%%i:%%S'), \ s.status \ FROM hstBATCHUPLOAD h INNER JOIN schTASK s \ ON h.id_schTASK = s.id \ WHERE h.user=%s and h.batch_mode='document' ORDER BY h.submitdate DESC""", (user_info['nickname'], )) return upload_list
def is_no_quota_user(uid): """ Return True if the user belongs to any of the no_quota roles. """ no_quota_role_ids = [ acc_get_role_id(role) for role in CFG_WEBMESSAGE_ROLES_WITHOUT_QUOTA ] res = {} user_info = collect_user_info(uid) for role_id in no_quota_role_ids: if acc_is_user_in_role(user_info, role_id): return True return False
def display_msg(self, req, form): """ Display a message @param msgid: id of message @param ln: languae @return: page """ argd = wash_urlargd(form, { 'msgid': (int, -1), }) # Check if user is logged uid = getUid(req) if CFG_ACCESS_CONTROL_LEVEL_SITE >= 1: return page_not_authorized(req, "%s/yourmessages/display_msg" % \ (CFG_SITE_URL,), navmenuid="yourmessages") elif uid == -1 or isGuestUser(uid): return redirect_to_url( req, "%s/youraccount/login%s" % (CFG_SITE_SECURE_URL, make_canonical_urlargd( { 'referer': "%s/yourmessages/display_msg%s" % (CFG_SITE_SECURE_URL, make_canonical_urlargd( argd, {})), "ln": argd['ln'] }, {}))) _ = gettext_set_language(argd['ln']) user_info = collect_user_info(req) if not user_info['precached_usemessages']: return page_not_authorized(req, "../", \ text = _("You are not authorized to use messages.")) # Generate content body = perform_request_display_msg(uid, argd['msgid'], argd['ln']) title = _("Read a message") return page(title=title, body=body, navtrail=get_navtrail(argd['ln'], title), uid=uid, lastupdated=__lastupdated__, req=req, language=argd['ln'], navmenuid="yourmessages", secure_page_p=1)
def test_check_bibdoc_authorization(self): """bibdocfile - check_bibdoc_authorization function""" from invenio.legacy.bibdocfile.api import check_bibdoc_authorization from invenio.legacy.webuser import collect_user_info, get_uid_from_email jekyll = collect_user_info(get_uid_from_email('*****@*****.**')) self.assertEqual( check_bibdoc_authorization(jekyll, 'role:thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertEqual( check_bibdoc_authorization(jekyll, 'role: thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertEqual( check_bibdoc_authorization(jekyll, 'role: thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertEqual( check_bibdoc_authorization(jekyll, 'Role: thesesviewer'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertEqual( check_bibdoc_authorization(jekyll, 'email: [email protected]'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertEqual( check_bibdoc_authorization(jekyll, 'email: [email protected]'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) juliet = collect_user_info( get_uid_from_email('*****@*****.**')) self.assertEqual( check_bibdoc_authorization(juliet, 'restricted_picture'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertEqual( check_bibdoc_authorization(juliet, 'status: restricted_picture'), (0, CFG_WEBACCESS_WARNING_MSGS[0])) self.assertNotEqual( check_bibdoc_authorization(juliet, 'restricted_video')[0], 0) self.assertNotEqual( check_bibdoc_authorization(juliet, 'status: restricted_video')[0], 0)