def acc_authorize_action(req, name_action, authorized_if_no_roles=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. """ user_info = collect_user_info(req) roles = acc_find_possible_roles(name_action, always_add_superadmin=False, **arguments) for id_role in roles: if acc_is_user_in_role(user_info, id_role): ## User belong to at least one authorized role. return (0, CFG_WEBACCESS_WARNING_MSGS[0]) if acc_is_user_in_role(user_info, CFG_SUPERADMINROLE_ID): ## User is SUPERADMIN return (0, CFG_WEBACCESS_WARNING_MSGS[0]) if not roles: ## 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 return (0, CFG_WEBACCESS_WARNING_MSGS[0]) else: ## User is not authorized. return (20, CFG_WEBACCESS_WARNING_MSGS[20] % cgi.escape(name_action)) ## User is not authorized in_a_web_request_p = bool(user_info['uri']) return (1, "%s %s" % (CFG_WEBACCESS_WARNING_MSGS[1], (in_a_web_request_p and "%s %s" % (CFG_WEBACCESS_MSGS[0] % quote(user_info['uri']), CFG_WEBACCESS_MSGS[1]) or "")))
def format_element(bfo, style): """ Offers action to delete a blog or a post @param style: the CSS style to be applied to the link. """ _ = gettext_set_language(bfo.lang) out = "" if bfo.user_info['email'] not in ["guest"]: coll = bfo.fields("980__a")[0] if coll in ['BLOG', 'BLOGPOST']: linkattrd = {} if style != '': linkattrd['style'] = style try: recid = bfo.control_field('001')[0] except: raise Exception("Record not found") if coll == 'BLOG': act = 'DBI' if acc_is_user_in_role(bfo.user_info, acc_get_role_id(SUPERADMINROLE)): doctype = 'BSI' sub = 'DBIBSI' else: doctype = 'BSIREF' sub = 'DBIBSIREF' elif coll == 'BLOGPOST': act = 'DPI' if acc_is_user_in_role(bfo.user_info, acc_get_role_id(SUPERADMINROLE)): doctype = 'BSI' sub = 'DPIBSI' else: doctype = 'BSIREF' sub = 'DPIBSIREF' out += create_html_link(CFG_SITE_URL + "/submit", {'ln': bfo.lang, 'doctype': doctype, 'indir': 'delete', 'act': act, 'sub': sub, 'BSI_RN': recid}, link_label = _("Ask for Deletion"), linkattrd = linkattrd) return out
def index(req): user_info = collect_user_info(req) if not acc_is_user_in_role(user_info, acc_get_role_id("SCOAP3")): return page_not_authorized(req=req) req.content_type = "text/html" req.write(pageheaderonly("Repository tools", req=req)) req.write("<h1>Repository tools</h1>") req.write("<h2>Compliance</h2>") req.write("<a href='/compliance.py'>Content compliance</a> - articles compliance with agreements<br />") req.write("<a href='/compliance.py/csv'>Content compliance to CSV</a> - articles compliance with agreements<br />") req.write("<a href='/nations.py/late'>24h deadline</a> - checks the 24h delivery deadline<br />") req.write("<h2>National statistics</h2>") req.write("<a href='/nations.py'>Countries impact</a> - number of pulications per country<br />") req.write("<a href='/nations.py/us_affiliations'>US affiliations</a> - all US affiliations<br />") req.write("<a href='/nations.py/us_affiliations_csv'>Selected US aff count CSV</a> - affiliation count for selected US universities<br />") req.write("<a href='/nations.py/usa_papers'>Selected US articles list</a><br />") req.write("<a href='/nations.py/usa_papers_csv'>Selected US articles list CSV</a><br />") req.write("<h2>Export to INSPIRE</h2>") req.write("<a href='/ffts_for_inspire.py'>Data export</a><br />") req.write("<a href='/ffts_for_inspire.py/csv'>Data export to CSV</a><br />") req.flush() req.write(pagefooteronly(req=req)) return ""
def isUserReferee(user_info): """Return True if the user is a referee for something; False otherwise.""" if CFG_CERN_SITE: return True else: for (role_id, role_name, role_description) in acc_get_action_roles(acc_get_action_id('referee')): if acc_is_user_in_role(user_info, role_id): return True return False
def isUserReferee(user_info): """Return True if the user is a referee for something; False otherwise.""" if CFG_CERN_SITE: return True else: for (role_id, role_name, role_description) in acc_get_action_roles( acc_get_action_id('referee')): if acc_is_user_in_role(user_info, role_id): return True return False
def acc_authorize_action(req, name_action, authorized_if_no_roles=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. """ user_info = collect_user_info(req) roles = acc_find_possible_roles(name_action, always_add_superadmin=False, **arguments) for id_role in roles: if acc_is_user_in_role(user_info, id_role): ## User belong to at least one authorized role. return (0, CFG_WEBACCESS_WARNING_MSGS[0]) if acc_is_user_in_role(user_info, CFG_SUPERADMINROLE_ID): ## User is SUPERADMIN return (0, CFG_WEBACCESS_WARNING_MSGS[0]) if not roles: ## 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 return (0, CFG_WEBACCESS_WARNING_MSGS[0]) else: ## User is not authorized. return (20, CFG_WEBACCESS_WARNING_MSGS[20] % cgi.escape(name_action)) ## User is not authorized in_a_web_request_p = bool(user_info['uri']) if CFG_CERN_SITE and arguments.has_key('collection'): # We apply the checks for all actions with that 'collection' # argument, for simplicity not necessity. from invenio.search_engine import get_collection_allchildren if arguments.get('collection', None) in get_collection_allchildren('e-Tendering', recreate_cache_if_needed=False): return (1, "%s %s" % (CFG_WEBACCESS_WARNING_MSGS[1], (in_a_web_request_p and "%s %s" % (CFG_WEBACCESS_MSGS[9] % ("*****@*****.**", "*****@*****.**"), CFG_WEBACCESS_MSGS[10] % (CFG_SITE_SECURE_URL + "/goto/etendering-faq", "Frequently Asked Questions (FAQ) concerning the CERN e-tendering application") ) or ""))) return (1, "%s %s" % (CFG_WEBACCESS_WARNING_MSGS[1], (in_a_web_request_p and "%s %s" % (CFG_WEBACCESS_MSGS[0] % quote(user_info['uri']), CFG_WEBACCESS_MSGS[1]) or "")))
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 show_restricted_records(req): user_info = collect_user_info(req) if not acc_is_user_in_role(user_info, acc_get_role_id("SCOAP3")): return page_not_authorized(req=req) all_ids = [id[0] for id in run_sql("Select id from bibrec")] visible_ids = perform_request_search() deleted_and_older_and_restricted = set(all_ids) - set(visible_ids) restricted_ids = [] # restricted_ids_older = [] for id in deleted_and_older_and_restricted: rec = get_record(id) collections = record_get_field_values(rec, "980","%","%","%") if "DELETED" not in collections: year = record_get_field_values(rec, "773","%","%","y") title = record_get_field_values(rec, "245","%","%","a") if title: title = title[0] else: title = "No title" if year: if int(year[0]) >= 2015: restricted_ids.append((id, title)) # else: # restricted_ids_older.append(id) else: restricted_ids.append((id,title)) print "Restricted ids" print restricted_ids req.content_type = "text/html" req.write(pageheaderonly("Repository tools", req=req)) req.write("<h1>Restricted records</h1>") req.write("<strong>Total number of possibli restricted records: {0}</strong>".format(len(restricted_ids))) req.write("<ol>") for id, title in restricted_ids: req.write("<li><a href='http://repo.scoap3.org/record/{1}'>{0}</a> <a href='http://repo.scoap3.org/record/edit/?ln=en#state=edit&recid={1}'>edit</a></li>".format(title, id)) req.write("</ol>") # for id, title in restricted_ids: # req.write("{0},".format(id)) req.write(pagefooteronly(req=req)) return ""
def index(req): user_info = collect_user_info(req) if not acc_is_user_in_role(user_info, acc_get_role_id("SCOAP3")): return page_not_authorized(req=req) req.content_type = "text/html" req.write(pageheaderonly("Repository tools & extra resources", req=req)) req.write("<h1>Repository tools</h1>") req.write("<h2>Compliance</h2>") req.write("<a href='/compliance.py'>Content compliance</a> - articles compliance with agreements<br />") req.write("<a href='/compliance.py/csv'>Content compliance to CSV</a> - articles compliance with agreements<br />") req.write("<a href='/nations.py/late'>24h deadline</a> - checks the 24h delivery deadline (OBSOLETE)<br />") req.write("<h2>National statistics</h2>") req.write("<a href='/nations.py'>Countries impact</a> - number of pulications per country<br />") req.write("<a href='/nations.py/us_affiliations'>US affiliations</a> - all US affiliations<br />") req.write("<a href='/nations.py/us_affiliations_csv'>Selected US aff count CSV</a> - affiliation count for selected US universities<br />") req.write("<a href='/nations.py/usa_papers'>Selected US articles list</a><br />") req.write("<a href='/nations.py/usa_papers_csv'>Selected US articles list CSV</a><br />") req.write("<a href='/nations.py/papers_by_country_csv?country=xxx'>CSV list of articles by country</a> - you need to change argument 'country=xxx' to a country from the list bellow<br />") req.write("<textarea>Algeria, Argentina, Armenia, Australia, Austria, Azerbaijan, Belarus, Belgium, Bangladesh, Brazil, Bulgaria, Canada, CERN, Chile, China, Colombia, Costa Rica, Cuba, Croatia, Cyprus, Czech Republic, Denmark, Egypt, Estonia, Finland, France, Georgia, Germany, Greece, Hong Kong, Hungary, Iceland, India, Indonesia, Iran, Ireland, Israel, Italy, Japan, South Korea, Lebanon, Lithuania, Luxembourg, Mexico, Montenegro, Morocco, Niger, Netherlands, New Zealand, Norway, Pakistan, Poland, Portugal, Romania, Republic of San Marino, Russia, Saudi Arabia, Serbia, Singapore, Slovakia, South Africa, Spain, Sweden, Switzerland, Taiwan, Thailand, Tunisia, Turkey, Ukraine, UK, USA, Uruguay, Uzbekistan, Venezuela, Vietnam, Yemen, Peru, Kuwait, Sri Lanka, Kazakhstan, Mongolia, United Arab Emirates, United Arab Emirates, Malaysia, Qatar, Kyrgyz Republic, Jordan</textarea>") req.write("<a href='https://repo.scoap3.org/nations.py/countries_by_publishers'>Countries per journals</a>") req.write("<h2>Articles for impact calculations</h2>") req.write("<a href='/nations.py/impact_articles?year=2014'>Countries impact for 2014</a><br />") req.write("<a href='https://gist.github.com/Dziolas/7924d2feb2b3e5b0618a'>Code to run on Inspire server to get articles for impact calculation</a><br />") req.write("<h2>Export to INSPIRE</h2>") req.write("<a href='/ffts_for_inspire.py'>Data export</a><br />") req.write("<a href='/ffts_for_inspire.py/csv'>Data export to CSV</a><br />") req.write("<h1>Hidden collections</h1>") req.write("<a href='/collection/Erratum'>Erratas</a><br />") req.write("<a href='/collection/Addendum'>Addendums</a><br />") req.write("<a href='/collection/Corrigendum'>Corrigendums</a><br />") req.write("<a href='/collection/Editorial'>Editorials</a><br />") req.write("<a href='/collection/older_than_2014'>Articles older than 2014</a><br />") req.flush() req.write(pagefooteronly(req=req)) return ""
def check_quota(nb_messages): """ @param nb_messages: max number of messages a user can have @return: a dictionary of users over-quota """ from invenio.webuser import collect_user_info from invenio.access_control_admin import acc_is_user_in_role, acc_get_role_id no_quota_role_ids = [ acc_get_role_id(role) for role in CFG_WEBMESSAGE_ROLES_WITHOUT_QUOTA ] res = {} for uid, n in run_sql( "SELECT id_user_to, COUNT(id_user_to) FROM user_msgMESSAGE GROUP BY id_user_to HAVING COUNT(id_user_to) > %s", (nb_messages, )): user_info = collect_user_info(uid) for role_id in no_quota_role_ids: if acc_is_user_in_role(user_info, role_id): break else: res[uid] = n return res
def json(req): """ Returns all BAI information in a JSON friendly way. """ import json from invenio.dbquery import run_sql from invenio.webuser import collect_user_info from invenio.access_control_admin import acc_is_user_in_role, acc_get_role_id if not acc_is_user_in_role(collect_user_info(req), acc_get_role_id('cernintranet')): from invenio.webinterface_handler_config import HTTP_FORBIDDEN req.status = HTTP_FORBIDDEN return "" bais = run_sql( "SELECT personid, tag, data FROM aidPERSONIDDATA WHERE tag in ('canonical_name', 'extid:INSPIREID', 'extid:ORCID', 'uid') ORDER BY personid" ) emails = dict(run_sql("SELECT id, email FROM user")) req.content_type = 'application/json' old_personid = None authors = {} person = {} canonical_name = "" for personid, tag, data in bais: if personid != old_personid: if not person and canonical_name in authors: # We can delete this person del authors[canonical_name] person = {} old_personid = personid if tag == 'canonical_name': authors[data] = person canonical_name = data elif tag == 'uid' and int(data) in emails: person['email'] = emails[int(data)] elif tag == 'extid:INSPIREID': person['INSPIREID'] = data elif tag == 'extid:ORCID': person['ORCID'] = data json.dump(authors, req) return ""
def json(req): """ Returns all BAI information in a JSON friendly way. """ import json from invenio.dbquery import run_sql from invenio.webuser import collect_user_info from invenio.access_control_admin import acc_is_user_in_role, acc_get_role_id if not acc_is_user_in_role(collect_user_info(req), acc_get_role_id('cernintranet')): from invenio.webinterface_handler_config import HTTP_FORBIDDEN req.status = HTTP_FORBIDDEN return "" bais = run_sql("SELECT personid, tag, data FROM aidPERSONIDDATA WHERE tag in ('canonical_name', 'extid:INSPIREID', 'extid:ORCID', 'uid') ORDER BY personid") emails = dict(run_sql("SELECT id, email FROM user")) req.content_type = 'application/json' old_personid = None authors = {} person = {} canonical_name = "" for personid, tag, data in bais: if personid != old_personid: if not person and canonical_name in authors: # We can delete this person del authors[canonical_name] person = {} old_personid = personid if tag == 'canonical_name': authors[data] = person canonical_name = data elif tag == 'uid' and int(data) in emails: person['email'] = emails[int(data)] elif tag == 'extid:INSPIREID': person['INSPIREID'] = data elif tag == 'extid:ORCID': person['ORCID'] = data json.dump(authors, req) return ""
def tmpl_pagefooter(self, req=None, ln=CFG_SITE_LANG, lastupdated=None, pagefooteradd=""): """Creates a page footer Parameters: - 'ln' *string* - The language to display - 'lastupdated' *string* - when the page was last updated - 'pagefooteradd' *string* - additional page footer HTML code Output: - HTML code of the page headers """ # load the right message language _ = gettext_set_language(ln) if lastupdated and lastupdated != '$Date$': if lastupdated.startswith("$Date: ") or \ lastupdated.startswith("$Id: "): lastupdated = convert_datestruct_to_dategui(\ convert_datecvs_to_datestruct(lastupdated), ln=ln) msg_lastupdated = _("Last updated") + ": " + lastupdated else: msg_lastupdated = "" user_info = collect_user_info(req) if acc_is_user_in_role(user_info, acc_get_role_id("SCOAP3")): tools = "<a href='/tools.py'>Repository tools</a>" else: tools = "" out = """ <div class="pagefooter"> %(pagefooteradd)s <!-- replaced page footer --> <div class="pagefooterstripeleft"> <!-- %(sitename)s :: <a class="footer" href="%(siteurl)s/?ln=%(ln)s">%(msg_search)s</a> :: <a class="footer" href="%(siteurl)s/submit?ln=%(ln)s">%(msg_submit)s</a> :: <a class="footer" href="%(sitesecureurl)s/youraccount/display?ln=%(ln)s">%(msg_personalize)s</a> :: <a class="footer" href="%(siteurl)s/help/%(langlink)s">%(msg_help)s</a> <br />--> %(msg_poweredby)s <a class="footer" href="http://invenio-software.org/">Invenio</a> v%(version)s <br /> %(msg_maintainedby)s <a class="footer" href="mailto:%(sitesupportemail)s">%(sitesupportemail)s</a> <br /> %(msg_lastupdated)s <br /> %(tools)s </div> <div class="pagefooterstriperight"> <p><em> Articles in the SCOAP3 repository are released under a <a target="_blank" rel="license" href="http://creativecommons.org/licenses/by/3.0/"><strong>CC-BY</strong></a> license. Metadata are provided by the corresponding publishers and released under the <a target="_blank" rel="license" href="http://creativecommons.org/publicdomain/zero/1.0/"> <strong>CC0</strong> </a> waiver. </em></p> %(languagebox)s </div> <!-- replaced page footer --> </div> <!-- Piwik --> <script type="text/javascript"> var _paq = _paq || []; _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="//piwik.inspirehep.net/"; _paq.push(['setTrackerUrl', u+'piwik.php']); _paq.push(['setSiteId', 10]); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s); })(); </script> <noscript><p><img src="//piwik.inspirehep.net/piwik.php?idsite=10" style="border:0;" alt="" /></p></noscript> <!-- End Piwik Code --> </body> </html> """ % { 'siteurl': CFG_BASE_URL, 'sitesecureurl': CFG_SITE_SECURE_URL, 'ln': ln, 'langlink': '?ln=' + ln, 'sitename': CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME), 'sitesupportemail': CFG_SITE_SUPPORT_EMAIL, 'msg_search': _("Search"), 'msg_submit': _("Submit"), 'msg_personalize': _("Personalize"), 'msg_help': _("Help"), 'msg_poweredby': _("Powered by"), 'msg_maintainedby': _("Maintained by"), 'msg_lastupdated': msg_lastupdated, 'languagebox': self.tmpl_language_selection_box(req, ln), 'version': CFG_VERSION, 'pagefooteradd': pagefooteradd, 'tools': tools, } return out
user_info['session'] = get_session(req).sid() user_info['remote_host'] = req.remote_host or '' user_info['referer'] = req.headers_in.get('Referer', '') user_info['uri'] = req.unparsed_uri or () user_info['agent'] = req.headers_in.get('User-Agent', 'N/A') user_info['uid'] = uid user_info['nickname'] = get_nickname(uid) or '' user_info['email'] = get_email(uid) or '' user_info['group'] = [] user_info['guest'] = str(isGuestUser(uid)) if user_info['guest'] == '1' and CFG_INSPIRE_SITE: usepaperattribution = False viewclaimlink = False if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role( user_info, acc_get_role_id("paperattributionviewers"))): usepaperattribution = True # if (CFG_BIBAUTHORID_ENABLED # and usepaperattribution # and acc_is_user_in_role(user_info, acc_get_role_id("paperattributionlinkviewers"))): # viewclaimlink = True if is_req: session = get_session(req) viewlink = False try: viewlink = session['personinfo']['claim_in_process'] except (KeyError, TypeError): viewlink = False else: viewlink = False
def collect_user_info(req, login_time=False, refresh=False): """Given the mod_python request object rec or a uid it returns a dictionary containing at least the keys uid, nickname, email, groups, plus any external keys in the user preferences (collected at login time and built by the different external authentication plugins) and if the mod_python request object is provided, also the remote_ip, remote_host, referer, agent fields. NOTE: if req is a mod_python request object, the user_info dictionary is saved into req._user_info (for caching purpouses) setApacheUser & setUid will properly reset it. """ from invenio.search_engine import get_permitted_restricted_collections user_info = { 'remote_ip' : '', 'remote_host' : '', 'referer' : '', 'uri' : '', 'agent' : '', 'uid' :-1, 'nickname' : '', 'email' : '', 'group' : [], 'guest' : '1', 'session' : None, 'precached_permitted_restricted_collections' : [], 'precached_usebaskets' : False, 'precached_useloans' : False, 'precached_usegroups' : False, 'precached_usealerts' : False, 'precached_usemessages' : False, 'precached_viewsubmissions' : False, 'precached_useapprove' : False, 'precached_useadmin' : False, 'precached_usestats' : False, 'precached_viewclaimlink' : False, 'precached_usepaperclaim' : False, 'precached_usepaperattribution' : False, } try: is_req = False if not req: uid = -1 elif type(req) in (type(1), type(1L)): ## req is infact a user identification uid = req elif type(req) is dict: ## req is by mistake already a user_info try: assert(req.has_key('uid')) assert(req.has_key('email')) assert(req.has_key('nickname')) except AssertionError: ## mmh... misuse of collect_user_info. Better warn the admin! register_exception(alert_admin=True) user_info.update(req) return user_info else: is_req = True uid = getUid(req) if hasattr(req, '_user_info') and not login_time: user_info = req._user_info if not refresh: return req._user_info req._user_info = user_info try: user_info['remote_ip'] = req.remote_ip except gaierror: #FIXME: we should support IPV6 too. (hint for FireRole) pass user_info['session'] = get_session(req).sid() user_info['remote_host'] = req.remote_host or '' user_info['referer'] = req.headers_in.get('Referer', '') user_info['uri'] = req.unparsed_uri or () user_info['agent'] = req.headers_in.get('User-Agent', 'N/A') user_info['uid'] = uid user_info['nickname'] = get_nickname(uid) or '' user_info['email'] = get_email(uid) or '' user_info['group'] = [] user_info['guest'] = str(isGuestUser(uid)) if user_info['guest'] == '1' and CFG_INSPIRE_SITE: usepaperattribution = False viewclaimlink = False if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role(user_info, acc_get_role_id("paperattributionviewers"))): usepaperattribution = True # if (CFG_BIBAUTHORID_ENABLED # and usepaperattribution # and acc_is_user_in_role(user_info, acc_get_role_id("paperattributionlinkviewers"))): # viewclaimlink = True if is_req: session = get_session(req) viewlink = False try: viewlink = session['personinfo']['claim_in_process'] except (KeyError, TypeError): viewlink = False else: viewlink = False if (CFG_BIBAUTHORID_ENABLED and usepaperattribution and viewlink): viewclaimlink = True user_info['precached_viewclaimlink'] = viewclaimlink user_info['precached_usepaperattribution'] = usepaperattribution if user_info['guest'] == '0': user_info['group'] = [group[1] for group in get_groups(uid)] prefs = get_user_preferences(uid) login_method = prefs['login_method'] login_object = CFG_EXTERNAL_AUTHENTICATION[login_method] if login_object and ((datetime.datetime.now() - get_last_login(uid)).seconds > 3600): ## The user uses an external authentication method and it's a bit since ## she has not performed a login if not CFG_EXTERNAL_AUTH_USING_SSO or ( is_req and login_object.in_shibboleth(req)): ## If we're using SSO we must be sure to be in HTTPS and Shibboleth handler ## otherwise we can't really read anything, hence ## it's better skip the synchronization try: groups = login_object.fetch_user_groups_membership(user_info['email'], req=req) # groups is a dictionary {group_name : group_description,} new_groups = {} for key, value in groups.items(): new_groups[key + " [" + str(login_method) + "]"] = value groups = new_groups except (AttributeError, NotImplementedError, TypeError, InvenioWebAccessExternalAuthError): pass else: # Groups synchronization from invenio.webgroup import synchronize_external_groups synchronize_external_groups(uid, groups, login_method) user_info['group'] = [group[1] for group in get_groups(uid)] try: # Importing external settings new_prefs = login_object.fetch_user_preferences(user_info['email'], req=req) for key, value in new_prefs.items(): prefs['EXTERNAL_' + key] = value except (AttributeError, NotImplementedError, TypeError, InvenioWebAccessExternalAuthError): pass else: set_user_preferences(uid, prefs) prefs = get_user_preferences(uid) run_sql('UPDATE user SET last_login=NOW() WHERE id=%s', (uid,)) if prefs: for key, value in prefs.iteritems(): user_info[key.lower()] = value if login_time: ## Heavy computational information from invenio.access_control_engine import acc_authorize_action if CFG_WEBSEARCH_PERMITTED_RESTRICTED_COLLECTIONS_LEVEL > 0: user_info['precached_permitted_restricted_collections'] = get_permitted_restricted_collections(user_info) user_info['precached_usebaskets'] = acc_authorize_action(user_info, 'usebaskets')[0] == 0 user_info['precached_useloans'] = acc_authorize_action(user_info, 'useloans')[0] == 0 user_info['precached_usegroups'] = acc_authorize_action(user_info, 'usegroups')[0] == 0 user_info['precached_usealerts'] = acc_authorize_action(user_info, 'usealerts')[0] == 0 user_info['precached_usemessages'] = acc_authorize_action(user_info, 'usemessages')[0] == 0 user_info['precached_usestats'] = acc_authorize_action(user_info, 'runwebstatadmin')[0] == 0 user_info['precached_viewsubmissions'] = isUserSubmitter(user_info) user_info['precached_useapprove'] = isUserReferee(user_info) user_info['precached_useadmin'] = isUserAdmin(user_info) usepaperclaim = False usepaperattribution = False viewclaimlink = False if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role(user_info, acc_get_role_id("paperclaimviewers"))): usepaperclaim = True if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role(user_info, acc_get_role_id("paperattributionviewers"))): usepaperattribution = True if is_req: session = get_session(req) viewlink = False try: viewlink = session['personinfo']['claim_in_process'] except (KeyError, TypeError): viewlink = False else: viewlink = False if (CFG_BIBAUTHORID_ENABLED and usepaperattribution and viewlink): viewclaimlink = True # if (CFG_BIBAUTHORID_ENABLED # and ((usepaperclaim or usepaperattribution) # and acc_is_user_in_role(user_info, acc_get_role_id("paperattributionlinkviewers")))): # viewclaimlink = True user_info['precached_viewclaimlink'] = viewclaimlink user_info['precached_usepaperclaim'] = usepaperclaim user_info['precached_usepaperattribution'] = usepaperattribution except Exception, e: register_exception()
def _precache(self, info, force=False): """ Calculate prermitions for user actions. FIXME: compatibility layer only !!! """ # get autorization key acc_key = self.get_acc_key() acc = cache.get(acc_key) if not force and acc_key is not None and acc is not None: return acc #FIXME: acc_authorize_action should use flask request directly user_info = info user_info.update(self.req) from invenio.webuser import isUserSubmitter, isUserReferee, \ isUserAdmin, isUserSuperAdmin from invenio.access_control_engine import acc_authorize_action from invenio.access_control_admin import acc_get_role_id, \ acc_is_user_in_role from invenio.search_engine import get_permitted_restricted_collections data = {} data['precached_permitted_restricted_collections'] = \ get_permitted_restricted_collections(user_info) data['precached_usebaskets'] = acc_authorize_action( user_info, 'usebaskets')[0] == 0 data['precached_useloans'] = acc_authorize_action( user_info, 'useloans')[0] == 0 data['precached_usegroups'] = acc_authorize_action( user_info, 'usegroups')[0] == 0 data['precached_usealerts'] = acc_authorize_action( user_info, 'usealerts')[0] == 0 data['precached_usemessages'] = acc_authorize_action( user_info, 'usemessages')[0] == 0 data['precached_usestats'] = acc_authorize_action( user_info, 'runwebstatadmin')[0] == 0 data['precached_viewsubmissions'] = isUserSubmitter(user_info) data['precached_useapprove'] = isUserReferee(user_info) data['precached_useadmin'] = isUserAdmin(user_info) data['precached_usesuperadmin'] = isUserSuperAdmin(user_info) data['precached_canseehiddenmarctags'] = acc_authorize_action( user_info, 'runbibedit')[0] == 0 usepaperclaim = False usepaperattribution = False viewclaimlink = False if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role( user_info, acc_get_role_id("paperclaimviewers"))): usepaperclaim = True if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role( user_info, acc_get_role_id("paperattributionviewers"))): usepaperattribution = True viewlink = False try: viewlink = session['personinfo']['claim_in_process'] except (KeyError, TypeError): pass if (CFG_BIBAUTHORID_ENABLED and usepaperattribution and viewlink): viewclaimlink = True # if (CFG_BIBAUTHORID_ENABLED # and ((usepaperclaim or usepaperattribution) # and acc_is_user_in_role(data, acc_get_role_id("paperattributionlinkviewers")))): # viewclaimlink = True data['precached_viewclaimlink'] = viewclaimlink data['precached_usepaperclaim'] = usepaperclaim data['precached_usepaperattribution'] = usepaperattribution cache.set(acc_key, data, timeout=CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT * 3600) return data
def User_is_Record_Owner_or_Curator(parameters, curdir, form, user_info=None): """ Check that user is either the original submitter, or that it belongs to the role(s) given as parameter. This enables collaborative editing of records, so that collections can be curated by a group of people in addition to the original submitter. If the user has permission, the function ends silently. If not, it will raise an InvenioWebSubmitFunctionStop, informing the user that they don't have rights and sending them back to the submission web form. This function makes it unnecessary to protect the submission with WebAccess (i.e. 'submit' action): the function can check authorizations by itself. However if the case the action in which this function is used is still protected with WebAccess (eg. an authorization exists for the 'submit' action, in 'MBI'), ALL the possible submitters AND the curators groups must be linked to the authorization in order for WebSubmit to let users reach this function: this function then ensures that only curators or submitters of the record will be able to continue further. A record owner must have her email in the record metadata. A record curator must be in the role given as parameter to this function. WARNING: you must remember that category-based restrictions require you to check that the selected category matches the document to modify: one can select category 'foo' to modify a document submitted in category 'bar', given that submissions are indepedendant of the record they create. WARNING: for backward compatibility reasons, if no role is given as parameter, the function simply check against the WebAccess 'submit' action, with this submission parameters. It then means that anybody connected to the authorization will be able to modify ANY of the records this submission can handle. @parameters: - curator_role: a role or mapping of roles that determine if user is a curator or not. The parameter can simply be the name of a WebAccess role. For eg: curator_photo where 'curator_photo' is a WebAccess role matching curator users for this submission. The parameter can also map the submission categories to different roles, so that different curator groups can be defined. For eg: ARTICLE=curator_art|REPORT=curator_rep|*=curator_gen (syntax: '|' to split mappings, and '=' to map category->role) This specifies that role 'curator_art' is used when category 'Article' is selected (code for this category is 'ARTICLE'), 'curator_rep' when 'Report' ('REPORT' code) is selected, and curator_gen in all other cases. * matches all categories. When defining a mapping category->role, and category cannot be retrieved (for eg. with /submit/direct URLs that do not specify category), only the * rule/role is matched. Eg: foo=role1|*=role2 matches role2 only When no role is defined or matched, the curator role is checked against the WebAccess 'submit' action, for current WebSubmit doctype, action and category. - curator_flag: the name of a file in which '1' is written if current submitter is a curator. Otherwise, an empty file is written. If no value is given, no file is written. @return: Empty string. @Exceptions raised: InvenioWebSubmitFunctionStop when user is denied permission to work with the record. """ global sysno # Get current doctype doctype_fd = open(os.path.join(curdir, 'doctype')) doctype = doctype_fd.read() doctype_fd.close() # Get current action act_fd = open(os.path.join(curdir, 'act')) act = act_fd.read() act_fd.close() # Get category. This one might not exist category = None if os.path.exists(os.path.join(curdir, 'combo%s' % doctype)): category_fd = open(os.path.join(curdir, 'combo%s' % doctype)) category = category_fd.read() category_fd.close() # Get role to belong to in order to be curator. If not specifed, # we simply check against 'submit' WebAccess action for the current # WebSubmit action (for eg. 'MBI') curator_roles = [] try: curator_role = parameters['curator_role'] except: curator_role = '' if '=' in curator_role: # Admin specifed a different role for different category. # For eg: general=curator_gen|photo=curator_photo|*=curator_other curator_roles = [categ_and_role.split('=', 1)[1].strip() \ for categ_and_role in curator_role.split('|') if \ len(categ_and_role.split('=', 1)) == 2 and \ categ_and_role.split('=', 1)[0].strip() in (category, '*')] elif curator_role: curator_roles = [curator_role] ## Get the current user's e-mail address: user_email = user_info["email"].lower() ## Now get the email address(es) of the record submitter(s)/owner(s) from ## the record itself: record_owners_list = [email.lower().strip() for email in \ get_fieldvalues(sysno, CFG_WEBSUBMIT_RECORD_OWNER_EMAIL)] ## Now determine whether this user is listed in the record as an "owner" ## (or submitter): user_has_permission = False user_msg = "" if user_email not in ("", "guest") and user_email in record_owners_list: ## This user's email address is listed in the record. She should ## be allowed to work with it: user_has_permission = True # Check if user is curator is_curator = False if curator_roles: # Check against roles for role in curator_roles: if not acc_get_role_id(role): # Role is not defined continue if acc_is_user_in_role(user_info, acc_get_role_id(role)): # One matching role found user_has_permission = True is_curator = True break else: # Check against authorization for 'submit' (for backward compatibility) (auth_code, dummy) = acc_authorize_action(user_info, \ "submit", \ verbose=0, \ doctype=doctype, \ act=act) if auth_code == 0: ## The user is a curator for this ## submission/collection. Do not prevent access. is_curator = True user_has_permission = True try: curator_flag = parameters['curator_flag'] if curator_flag: flag_fd = open(os.path.join(curdir, curator_flag), 'w') flag_fd.write(is_curator and '1' or '0') flag_fd.close() except: pass ## Finally, if the user still doesn't have permission to work with this ## record, raise an InvenioWebSubmitFunctionStop exception sending the ## user back to the form. if not user_has_permission: raise InvenioWebSubmitFunctionStop(CFG_MSG_USER_NOT_AUTHORIZED) return ""