本文整理汇总了Python中pyramid.security.effective_principals函数的典型用法代码示例。如果您正苦于以下问题:Python effective_principals函数的具体用法?Python effective_principals怎么用?Python effective_principals使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了effective_principals函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: user
def user(request):
from pyramid.security import authenticated_userid, effective_principals
return {
"authenticated_userid": authenticated_userid(request),
"effective_principals": effective_principals(request),
}
示例2: reset
def reset(self):
if self.request.params.get('came_from') is not None:
came_from = self.request.params.get('came_from')
else:
came_from = self.request.route_url('map_view')
# Make sure the user is not logged in
principals = effective_principals(self.request)
if "system.Authenticated" in principals:
return HTTPFound(location=came_from)
username = self.request.params.get("username")
user = DBSession.query(User).filter(User.username == username).first()
if user is None:
msg = _(u"No registered user found with this email address.")
return render_to_response(getTemplatePath(self.request, 'users/reset_password_form.mak'), {
'came_from': came_from,
'warning': msg
}, self.request)
new_password = user.set_new_password()
body = render(getTemplatePath(self.request, 'emails/reset_password.mak'), {
'user': user.username,
'new_password': new_password
}, self.request)
self._send_email([user.email], _(u"Password reset"), body)
return render_to_response(getTemplatePath(self.request, 'users/reset_password_success.mak'), {}, self.request)
示例3: get_user_id
def get_user_id(request):
principals = effective_principals(request)
for principal in principals:
if type(principal) is unicode:
user = user_service.get_user_by_login(principal)
return user.id
return None
示例4: report_year_week
def report_year_week(request):
""" The leaderboard for a specific week of a specific year. """
frame = 'week'
## TODO: how to make sure this doesn't break?
year = int(request.matchdict.get('year'))
week = int(request.matchdict.get('weeknumber'))
# Get the week using the number of week
start = date(year, 1, 1) + timedelta(weeks=week - 1)
# Get the start of the week (as January 1st might not have been a Monday)
start = get_start_week(start.year, start.month, start.day)
stop = start + timedelta(days=6)
user_to_rank = request.db._make_leaderboard(
start=start,
stop=stop,
)
return dict(
auth_principals=effective_principals(request),
user_to_rank=user_to_rank,
start_date=start,
stop_date=stop,
frame=frame,
)
示例5: report_year_month_day
def report_year_month_day(request):
""" The leaderboard for a specific month of a specific year. """
frame = 'day'
## TODO: how to make sure this doesn't break?
year = int(request.matchdict.get('year'))
month = int(request.matchdict.get('month'))
day = int(request.matchdict.get('day'))
start = date(year, month, day)
stop = date(year, month, day) + timedelta(days=1)
user_to_rank = request.db._make_leaderboard(
start=start,
stop=stop,
)
return dict(
auth_principals=effective_principals(request),
user_to_rank=user_to_rank,
start_date=start,
stop_date=stop,
frame=frame,
)
示例6: get_members_batch
def get_members_batch(community, request, size=10):
mods = list(community.moderator_names)
members = list(community.member_names - community.moderator_names)
any = list(community.member_names | community.moderator_names)
principals = effective_principals(request)
searcher = ICatalogSearch(community)
total, docids, resolver = searcher(interfaces=[IProfile],
limit=size,
name={'query': any,
'operator': 'or'},
allowed={'query': principals,
'operator': 'or'},
)
mod_entries = []
other_entries = []
for docid in docids:
model = resolver(docid)
if model is not None:
if model.__name__ in mods:
mod_entries.append(model)
else:
other_entries.append(model)
return (mod_entries + other_entries)[:size]
示例7: __call__
def __call__(self, context, request):
req_principals = effective_principals(request)
if is_nonstr_iter(req_principals):
rpset = set(req_principals)
if self.val.issubset(rpset):
return True
return False
示例8: outstanding_principals
def outstanding_principals(permission, context, request):
"""Returns a list of sets of principals, where the attainment of all of the
principals in any one of the sets would be sufficient to grant the current
user (``request.user``) the `permission` in the given `context`."""
# TODO be able to determine a context based on a route name
if has_permission(permission, context, request):
return []
principals = principals_allowed_by_permission(context, permission)
if not principals:
# the permission must not exist at all within this context
return ['__unattainable__']
effective = set(effective_principals(request))
outstanding = []
for p in principals:
if p in TRUST_MAP:
for alternative_principals in TRUST_MAP[p]:
diff = set(alternative_principals) - effective
if len(diff) > 0 and 'auth:insecure' not in diff:
outstanding.append(diff)
else:
outstanding.append(set([p]))
return outstanding
示例9: login
def login(context, request):
email = urllib.unquote(request.matchdict['email'])
user = User.get(request.db_session, email)
# non-admin users cannot check if another user has permissions on a
# given instance
if authenticated_userid(request) != email and \
'admin' not in effective_principals(request):
return generate_empty_response(HTTPForbidden(), request, 403)
try:
# the domain could be an alias. We need the instance domain
domain = Alias.get(request.db_session,
request.params['domain'])\
.instance.domain
except NoResultFound:
domain = request.params['domain']
except KeyError:
log.error('No domain in request for users.login')
return generate_empty_response(HTTPForbidden(), request, 403)
instance = Instance.get_by_domain(request.db_session, domain)
if not user.can_access(instance):
log.error('%s cannot login on %s', email, domain)
return generate_empty_response(HTTPForbidden(), request, 403)
return user.to_dict()
示例10: get_my_communities
def get_my_communities(communities_folder, request, ignore_preferred=False):
# sorted by title
principals = effective_principals(request)
communities = {}
for name, role in get_community_groups(principals):
if name in communities:
continue
try:
community = communities_folder[name]
except KeyError:
continue
# Do not include any communities in any stage of being archived
if not getattr(community, 'archive_status', False):
communities[name] = (community.title, community)
communities = communities.values()
communities.sort()
communities = [ x[1] for x in communities ]
preferred = get_preferred_communities(communities_folder, request)
# if preferred list is empty show all instead of nothing
if preferred == []:
ignore_preferred = True
my_communities = []
for community in communities:
adapted = getMultiAdapter((community, request), ICommunityInfo)
if not ignore_preferred and preferred is not None \
and adapted.title in preferred:
my_communities.append(adapted)
if preferred is None or ignore_preferred:
my_communities.append(adapted)
return my_communities
示例11: class_view
def class_view(request):
id = request.matchdict['id']
cl = session.query(Class).filter_by(id = id).first()
if not cl:
raise HTTPNotFound()
roles = effective_principals(request)
login = roles[2]
teacher = session.query(User).filter(cl.teacher_id == User.id).first()
isAdministrator = isDirector = isAssistant = False
if 'administrator' in roles:
isAdministrator = True
if 'director' in roles:
isDirector = True
if 'assistant' in roles:
isAssistant = True
return {
'cl': cl,
'teacher': teacher,
'isAdministrator': isAdministrator,
'isDirector': isDirector,
'isAssistant': isAssistant,
}
示例12: login_form
def login_form(self):
"""
Renders the simple login form
"""
# Prevent endless loops
if self.request.referer is not None\
and self.request.referer != self.request.route_url('reset_form')\
and not self.request.referer.startswith(
self.request.route_url('login_form')):
came_from = self.request.referer
else:
came_from = self.request.route_url('map_view')
# Make sure the user is not logged in
principals = effective_principals(self.request)
if "system.Authenticated" in principals:
return HTTPFound(location=came_from)
return render_to_response(
get_customized_template_path(self.request, 'login_form.mak'),
{
'came_from': came_from,
'warning': None
},
self.request)
示例13: _get_criteria
def _get_criteria(request):
principals = effective_principals(request)
principals = [x for x in principals if not x.startswith('system.')]
# Check to see if we're asking for only "my" communities.
filterby = request.params.get('filter', '')
# cookie must be set even if param is empty or non-existent, to make
# the no-filter button sticky.
#header = ('Set-Cookie', '%s=%s; Path=/' % (_FILTER_COOKIE, str(filterby)))
request.cookies[_FILTER_COOKIE] = filterby
request.response.set_cookie(_FILTER_COOKIE, str(filterby), path='/')
if filterby == 'mycommunities':
principals = [x for x in principals if not x.startswith('group.Karl')]
if filterby == 'mycontent':
created_by = authenticated_userid(request)
elif filterby.startswith('profile:'):
created_by = filterby[len('profile:'):]
elif filterby.startswith('community:'):
created_by = None
community = filterby[len('community:'):]
prefix = 'group.community:%s' % community
principals = [x for x in principals if x.startswith(prefix)]
else:
created_by = None
return principals, created_by
示例14: allows
def allows(self, principals, permission=None):
""" ``principals`` may either be 1) a sequence of principal
indentifiers, 2) a single principal identifier, or 3) a Pyramid
request, which indicates that all the effective principals implied by
the request are used.
``permission`` may be ``None`` if this index is configured with
only a single permission. Otherwise a permission name must be passed
or an error will be raised.
"""
permissions = self.discriminator.permissions
if permission is None:
if len(permissions) > 1:
raise ValueError('Must pass a permission')
else:
permission = list(permissions)[0]
else:
if permissions is not None and not permission in permissions:
raise ValueError(
'This index does not support the %s '
'permission' % (permission,)
)
if IRequest.providedBy(principals):
principals = effective_principals(principals)
elif not is_nonstr_iter(principals):
principals = (principals,)
principals = [ get_principal_repr(p) for p in principals ]
values = [(principal, permission) for principal in principals]
return hypatia.query.Any(self, values)
示例15: access_key_add
def access_key_add(context, request):
crypt_context = request.registry[CRYPT_CONTEXT]
if 'access_key_id' not in request.validated:
request.validated['access_key_id'] = generate_user()
if 'user' not in request.validated:
request.validated['user'], = [
principal.split('.', 1)[1]
for principal in effective_principals(request)
if principal.startswith('userid.')
]
password = None
if 'secret_access_key_hash' not in request.validated:
password = generate_password()
request.validated['secret_access_key_hash'] = crypt_context.encrypt(password)
result = collection_add(context, request)
if password is None:
result['secret_access_key'] = None
else:
result['secret_access_key'] = password
result['access_key_id'] = request.validated['access_key_id']
result['description'] = request.validated['description']
return result