desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Remove a role from the system. @param role_id: the ID or UID of the role @note: protected roles cannot be deleted with this function, need to reset the protected-flag first to override'
def s3_delete_role(self, role_id):
db = current.db table = self.settings.table_group if (isinstance(role_id, str) and (not role_id.isdigit())): query = (table.uuid == role_id) else: role_id = int(role_id) query = (table.id == role_id) role = db(query).select(table.id, table.protected, limitby=(0, 1)).first() ...
'Assigns a role to a user (add the user to a user group) @param user_id: the record ID of the user account @param group_id: the record ID(s)/UID(s) of the group @param for_pe: the person entity (pe_id) to restrict the group membership to, possible values: - None: use default realm (entities the user is affiliated with)...
def s3_assign_role(self, user_id, group_id, for_pe=None):
db = current.db gtable = self.settings.table_group mtable = self.settings.table_membership query = None uuids = None if isinstance(group_id, (list, tuple)): if isinstance(group_id[0], str): uuids = group_id query = gtable.uuid.belongs(group_id) else: ...
'Removes a role assignment from a user account @param user_id: the record ID of the user account @param group_id: the record ID(s)/UID(s) of the role @param for_pe: only remove the group membership for this realm, possible values: - None: only remove for the default realm - 0: only remove for the site-wide realm - X: o...
def s3_withdraw_role(self, user_id, group_id, for_pe=None):
if (not group_id): return db = current.db gtable = self.settings.table_group mtable = self.settings.table_membership query = None if isinstance(group_id, (list, tuple)): if isinstance(group_id[0], str): query = gtable.uuid.belongs(group_id) else: g...
'Lookup all roles which have been assigned to user for an entity @param user_id: the user_id @param for_pe: the entity (pe_id) or list of entities'
def s3_get_roles(self, user_id, for_pe=[]):
if (not user_id): return [] mtable = self.settings.table_membership query = ((mtable.deleted != True) & (mtable.user_id == user_id)) if isinstance(for_pe, (list, tuple)): if len(for_pe): query &= mtable.pe_id.belongs(for_pe) else: query &= (mtable.pe_id == for_pe)...
'Check whether the currently logged-in user has a certain role (auth_group membership). @param role: the record ID or UID of the role @param for_pe: check for this particular realm, possible values: None - for any entity 0 - site-wide X - for entity X'
def s3_has_role(self, role, for_pe=None):
if self.override: return True system_roles = self.get_system_roles() if (role == system_roles.ANONYMOUS): return True s3 = current.session.s3 self.s3_logged_in() if (not s3): return False realms = None if self.user: realms = self.user.realms elif s3.ro...
'Get a list of members of a group @param group_id: the group record ID @param for_pe: show only group members for this PE @return: a list of the user_ids for members of a group'
def s3_group_members(self, group_id, for_pe=[]):
mtable = self.settings.table_membership query = ((mtable.deleted != True) & (mtable.group_id == group_id)) if (for_pe is None): query &= (mtable.pe_id == None) elif for_pe: query &= (mtable.pe_id == for_pe) members = current.db(query).select(mtable.user_id) return [m.user_id for ...
'Delegate a role (auth_group) from one entity to another @param group_id: the role ID or UID (or a list of either) @param entity: the delegating entity @param receiver: the pe_id of the receiving entity (or a list of pe_ids) @param role: the affiliation role @param role_type: the role type for the affiliation role (def...
def s3_delegate_role(self, group_id, entity, receiver=None, role=None, role_type=None):
if (not self.permission.delegations): return False db = current.db s3db = current.s3db dtable = s3db.table('pr_delegation') rtable = s3db.table('pr_role') atable = s3db.table('pr_affiliation') if ((dtable is None) or (rtable is None) or (atable is None)): return False if ...
'Remove a delegation. @param group_id: the auth_group ID or UID (or a list of either) @param entity: the delegating entity @param receiver: the receiving entity @param role: the affiliation role @note: if receiver is specified, only 1:1 delegations (to role_type 0) will be removed, but not 1:N delegations => to remove ...
def s3_remove_delegation(self, group_id, entity, receiver=None, role=None):
if (not self.permission.delegations): return False db = current.db s3db = current.s3db dtable = s3db.table('pr_delegation') rtable = s3db.table('pr_role') atable = s3db.table('pr_affiliation') if ((dtable is None) or (rtable is None) or (atable is None)): return False if ...
'Lookup delegations for an entity, ordered either by receiver (by_role=False) or by affiliation role (by_role=True) @param entity: the delegating entity (pe_id) @param role_type: limit the lookup to this affiliation role type, (can use 0 to lookup 1:1 delegations) @param by_role: group by affiliation roles @return: a S...
def s3_get_delegations(self, entity, role_type=0, by_role=False):
if ((not entity) or (not self.permission.delegations)): return None s3db = current.s3db dtable = s3db.pr_delegation rtable = s3db.pr_role atable = s3db.pr_affiliation if (None in (dtable, rtable, atable)): return None query = ((((((rtable.deleted != True) & (dtable.deleted !=...
'Wrapper for permission.update_acl to allow batch updating'
def s3_update_acls(self, role, *acls):
for acl in acls: self.permission.update_acl(role, **acl)
'Get the user_id for a person_id @param person_id: the pr_person record ID, or a user email address @param pe_id: the person entity ID, alternatively'
def s3_get_user_id(self, person_id=None, pe_id=None):
result = None if (isinstance(person_id, basestring) and (not person_id.isdigit())): utable = self.settings.table_user query = (utable.email == person_id) user = current.db(query).select(utable.id, limitby=(0, 1)).first() if user: result = user.id else: s3d...
'Get the person pe_id for a user ID @param user_id: the user ID'
def s3_user_pe_id(self, user_id):
table = current.s3db.pr_person_user row = current.db((table.user_id == user_id)).select(table.pe_id, limitby=(0, 1)).first() return (row.pe_id if row else None)
'Get the list of person pe_id for list of user_ids @param user_id: list of user IDs'
def s3_bulk_user_pe_id(self, user_ids):
table = current.s3db.pr_person_user if (not isinstance(user_ids, list)): user_ids = [user_ids] rows = current.db(table.user_id.belongs([user_id for user_id in user_ids])).select(table.pe_id, table.user_id) if rows: return {row.user_id: row.pe_id for row in rows} return None
'Get the person record ID for the current logged-in user'
def s3_logged_in_person(self):
row = None if self.s3_logged_in(): ptable = current.s3db.pr_person try: query = (ptable.pe_id == self.user.pe_id) except AttributeError: pass else: row = current.db(query).select(ptable.id, limitby=(0, 1)).first() return (row.id if row else...
'Get the first HR record ID for the current logged-in user'
def s3_logged_in_human_resource(self):
row = None if self.s3_logged_in(): s3db = current.s3db ptable = s3db.pr_person htable = s3db.hrm_human_resource try: query = ((htable.person_id == ptable.id) & (ptable.pe_id == self.user.pe_id)) except AttributeError: pass else: ...
'S3 framework function to define whether a user can access a record in manner "method". Designed to be called from the RESTlike controller. @param method: the access method as string, one of "create", "read", "update", "delete" @param table: the table or tablename @param record_id: the record ID (if any) @param c: the ...
def s3_has_permission(self, method, table, record_id=None, c=None, f=None):
if self.override: return True sr = self.get_system_roles() if (not hasattr(table, '_tablename')): tablename = table table = current.s3db.table(tablename, db_only=True) if (table is None): current.log.warning(("Permission check on Table %s failed ...
'Returns a query with all accessible records for the currently logged-in user @param method: the access method as string, one of: "create", "read", "update" or "delete" @param table: the table or table name @param c: the controller name (overrides current.request) @param f: the function name (overrides current.request)...
def s3_accessible_query(self, method, table, c=None, f=None):
if self.override: return (table.id > 0) sr = self.get_system_roles() if (not hasattr(table, '_tablename')): table = current.s3db[table] policy = current.deployment_settings.get_security_policy() if (policy == 1): return (table.id > 0) elif (policy == 2): return (t...
'Checks if user is member of group_id or role Extends Web2Py\'s requires_membership() to add new functionality: - Custom Flash style - Uses s3_has_role()'
def s3_has_membership(self, group_id=None, user_id=None, role=None):
if self.override: return True group_id = (group_id or self.id_group(role)) try: group_id = int(group_id) except: group_id = self.id_group(group_id) if self.s3_has_role(group_id): r = True else: r = False log = self.messages.has_membership_log if lo...
'Decorator that prevents access to action if not logged in or if user logged in is not a member of group_id. If role is provided instead of group_id then the group_id is calculated. Extends Web2Py\'s requires_membership() to add new functionality: - Custom Flash style - Uses s3_has_role() - Administrators (id=1) are de...
def s3_requires_membership(self, role):
def decorator(action): def f(*a, **b): if self.override: return action(*a, **b) ADMIN = self.get_system_roles().ADMIN if ((not self.s3_has_role(role)) and (not self.s3_has_role(ADMIN))): self.permission.fail() return action(*a, ...
'Makes the current session owner of a record @param table: the table or table name @param record_id: the record ID'
def s3_make_session_owner(self, table, record_id):
if hasattr(table, '_tablename'): tablename = original_tablename(table) else: tablename = table if (not self.user): session = current.session if ('owned_records' not in session): session.owned_records = {} records = session.owned_records.get(tablename, []) ...
'Checks whether the current session owns a record @param table: the table or table name @param record_id: the record ID'
def s3_session_owns(self, table, record_id):
session = current.session if (self.user or (not record_id) or ('owned_records' not in session)): return False if hasattr(table, '_tablename'): tablename = original_tablename(table) else: tablename = table records = session.owned_records.get(tablename) if records: ...
'Removes session ownership for a record @param table: the table or table name (default: all tables) @param record_id: the record ID (default: all records)'
def s3_clear_session_ownership(self, table=None, record_id=None):
session = current.session if ('owned_records' not in session): return if (table is not None): if hasattr(table, '_tablename'): tablename = original_tablename(table) else: tablename = table if (tablename in session.owned_records): if record_...
'Update ownership fields in a record (DRY helper method for s3_set_record_owner and set_realm_entity) @param table: the table @param record: the record or record ID @param update: True to update realm_entity in all realm-components @param fields: dict of {ownership_field:value}'
def s3_update_record_owner(self, table, record, update=False, **fields):
OUSR = 'owned_by_user' OGRP = 'owned_by_group' REALM = 'realm_entity' ownership_fields = (OUSR, OGRP, REALM) pkey = table._id.name if (isinstance(record, (Row, dict)) and (pkey in record)): record_id = record[pkey] else: record_id = record data = Storage() for key in ...
'Set the record owned_by_user, owned_by_group and realm_entity for a record (auto-detect values). To be called by CRUD and Importer during record creation. @param table: the Table (or table name) @param record: the record (or record ID) @param force_update: True to update all fields regardless of the current value in t...
def s3_set_record_owner(self, table, record, force_update=False, **fields):
s3db = current.s3db OUSR = 'owned_by_user' OGRP = 'owned_by_group' REALM = 'realm_entity' ownership_fields = (OUSR, OGRP, REALM) EID = 'pe_id' OID = 'organisation_id' SID = 'site_id' GID = 'group_id' PID = 'person_id' entity_fields = (EID, OID, SID, GID, PID) if hasattr(t...
'Update the realm entity for records, will also update the realm in all configured realm-entities, see: http://eden.sahanafoundation.org/wiki/S3AAA/OrgAuth#Realms1 To be called by CRUD and Importer during record update. @param table: the Table (or tablename) @param records: - a single record - a single record ID - a li...
def set_realm_entity(self, table, records, entity=0, force_update=False):
db = current.db s3db = current.s3db REALM = 'realm_entity' EID = 'pe_id' OID = 'organisation_id' SID = 'site_id' GID = 'group_id' entity_fields = (EID, OID, SID, GID) if hasattr(table, '_tablename'): tablename = original_tablename(table) else: tablename = table ...
'Lookup the realm entity for a record @param table: the Table @param record: the record (as Row or dict) @param entity: the entity (pe_id)'
def get_realm_entity(self, table, record, entity=0):
if ('realm_entity' not in table): return None s3db = current.s3db if isinstance(entity, tuple): realm_entity = s3db.pr_get_pe_id(entity) else: realm_entity = entity if (realm_entity == 0): handler = current.deployment_settings.get_auth_realm_entity() if callab...
'Update the shared fields in data in all super-entity rows linked with this record. @param table: the table @param record: a record, record ID or a query @param data: the field/value pairs to update'
def update_shared_fields(self, table, record, **data):
db = current.db s3db = current.s3db super_entities = s3db.get_config(table, 'super_entity') if (not super_entities): return if (not isinstance(super_entities, (list, tuple))): super_entities = [super_entities] tables = dict() load = s3db.table super_key = s3db.super_key ...
'If there are no facilities that the user has permission for, prevents create & update of records in table & gives a warning if the user tries to. @param table: the table or table name @param error_msg: error message @param redirect_on_error: whether to redirect on error @param facility_type: restrict to this particula...
def permitted_facilities(self, table=None, error_msg=None, redirect_on_error=True, facility_type=None):
T = current.T ERROR = T('You do not have permission for any facility to perform this action.') HINT = T('Create a new facility or ensure that you have permissions for an existing facility.') if (not error_msg): error_msg = E...
'If there are no organisations that the user has update permission for, prevents create & update of a record in table & gives an warning if the user tries to. @param table: the table or table name @param error_msg: error message @param redirect_on_error: whether to redirect on error'
def permitted_organisations(self, table=None, error_msg=None, redirect_on_error=True):
T = current.T ERROR = T('You do not have permission for any organization to perform this action.') HINT = T('Create a new organization or ensure that you have permissions for an existing organization.') if (not error_msg): e...
'Return the current user\'s root organisation ID or None'
def root_org(self):
if (not self.user): return None org_id = self.user.organisation_id if (not org_id): return None if (not current.deployment_settings.get_org_branches()): return org_id return current.cache.ram(('root_org_%s' % org_id), (lambda : current.s3db.org_root_organisation(org_id)), tim...
'Return the current user\'s root organisation name or None'
def root_org_name(self):
if (not self.user): return None org_id = self.user.organisation_id if (not org_id): return None if (not current.deployment_settings.get_org_branches()): s3db = current.s3db table = s3db.org_organisation row = current.db((table.id == org_id)).select(table.name, cac...
'Function to return a query to filter a table to only display results for the user\'s root org OR record with no root org @ToDo: Restore Realms and add a role/functionality support for Master Data Then this function is redundant'
def filter_by_root_org(self, table):
root_org = self.root_org() if root_org: return ((table.organisation_id == root_org) | (table.organisation_id == None)) else: return (table.organisation_id == None)
'Constructor, invoked by AuthS3.__init__ @param auth: the AuthS3 instance @param tablename: the name for the permissions table'
def __init__(self, auth, tablename=None):
db = current.db self.auth = auth self.error = S3PermissionError settings = current.deployment_settings self.policy = settings.get_security_policy() self.use_cacls = (self.policy in (3, 4, 5, 6, 7, 8)) self.use_facls = (self.policy in (4, 5, 6, 7, 8)) self.use_tacls = (self.policy in (5, ...
'Clear any cached permissions or accessible-queries'
def clear_cache(self):
self.permission_cache = {} self.query_cache = {}
'Check whether permission-relevant settings have changed during the request, and clear the cache if so.'
def check_settings(self):
clear_cache = False settings = current.deployment_settings record_approval = settings.get_auth_record_approval() if (record_approval != self.record_approval): clear_cache = True self.record_approval = record_approval strict_ownership = settings.get_security_strict_ownership() if ...
'Define permissions table, invoked by AuthS3.define_tables()'
def define_table(self, migrate=True, fake_migrate=False):
table_group = self.auth.settings.table_group if (table_group is None): table_group = 'integer' if (not self.table): db = current.db db.define_table(self.tablename, Field('group_id', table_group), Field('controller', length=64), Field('function', length=512), Field('tablename', length...
'Update an ACL @param group: the ID or UID of the auth_group this ACL applies to @param c: the controller @param f: the function @param t: the tablename @param record: the record (as ID or Row with ID) @param oacl: the ACL for the owners of the specified record(s) @param uacl: the ACL for all other users @param entity:...
def update_acl(self, group, c=None, f=None, t=None, record=None, oacl=None, uacl=None, entity=None, delete=False):
ANY = 'any' unrestricted = (entity == ANY) if unrestricted: entity = None table = self.table if (not table): return None s3 = current.response.s3 if ('restricted_tables' in s3): del s3['restricted_tables'] self.clear_cache() if ((c is None) and (f is None) and...
'Delete an ACL @param group: the ID or UID of the auth_group this ACL applies to @param c: the controller @param f: the function @param t: the tablename @param record: the record (as ID or Row with ID) @param entity: restrict this ACL to the records owned by this entity (pe_id), specify "any" for any entity'
def delete_acl(self, group, c=None, f=None, t=None, record=None, entity=None):
return self.update_acl(group, c=c, f=f, t=t, record=record, entity=entity, delete=True)
'Get the entity/group/user owning a record @param table: the table @param record: the record ID (or the Row, if already loaded) @note: if passing a Row, it must contain all available ownership fields (id, owned_by_user, owned_by_group, realm_entity), otherwise the record will be re-loaded by this function. @return: tup...
def get_owners(self, table, record):
realm_entity = None owner_group = None owner_user = None record_id = None DEFAULT = (None, None, None) if (table and (not hasattr(table, '_tablename'))): table = current.s3db.table(table) if (not table): return DEFAULT ownership_fields = ('realm_entity', 'owned_by_group',...
'Check whether the current user owns the record @param table: the table or tablename @param record: the record ID (or the Row if already loaded) @param owners: override the actual record owners by a tuple (realm_entity, owner_group, owner_user) @return: True if the current user owns the record, else False'
def is_owner(self, table, record, owners=None, strict=False):
auth = self.auth user_id = None sr = auth.get_system_roles() if (auth.user is not None): user_id = auth.user.id session = current.session roles = [sr.ANONYMOUS] if (session.s3 is not None): roles = (session.s3.roles or roles) if (sr.ADMIN in roles): return True ...
'Returns a query to select the records in table owned by user @param table: the table @param user: the current auth.user (None for not authenticated) @param use_realm: use realms @param realm: limit owner access to these realms @param no_realm: don\'t include these entities in role realms @return: a web2py Query instan...
def owner_query(self, table, user, use_realm=True, realm=None, no_realm=None):
OUSR = 'owned_by_user' OGRP = 'owned_by_group' OENT = 'realm_entity' if (realm is None): realm = [] no_realm = (set() if (no_realm is None) else set(no_realm)) query = None if (user is None): if hasattr(table, '_tablename'): tablename = original_tablename(table) ...
'Returns a query to select the records owned by one of the entities. @param table: the table @param entities: list of entities @return: a web2py Query instance, or None if no query can be constructed'
def realm_query(self, table, entities):
OENT = 'realm_entity' query = None if (entities and ('ANY' not in entities) and (OENT in table.fields)): public = (table[OENT] == None) if (len(entities) == 1): query = ((table[OENT] == entities[0]) | public) else: query = (table[OENT].belongs(entities) | publ...
'Returns a list of the realm entities which a user can access for the given table. @param tablename: the tablename @param method: the method @return: a list of pe_ids or None (for no restriction)'
def permitted_realms(self, tablename, method='read'):
if (not self.entity_realm): return auth = self.auth sr = auth.get_system_roles() user = auth.user if auth.is_logged_in(): realms = user.realms if (sr.ADMIN in realms): return None delegations = user.delegations else: realms = Storage({sr.ANONYM...
'Check whether a record has been approved or not @param table: the table @param record: the record or record ID @param approved: True = check if approved, False = check if unapproved'
def approved(self, table, record, approved=True):
if (('approved_by' not in table.fields) or (not self.requires_approval(table))): return approved if isinstance(record, (Row, dict)): if ('approved_by' not in record): record_id = record[table._id] record = None else: record_id = record record = None ...
'Check whether a record has not been approved yet @param table: the table @param record: the record or record ID'
def unapproved(self, table, record):
return self.approved(table, record, approved=False)
'Check whether record approval is required for a table @param table: the table (or tablename)'
@classmethod def requires_approval(cls, table):
settings = current.deployment_settings if settings.get_auth_record_approval(): if (type(table) is Table): tablename = original_tablename(table) else: tablename = table tables = settings.get_auth_record_approval_required_for() if (tables is not None): ...
'Set the default approver for new records in table @param table: the table @param force: whether to force approval for tables which require manual approval'
@classmethod def set_default_approver(cls, table, force=False):
APPROVER = 'approved_by' if (APPROVER in table): approver = table[APPROVER] else: return settings = current.deployment_settings auth = current.auth tablename = original_tablename(table) if (not settings.get_auth_record_approval()): if (auth.s3_logged_in() and auth.use...
'Check permission to access a record with method @param method: the access method (string) @param c: the controller name (falls back to current request) @param f: the function name (falls back to current request) @param t: the table or tablename @param record: the record or record ID (None for any record)'
def has_permission(self, method, c=None, f=None, t=None, record=None):
if isinstance(method, (list, tuple)): for m in method: if self.has_permission(m, c=c, f=f, t=t, record=record): return True return False else: method = [method] if (record == 0): record = None auth = self.auth if auth.override: retu...
'Returns a query to select the accessible records for method in table. @param method: the method as string or a list of methods (AND) @param table: the database table or table name @param c: controller name (falls back to current request) @param f: function name (falls back to current request)'
def accessible_query(self, method, table, c=None, f=None, deny=True):
if (not hasattr(table, '_tablename')): tablename = table error = AttributeError(('undefined table %s' % tablename)) table = current.s3db.table(tablename, db_only=True, default=error) if (not isinstance(method, (list, tuple))): method = [method] ALL_RECORDS = (table._id ...
'Return a URL only if accessible by the user, otherwise False - used for Navigation Items @param c: the controller @param f: the function @param p: the permission (defaults to READ) @param t: the tablename (defaults to <c>_<f>) @param a: the application name @param args: the URL arguments @param vars: the URL variables...
def accessible_url(self, c=None, f=None, p=None, t=None, a=None, args=[], vars={}, anchor='', extension=None, env=None):
if (c != 'static'): settings = current.deployment_settings if (not settings.has_module(c)): return False if (t is None): t = ('%s_%s' % (c, f)) table = current.s3db.table(t) if (not table): t = None if (not p): p = 'read' permitted ...
'Action upon insufficient permissions'
def fail(self):
if (self.format == 'html'): if self.auth.s3_logged_in(): current.session.error = self.INSUFFICIENT_PRIVILEGES redirect(self.homepage) else: current.session.error = self.AUTHENTICATION_REQUIRED redirect(self.loginpage) elif self.auth.s3_logged_in():...
'Find all applicable ACLs for the specified situation for the specified realms and delegations @param racl: the required ACL @param realms: the realms @param delegations: the delegations @param c: the controller name, falls back to current request @param f: the function name, falls back to current request @param t: the...
def applicable_acls(self, racl, realms=None, delegations=None, c=None, f=None, t=None, entity=[]):
if (not self.use_cacls): return None else: acls = {} if realms: roles = set(realms.keys()) if delegations: for role in delegations: roles.add(role) else: return acls db = current.db table = self.table c = (c or self.controll...
'Checks whether a page is restricted (=whether ACLs are to be applied) @param c: controller name @param f: function name'
def page_restricted(self, c=None, f=None):
modules = current.deployment_settings.modules page = ('%s/%s' % (c, f)) if (page in self.unrestricted_pages): return False elif ((c not in modules) or ((c in modules) and (not modules[c].restricted))): return False return True
'Check whether access to a table is restricted @param t: the table name or Table'
def table_restricted(self, t=None):
s3 = current.response.s3 if (not ('restricted_tables' in s3)): table = self.table query = (((table.deleted != True) & (table.controller == None)) & (table.function == None)) rows = current.db(query).select(table.tablename, groupby=table.tablename) s3.restricted_tables = [row.tabl...
'List of modules to hide from the main menu'
def hidden_modules(self):
hidden_modules = [] if self.use_cacls: sr = self.auth.get_system_roles() modules = current.deployment_settings.modules restricted_modules = [m for m in modules if modules[m].restricted] roles = [] if (current.session.s3 is not None): roles = (current.session.s...
'Checks whether ownership can be required to access records in this table (this may not apply to every record in this table). @param method: the method as string or a list of methods (AND) @param table: the database table or table name @param c: controller name (falls back to current request) @param f: function name (f...
def ownership_required(self, method, table, c=None, f=None):
if (not self.use_cacls): if (self.policy in (1, 2)): return False else: return True if (not hasattr(table, '_tablename')): tablename = table table = current.s3db.table(tablename) if (not table): raise AttributeError(('undefined table...
'Remove any cached permissions for a record. This can be necessary in methods which change the status of the record (e.g. approval). @param table: the table @param record_id: the record ID'
def forget(self, table=None, record_id=None):
if (table is None): self.permission_cache = {} return permissions = self.permission_cache if (not permissions): return if hasattr(table, '_tablename'): tablename = original_tablename(table) else: tablename = table for key in list(permissions.keys()): ...
'Constructor @param tablename: the name of the audit table @param migrate: migration setting @note: this defines the audit table'
def __init__(self, tablename='s3_audit', migrate=True, fake_migrate=False):
settings = current.deployment_settings audit_read = settings.get_security_audit_read() audit_write = settings.get_security_audit_write() if ((not audit_read) and (not audit_write)): self.table = None return db = current.db if (tablename not in db): db.define_table(tablena...
'Audit @param method: Method to log, one of "create", "update", "read", "list" or "delete" @param prefix: the module prefix of the resource @param name: the name of the resource (without prefix) @param form: the form @param record: the record ID @param representation: the representation format'
def __call__(self, method, prefix, name, form=None, record=None, representation='unknown'):
table = self.table if (not table): return True if (method in ('list', 'read')): audit = current.deployment_settings.get_security_audit_read() elif (method in ('create', 'update', 'delete')): audit = current.deployment_settings.get_security_audit_write() else: return T...
'Provide a Human-readable representation of Audit records - currently unused @param record: the record IDs'
def represent(self, records):
table = self.table if isinstance(records, int): limit = 1 query = (table.id == records) else: limit = len(records) query = table.id.belongs(records) records = current.db(query).select(table.tablename, table.method, table.user_id, table.old_value, table.new_value, limitby=...
'Apply role manager'
def apply_method(self, r, **attr):
method = self.method if (method == 'list'): output = self._list(r, **attr) elif (method in ('read', 'create', 'update')): output = self._edit(r, **attr) elif (method == 'delete'): output = self._delete(r, **attr) elif ((method == 'roles') and (r.name == 'user')): outp...
'List roles/permissions'
def _list(self, r, **attr):
if r.id: return self._edit(r, **attr) output = dict() if r.interactive: T = current.T db = current.db response = current.response resource = self.resource auth = current.auth options = auth.permission.PERMISSION_OPTS NONE = auth.permission.NONE...
'Create/update role'
def _edit(self, r, **attr):
output = dict() request = self.request session = current.session db = current.db T = current.T CACL = T('Module Permissions') FACL = T('Function Permissions') TACL = T('Table Permissions') CANCEL = T('Cancel') auth = current.auth permission = auth.permission acl_...
'Delete role'
def _delete(self, r, **attr):
session = current.session request = self.request T = current.T auth = current.auth if r.interactive: if r.record: role = r.record role_id = role.id role_name = role.role if (role.protected or role.system): session.error = ('%s ...
'Get a SELECT of person entities for realm assignment'
def _entity_select(self):
T = current.T s3db = current.s3db auth = current.auth system_roles = auth.get_system_roles() has_role = auth.s3_has_role is_admin = has_role(system_roles.ADMIN) if is_admin: all_entities = OPTION(T('All Entities'), _value=0) else: all_entities = '' select = SELECT(...
'Get a representation dict for a list of pe_ids @param entities: the pe_ids of the entities'
def _entity_represent(self, entities):
T = current.T pe_ids = [e for e in entities if ((e is not None) and (e != 0))] if pe_ids: representation = current.s3db.pr_get_entities(pe_ids=pe_ids) else: representation = Storage() representation[None] = T('Default Realm') representation[0] = T('All Entities') return...
'Generates a SELECT tag, with OPTIONs grouped by OPTGROUPs @param field: the field needing the widget @param value: value @param options: list @param options: a list of tuples, each either (label, value) or (label, {options}) @param attributes: any other attributes to be applied @return: SELECT object'
@classmethod def widget(cls, field, value, options, **attributes):
default = dict(value=value) attr = cls._attributes(field, default, **attributes) select_items = [] for option in options: if isinstance(option[1], dict): items = [(v, k) for (k, v) in option[1].items()] if (not items): continue items.sort() ...
'Constructor'
def __init__(self, *args, **kwargs):
super(S3EntityRoleManager, self).__init__(*args, **kwargs) self.realm = self.get_realm() self.realm_users = current.s3db.pr_realm_users(self.realm) self.roles = {} self.modules = self.get_modules() self.acls = self.get_access_levels() for (module_uid, module_label) in self.modules.items(): ...
'Plug-in OrgAdmin Role Managers when appropriate @param r: the S3Request @param entity: override target entity (default: r.tablename) @param record_id: specify target record ID (only for OU\'s)'
@classmethod def set_method(cls, r, entity=None, record_id=None):
s3db = current.s3db auth = current.auth if ((not current.deployment_settings.get_auth_entity_role_manager()) or (auth.user is None)): return False sr = auth.get_system_roles() realms = (auth.user.realms or Storage()) ORG_ADMIN = sr.ORG_ADMIN admin = (sr.ADMIN in realms) org_admin...
''
def apply_method(self, r, **attr):
if ((self.method == 'roles') and (r.tablename in (self.ENTITY_TYPES + ['pr_person']))): context = self.get_context_data(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD) current.response.view = 'admin/manage_roles.html' return context
'@todo: description? @return: dictionary for the view # All the possible roles "roles": { "staff_reader": { "module": { "uid": "staff", "label": "Staff" # The roles currently assigned to users for entit(y/ies) "assigned_roles": { "1": [ "staff_reader", "project_editor", "pagination_list": [ "User One", "1" # The object...
def get_context_data(self, r, **attr):
T = current.T self.entity = self.get_entity() self.user = self.get_user() self.assigned_roles = self.get_assigned_roles() self.foreign_object = self.get_foreign_object() form = self.get_form() form.vars.update(self.get_form_vars()) if form.accepts(r.post_vars, current.session): b...
'Returns the realm (list of pe_ids) that this user can manage or raises a permission error if the user is not logged in'
def get_realm(self):
auth = current.auth system_roles = auth.get_system_roles() ORG_ADMIN = system_roles.ORG_ADMIN ADMIN = system_roles.ADMIN if auth.user: realms = auth.user.realms else: auth.permission.fail() if (ADMIN in realms): return realms[ADMIN] elif (ORG_ADMIN in realms): ...
'This returns an OrderedDict of modules with their uid as the key, e.g., {hrm: "Human Resources",} @return: OrderedDict'
def get_modules(self):
return current.deployment_settings.get_auth_role_modules()
'This returns an OrderedDict of access levels and their uid as the key, e.g., {reader: "Reader",} @return: OrderedDict'
def get_access_levels(self):
return current.deployment_settings.get_auth_access_levels()
'If an entity ID is provided, the dict will be the users with roles assigned to that entity. The key will be the user IDs. If a user ID is provided, the dict will be the entities the user has roles for. The key will be the entity pe_ids. If both an entity and user ID is provided, the dict will be the roles assigned to ...
def get_assigned_roles(self, entity_id=None, user_id=None):
if ((not entity_id) and (not user_id)): raise RuntimeError('Not enough arguments') mtable = current.auth.settings.table_membership gtable = current.auth.settings.table_group utable = current.auth.settings.table_user query = (((((mtable.deleted != True) & (gtable.deleted != True)) & (gt...
'Contructs the role form @return: SQLFORM'
def get_form(self):
fields = self.get_form_fields() form = SQLFORM.factory(table_name='roles', _id='role-form', _action='', _method='POST', *fields) return form
'@todo: description? @return: list of Fields'
def get_form_fields(self):
fields = [] requires = IS_EMPTY_OR(IS_IN_SET(self.acls.keys(), labels=self.acls.values())) for (module_uid, module_label) in self.modules.items(): field = Field(module_uid, label=module_label, requires=requires) fields.append(field) return fields
'Get the roles currently assigned for a user/entity and put it into a Storage object for the form @return: Storage() to pre-populate the role form'
def get_form_vars(self):
form_vars = Storage() fo = self.foreign_object roles = self.roles if (fo and (fo['id'] in self.assigned_roles)): for role in self.assigned_roles[fo['id']]: mod_uid = roles[role]['module']['uid'] acl_uid = roles[role]['acl']['uid'] form_vars[mod_uid] = acl_uid ...
'Update the users roles on entity based on the selected roles in before and after @param user_id: id (pk) of the user account to modify @param entity_id: id of the pentity to modify roles for @param before: list of role_uids (current values for the user) @param after: list of role_uids (new values from the admin)'
def update_roles(self, user_id, entity_id, before, after):
auth = current.auth assign_role = auth.s3_assign_role withdraw_role = auth.s3_withdraw_role for role_uid in before: if (role_uid not in after): withdraw_role(user_id, role_uid, entity_id) for role_uid in after: if ((role_uid != 'None') and (role_uid not in before)): ...
'Override to set the context from the perspective of an entity @return: dictionary for view'
def get_context_data(self, r, **attr):
context = super(S3OrgRoleManager, self).get_context_data(r, **attr) context['foreign_object_label'] = current.T('Users') return context
'We are on an entity (org/office) so we can fetch the entity details from the request record. @return: dictionary containing the ID and name of the entity'
def get_entity(self):
entity = dict(id=int(self.request.record.pe_id)) entity['name'] = current.s3db.pr_get_entities(pe_ids=[entity['id']], types=self.ENTITY_TYPES)[entity['id']] return entity
'The edit parameter @return: dictionary containing the ID and username/email of the user account.'
def get_user(self):
user = self.request.get_vars.get('edit', None) if user: user = dict(id=int(user), name=self.objects.get(int(user), None)) return user
'We are on an entity so our target is a user account. @return: dictionary with ID and username/email of user account'
def get_foreign_object(self):
return self.user
'Override to get assigned roles for this entity @return: dictionary with user IDs as the keys.'
def get_assigned_roles(self):
assigned_roles = super(S3OrgRoleManager, self).get_assigned_roles return assigned_roles(entity_id=self.entity['id'])
'Override the standard method so we can add the user-selection field to the list. @return: list of Fields'
def get_form_fields(self):
T = current.T fields = super(S3OrgRoleManager, self).get_form_fields() if (not self.user): assigned_roles = self.assigned_roles realm_users = Storage([(k, v) for (k, v) in self.realm_users.items() if (k not in assigned_roles)]) nonrealm_users = Storage([(k, v) for (k, v) in self.obje...
'Constructor'
def __init__(self, *args, **kwargs):
super(S3PersonRoleManager, self).__init__(*args, **kwargs) self.objects = current.s3db.pr_get_entities(types=self.ENTITY_TYPES)
'Override to set the context from the perspective of a person @return: dictionary for view'
def get_context_data(self, r, **attr):
context = super(S3PersonRoleManager, self).get_context_data(r, **attr) context['foreign_object_label'] = current.T('Organizations / Teams / Facilities') return context
'An entity needs to be specified with the "edit" query string parameter. @return: dictionary with pe_id and name of the org/office.'
def get_entity(self):
entity = self.request.get_vars.get('edit', None) if entity: entity = dict(id=int(entity), name=self.objects.get(int(entity), None)) return entity
'We are on a person record so we need to find the associated user account. @return: dictionary with ID and username/email of the user account'
def get_user(self):
settings = current.auth.settings utable = settings.table_user ptable = current.s3db.pr_person_user pe_id = int(self.request.record.pe_id) userfield = settings.login_userfield query = ((ptable.pe_id == pe_id) & (ptable.user_id == utable.id)) record = current.db(query).select(utable.id, utable...
'We are on a user/person so we want to target an entity (org/office)'
def get_foreign_object(self):
return self.entity
'@todo: description? @return: dictionary of assigned roles with entity pe_id as the keys'
def get_assigned_roles(self):
user_id = self.user['id'] return super(S3PersonRoleManager, self).get_assigned_roles(user_id=user_id)
'Return a list of fields, including a field for selecting a realm entity (such as an organisation or office). @return: list of Fields'
def get_form_fields(self):
s3db = current.s3db fields = super(S3PersonRoleManager, self).get_form_fields() if (not self.entity): options = s3db.pr_get_entities(pe_ids=self.realm, types=self.ENTITY_TYPES, group=True) nice_name = s3db.table('pr_pentity').instance_type.represent filtered_options = [] for ...
'Apply Merge methods @param r: the S3Request @param attr: dictionary of parameters for the method handler @return: output object to send to the view'
def apply_method(self, r, **attr):
output = dict() auth = current.auth system_roles = auth.get_system_roles() if (not auth.s3_has_role(system_roles.ADMIN)): r.unauthorized() if (r.method == 'deduplicate'): if (r.http in ('GET', 'POST')): if ('remove' in r.get_vars): remove = (r.get_vars['re...
'Bookmark the current record for de-duplication @param r: the S3Request @param attr: the controller parameters for the request'
def mark(self, r, **attr):
s3 = current.session.s3 DEDUPLICATE = self.DEDUPLICATE if (DEDUPLICATE not in s3): bookmarks = s3[DEDUPLICATE] = Storage() else: bookmarks = s3[DEDUPLICATE] record_id = str(self.record_id) if record_id: tablename = self.tablename if (tablename not in bookmarks): ...
'Remove a record from the deduplicate list @param r: the S3Request @param attr: the controller parameters for the request'
def unmark(self, r, **attr):
s3 = current.session.s3 DEDUPLICATE = self.DEDUPLICATE success = current.xml.json_message() if (DEDUPLICATE not in s3): return success else: bookmarks = s3[DEDUPLICATE] tablename = self.tablename if (tablename not in bookmarks): return success else: record...
'Get a bookmark link for a record in order to embed it in the view, also renders a link to the duplicate bookmark list to initiate the merge process from @param r: the S3Request @param tablename: the table name @param record_id: the record ID'
@classmethod def bookmark(cls, r, tablename, record_id):
auth = current.auth system_roles = auth.get_system_roles() if (not auth.s3_has_role(system_roles.ADMIN)): return '' if (r.component and (not r.component.multiple)): return '' s3 = current.session.s3 DEDUPLICATE = cls.DEDUPLICATE remove = (((DEDUPLICATE in s3) and (tablename i...
'Renders a list of all currently duplicate-bookmarked records in this resource, with option to select two and initiate the merge process from here @param r: the S3Request @param attr: the controller attributes for the request'
def duplicates(self, r, **attr):
s3 = current.response.s3 session_s3 = current.session.s3 resource = self.resource tablename = self.tablename if (r.http == 'POST'): return self.merge(r, **attr) record_ids = [] DEDUPLICATE = self.DEDUPLICATE if (DEDUPLICATE in session_s3): bookmarks = session_s3[DEDUPLICA...
'Merge form for two records @param r: the S3Request @param **attr: the controller attributes for the request @note: this method can always only be POSTed, and requires both "selected" and "mode" in post_vars, as well as the duplicate bookmarks list in session.s3'
def merge(self, r, **attr):
T = current.T session = current.session response = current.response output = dict() tablename = self.tablename s3 = session.s3 DEDUPLICATE = self.DEDUPLICATE if (DEDUPLICATE in s3): bookmarks = s3[DEDUPLICATE] if (tablename in bookmarks): record_ids = bookmark...
'Runs the onvalidation routine for this table, and maps form fields and errors to regular keys @param tablename: the table name @param form: the FORM'
@classmethod def onvalidation(cls, tablename, form):
(ORIGINAL, DUPLICATE, KEEP) = (cls.ORIGINAL, cls.DUPLICATE, cls.KEEP) if form.vars[KEEP.d]: prefix = ('%s_' % DUPLICATE) else: prefix = ('%s_' % ORIGINAL) data = Storage() for key in form.vars: if key.startswith(prefix): fname = key.split('_', 1)[1] da...
'Initialize all IS_NOT_IN_DB to allow override of both original and duplicate value @param field: the Field @param o: the original value @param d: the duplicate value'
@staticmethod def init_requires(field, o, d):
allowed_override = [str(o), str(d)] requires = field.requires if (field.unique and (not requires)): field.requires = IS_NOT_IN_DB(current.db, str(field), allowed_override=allowed_override) else: if (not isinstance(requires, (list, tuple))): requires = [requires] for r...