def get_authorized_deposition_types(user_info): """Return a list of allowed deposition types for a certain user.""" from invenio_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 }
def _authorize_user(obj, dummy_eng): from invenio_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)
def allows(self, identity): """Check if given identity can perform defined action.""" from invenio_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
def allows(self, identity): """Check if given identity can perform defined action.""" from invenio_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
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 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)
def get_permitted_restricted_collections(user_info, recreate_cache_if_needed=True): """Return a list of restricted collection with user is authorization.""" from invenio_access.engine import acc_authorize_action from invenio_collections.cache import ( restricted_collection_cache, ) if recreate_cache_if_needed: restricted_collection_cache.recreate_cache_if_needed() ret = [] auths = acc_authorize_action(user_info, 'viewrestrcoll', batch_args=True, collection=restricted_collection_cache.cache) for collection, auth in zip(restricted_collection_cache.cache, auths): if auth[0] == 0: ret.append(collection) return ret
def get_permitted_restricted_collections(user_info, recreate_cache_if_needed=True): """Return a list of restricted collection with user is authorization.""" from invenio_access.engine import acc_authorize_action if recreate_cache_if_needed: restricted_collection_cache.recreate_cache_if_needed() ret = [] auths = acc_authorize_action( user_info, 'viewrestrcoll', batch_args=True, collection=restricted_collection_cache.cache ) for collection, auth in zip(restricted_collection_cache.cache, auths): if auth[0] == 0: ret.append(collection) return ret
def main(): """CLI to acc_authorize_action. The function finds the needed arguments in sys.argv. If the number of arguments is wrong it prints help. Return 0 on success, 9 or higher on failure. """ from invenio_access.engine import acc_authorize_action from invenio_access.local_config import CFG_WEBACCESS_WARNING_MSGS alen, auth = len(sys.argv), 0 # return ``not permitted'' if wrong arguments if alen > 1 and sys.argv[1] in ["-h", "--help"]: usage(0) elif alen > 1 and sys.argv[1] in ["-V", "--version"]: sys.stderr.write("%s\n" % __revision__) sys.exit(0) if alen < 3 or alen % 2 == 0: print("7 - %s" % CFG_WEBACCESS_WARNING_MSGS[7]) return "7 - %s" % CFG_WEBACCESS_WARNING_MSGS[7] # try to authorize else: # get values id_user = int(sys.argv[1]) name_action = sys.argv[2] kwargs = {} for i in range(3, alen, 2): kwargs[sys.argv[i]] = sys.argv[i + 1] # run ace-function (auth_code, auth_message) = acc_authorize_action(id_user, name_action, **kwargs) # print and return print("%s - %s" % (auth_code, auth_message)) return "%s - %s" % (auth_code, auth_message)
def is_authorized(self, name, **kwargs): """Check if user is authorized.""" from invenio_access.engine import acc_authorize_action return acc_authorize_action(self, name)[0] == 0
def _precache(self, info, force=False): """Calculate permissions for user actions. FIXME: compatibility layer only !!! """ try: from invenio_accounts.models import User except ImportError: return {} CFG_BIBAUTHORID_ENABLED = current_app.config.get( 'CFG_BIBAUTHORID_ENABLED', False) # get authorization 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) user = User.query.get(user_info['uid']) from invenio_access.engine import acc_authorize_action from invenio_access.control import acc_get_role_id, \ acc_is_user_in_role from invenio_search.utils import \ get_permitted_restricted_collections from invenio_deposit.cache import \ get_authorized_deposition_types data = {} data['precached_permitted_restricted_collections'] = \ get_permitted_restricted_collections(user_info) data['precached_allowed_deposition_types'] = \ get_authorized_deposition_types(user_info) data['precached_useloans'] = acc_authorize_action( user_info, 'useloans')[0] == 0 data['precached_usegroups'] = acc_authorize_action( user_info, 'usegroups')[0] == 0 data['precached_usemessages'] = acc_authorize_action( user_info, 'usemessages')[0] == 0 data['precached_useadmin'] = user.has_admin_role data['precached_usesuperadmin'] = user.has_super_admin_role 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 (current_app.config.get('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 timeout = current_app.config.get( 'CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT', 0) * 3600 cache.set(acc_key, data, timeout=timeout) return data
def check_user_can_view_record(user_info, recid): """Check if the user is authorized to view the given recid. The function grants access in two cases: either user has author rights on this record, or he has view rights to the primary collection this record belongs to. :param user_info: the user_info dictionary that describe the user. :type user_info: user_info dictionary :param recid: the record identifier. :type recid: positive integer :return: (0, ''), when authorization is granted, (>0, 'message') when authorization is not granted """ from invenio_access.engine import acc_authorize_action from invenio_access.local_config import VIEWRESTRCOLL policy = cfg['CFG_WEBSEARCH_VIEWRESTRCOLL_POLICY'].strip().upper() if not isinstance(recid, MutableMapping): record = get_record(int(recid)) else: record = recid # At this point, either webcoll has not yet run or there are some # restricted collections. Let's see first if the user own the record. if is_user_owner_of_record(user_info, record): # Perfect! It's authorized then! return (0, '') if is_user_viewer_of_record(user_info, record): # Perfect! It's authorized then! return (0, '') restricted_collections = get_restricted_collections_for_record( record, recreate_cache_if_needed=False) if not restricted_collections and is_record_public(record): # The record is public and not part of any restricted collection return (0, '') if restricted_collections: # If there are restricted collections the user must be authorized to # all/any of them (depending on the policy) auth_code, auth_msg = 0, '' for collection in restricted_collections: (auth_code, auth_msg) = acc_authorize_action(user_info, VIEWRESTRCOLL, collection=collection) if auth_code and policy != 'ANY': # Ouch! the user is not authorized to this collection return (auth_code, auth_msg) elif auth_code == 0 and policy == 'ANY': # Good! At least one collection is authorized return (0, '') # Depending on the policy, the user will be either authorized or not return auth_code, auth_msg # FIXME is record in any collection if bool(record.get('_collections', [])): # the record is not in any restricted collection return (0, '') elif record is not None: # We are in the case where webcoll has not run. # Let's authorize SUPERADMIN (auth_code, auth_msg) = acc_authorize_action(user_info, VIEWRESTRCOLL, collection=None) if auth_code == 0: return (0, '') else: # Too bad. Let's print a nice message: return ( 1, "The record you are trying to access has just been " "submitted to the system and needs to be assigned to the " "proper collections. It is currently restricted for security " "reasons until the assignment will be fully completed. Please " "come back later to properly access this record.") else: # The record either does not exists or has been deleted. # Let's handle these situations outside of this code. return (0, '')
def authorize_action(self, *args, **kwargs): from invenio_access.engine import acc_authorize_action return acc_authorize_action(*args, **kwargs)
def managedocfiles(self, req, form): """ Display admin interface to manage files of a record """ argd = wash_urlargd(form, { 'ln': (str, ''), 'access': (str, ''), 'recid': (int, None), 'do': (int, 0), 'cancel': (str, None), }) _ = gettext_set_language(argd['ln']) uid = getUid(req) user_info = collect_user_info(req) # Check authorization (auth_code, auth_msg) = acc_authorize_action(req, 'runbibdocfile') 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_SECURE_URL + user_info['uri']}, {}) return redirect_to_url(req, target) elif auth_code: return page_not_authorized(req, referer="/%s/managedocfiles" % CFG_SITE_RECORD, uid=uid, text=auth_msg, ln=argd['ln'], navmenuid="admin") # Prepare navtrail navtrail = '''<a class="navtrail" href="%(CFG_SITE_URL)s/help/admin">Admin Area</a> > %(manage_files)s''' \ % {'CFG_SITE_URL': CFG_SITE_URL, 'manage_files': _("Manage Document Files")} body = '' if argd['do'] != 0 and not argd['cancel']: # Apply modifications working_dir = os.path.join(CFG_TMPSHAREDDIR, 'websubmit_upload_interface_config_' + str(uid), argd['access']) if not os.path.isdir(working_dir): # We accessed the url without preliminary steps # (we did not upload a file) # Our working dir does not exist # Display the file manager argd['do'] = 0 else: move_uploaded_files_to_storage(working_dir=working_dir, recid=argd['recid'], icon_sizes=['180>', '700>'], create_icon_doctypes=['*'], force_file_revision=False) # Clean temporary directory shutil.rmtree(working_dir) # Confirm modifications body += '<p style="color:#0f0">%s</p>' % \ (_('Your modifications to record #%(x_redid)i have been submitted', x_redid=argd['recid'])) elif argd['cancel']: # Clean temporary directory working_dir = os.path.join(CFG_TMPSHAREDDIR, 'websubmit_upload_interface_config_' + str(uid), argd['access']) shutil.rmtree(working_dir) body += '<p style="color:#c00">%s</p>' % \ (_('Your modifications to record #%(x_num)i have been cancelled', x_num=argd['recid'])) if not argd['recid'] or argd['do'] != 0: body += ''' <form method="post" action="%(CFG_SITE_URL)s/%(CFG_SITE_RECORD)s/managedocfiles"> <label for="recid">%(edit_record)s:</label> <input type="text" name="recid" id="recid" /> <input type="submit" value="%(edit)s" class="adminbutton" /> </form> ''' % {'edit': _('Edit'), 'edit_record': _('Edit record'), 'CFG_SITE_URL': CFG_SITE_URL, 'CFG_SITE_RECORD': CFG_SITE_RECORD} access = time.strftime('%Y%m%d_%H%M%S') if argd['recid'] and argd['do'] == 0: # Displaying interface to manage files # Prepare navtrail title, dummy_description, dummy_keywords = websearch_templates.tmpl_record_page_header_content(req, argd['recid'], argd['ln']) navtrail = '''<a class="navtrail" href="%(CFG_SITE_URL)s/help/admin">Admin Area</a> > <a class="navtrail" href="%(CFG_SITE_URL)s/%(CFG_SITE_RECORD)s/managedocfiles">%(manage_files)s</a> > %(record)s: %(title)s ''' \ % {'CFG_SITE_URL': CFG_SITE_URL, 'title': title, 'manage_files': _("Document File Manager"), 'record': _("Record #%(x_rec)i", x_rec=argd['recid']), 'CFG_SITE_RECORD': CFG_SITE_RECORD} body += create_file_upload_interface(\ recid=argd['recid'], ln=argd['ln'], uid=uid, sbm_access=access, display_hidden_files=True, restrictions_and_desc=CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_RESTRICTIONS, doctypes_and_desc=CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_DOCTYPES, **CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_MISC)[1] body += '''<br /> <form method="post" action="%(CFG_SITE_URL)s/%(CFG_SITE_RECORD)s/managedocfiles"> <input type="hidden" name="recid" value="%(recid)s" /> <input type="hidden" name="do" value="1" /> <input type="hidden" name="access" value="%(access)s" /> <input type="hidden" name="ln" value="%(ln)s" /> <div style="font-size:small"> <input type="submit" name="cancel" value="%(cancel_changes)s" /> <input type="submit" onclick="user_must_confirm_before_leaving_page=false;return true;" class="adminbutton" name="submit" id="applyChanges" value="%(apply_changes)s" /> </div></form>''' % \ {'apply_changes': _("Apply changes"), 'cancel_changes': _("Cancel all changes"), 'recid': argd['recid'], 'access': access, 'ln': argd['ln'], 'CFG_SITE_URL': CFG_SITE_URL, 'CFG_SITE_RECORD': CFG_SITE_RECORD} return page(title = _("Document File Manager") + (argd['recid'] and (': ' + _("Record #%(x_rec)i", x_rec=argd['recid'])) or ''), navtrail=navtrail, navtrail_append_title_p=0, metaheaderadd = get_upload_file_interface_javascript(form_url_params='?access='+access) + \ get_upload_file_interface_css(), body = body, uid = uid, language=argd['ln'], req=req, navmenuid='admin')
def _precache(self, info, force=False): """Calculate permissions for user actions. FIXME: compatibility layer only !!! """ CFG_BIBAUTHORID_ENABLED = current_app.config.get("CFG_BIBAUTHORID_ENABLED", False) # get authorization 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.legacy.webuser import isUserSubmitter, isUserReferee, isUserAdmin, isUserSuperAdmin from invenio_access.engine import acc_authorize_action from invenio_access.control import acc_get_role_id, acc_is_user_in_role from invenio_search.utils import get_permitted_restricted_collections from invenio_deposit.cache import get_authorized_deposition_types data = {} data["precached_permitted_restricted_collections"] = get_permitted_restricted_collections(user_info) data["precached_allowed_deposition_types"] = get_authorized_deposition_types(user_info) data["precached_useloans"] = acc_authorize_action(user_info, "useloans")[0] == 0 data["precached_usegroups"] = acc_authorize_action(user_info, "usegroups")[0] == 0 data["precached_usemessages"] = acc_authorize_action(user_info, "usemessages")[0] == 0 try: data["precached_viewsubmissions"] = isUserSubmitter(user_info) except Exception: data["precached_viewsubmissions"] = None 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 current_app.config.get("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 timeout = current_app.config.get("CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT", 0) * 3600 cache.set(acc_key, data, timeout=timeout) return data
def _precache(self, info, force=False): """Calculate permissions for user actions. FIXME: compatibility layer only !!! """ try: from invenio_accounts.models import User except ImportError: return {} CFG_BIBAUTHORID_ENABLED = current_app.config.get( 'CFG_BIBAUTHORID_ENABLED', False) # get authorization 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) user = User.query.get(user_info['uid']) data = {} data['precached_useadmin'] = getattr(user, 'has_admin_role', False) data['precached_usesuperadmin'] = getattr(user, 'has_super_admin_role', False) try: from invenio_search.utils import \ get_permitted_restricted_collections data['precached_permitted_restricted_collections'] = \ get_permitted_restricted_collections(user_info) except Exception: current_app.logger.exception( 'Permitted restricted collections were not loaded.') try: from invenio_deposit.cache import \ get_authorized_deposition_types data['precached_allowed_deposition_types'] = \ get_authorized_deposition_types(user_info) except Exception: current_app.logger.exception( 'Allowed deposition types were not loaded.') usepaperclaim = False usepaperattribution = False viewclaimlink = False try: from invenio_access.engine import acc_authorize_action from invenio_access.control import acc_get_role_id, \ acc_is_user_in_role data['precached_useloans'] = acc_authorize_action( user_info, 'useloans')[0] == 0 data['precached_usegroups'] = acc_authorize_action( user_info, 'usegroups')[0] == 0 data['precached_usemessages'] = acc_authorize_action( user_info, 'usemessages')[0] == 0 data['precached_canseehiddenmarctags'] = acc_authorize_action( user_info, 'runbibedit')[0] == 0 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 except Exception: current_app.logger.exception("Access control module is broken.") viewlink = False try: viewlink = session['personinfo']['claim_in_process'] except (KeyError, TypeError): pass if (current_app.config.get('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 timeout = current_app.config.get('CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT', 0) * 3600 cache.set(acc_key, data, timeout=timeout) return data
def managedocfilesasync(self, req, form): "Upload file and returns upload interface" argd = wash_urlargd(form, { 'ln': (str, ''), 'recid': (int, 1), 'doctype': (str, ''), 'access': (str, ''), 'indir': (str, ''), }) user_info = collect_user_info(req) include_headers = False # User submitted either through WebSubmit, or admin interface. if 'doctype' in form and 'indir' in form \ and 'access' in form: # Submitted through WebSubmit. Check rights include_headers = True working_dir = os.path.join(CFG_WEBSUBMIT_STORAGEDIR, argd['indir'], argd['doctype'], argd['access']) try: assert(working_dir == os.path.abspath(working_dir)) except AssertionError: raise apache.SERVER_RETURN(apache.HTTP_UNAUTHORIZED) try: # Retrieve recid from working_dir, safer. recid_fd = file(os.path.join(working_dir, 'SN')) recid = int(recid_fd.read()) recid_fd.close() except: recid = "" try: act_fd = file(os.path.join(working_dir, 'act')) action = act_fd.read() act_fd.close() except: action = "" # Is user authorized to perform this action? auth_code = acc_authorize_action(user_info, "submit", authorized_if_no_roles=not isGuestUser(getUid(req)), doctype=argd['doctype'], act=action)[0] if auth_code and not acc_is_role("submit", doctype=argd['doctype'], act=action): # There is NO authorization plugged. User should have access auth_code = 0 else: # User must be allowed to attach files auth_code = acc_authorize_action(user_info, 'runbibdocfile')[0] recid = argd['recid'] if auth_code: raise apache.SERVER_RETURN(apache.HTTP_UNAUTHORIZED) return create_file_upload_interface(recid=recid, ln=argd['ln'], print_outside_form_tag=False, print_envelope=False, form=form, include_headers=include_headers, sbm_indir=argd['indir'], sbm_access=argd['access'], sbm_doctype=argd['doctype'], uid=user_info['uid'])[1]