• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python security.effective_principals函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyramid.security.effective_principals函数的典型用法代码示例。如果您正苦于以下问题:Python effective_principals函数的具体用法?Python effective_principals怎么用?Python effective_principals使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了effective_principals函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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),
    }
开发者ID:katerose,项目名称:encoded,代码行数:7,代码来源:testing_views.py


示例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)
开发者ID:sinnwerkstatt,项目名称:lokp,代码行数:31,代码来源:login.py


示例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
开发者ID:jorgelf,项目名称:pyratest,代码行数:7,代码来源:security.py


示例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,
    )
开发者ID:echevemaster,项目名称:tahrir,代码行数:28,代码来源:views.py


示例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,
    )
开发者ID:echevemaster,项目名称:tahrir,代码行数:25,代码来源:views.py


示例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]
开发者ID:Falmarri,项目名称:karl,代码行数:25,代码来源:community.py


示例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
开发者ID:AndreaCrotti,项目名称:pyramid,代码行数:7,代码来源:predicates.py


示例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
开发者ID:eevee,项目名称:floof,代码行数:28,代码来源:authz.py


示例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()
开发者ID:asidev,项目名称:aybu-manager,代码行数:29,代码来源:users.py


示例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
开发者ID:araymund,项目名称:karl,代码行数:32,代码来源:communities.py


示例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,
        }
开发者ID:amarz121,项目名称:a2-computing,代码行数:25,代码来源:WorkingProject.py


示例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)
开发者ID:CDE-UNIBE,项目名称:lokp,代码行数:26,代码来源:login.py


示例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
开发者ID:hj91,项目名称:karl,代码行数:28,代码来源:contentfeeds.py


示例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)
开发者ID:Web5design,项目名称:substanced,代码行数:29,代码来源:indexes.py


示例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
开发者ID:rmoorman,项目名称:encoded,代码行数:28,代码来源:access_key.py


示例16: get_report_query

def get_report_query(report, request, letter=None):
    """Produce query parameters for a catalog search
    """
    if report is not None:
        kw = report.getQuery()
    else:
        kw = {}
        for k, v in request.GET.items():
            if k.startswith('category_') or k == 'groups':
                if ':' in v:
                    values, operator = v.split(':')
                else:
                    values, operator = v, 'or'
                kw[k] = {'query': values.split(','), 'operator': operator}
            elif k == 'is_staff':
                kw[k] = v.lower() in ('true', 't', 'yes', 'y', '1')
    principals = effective_principals(request)
    show_all_users = get_setting(report, "show_all_users")
    if not show_all_users:
        principals.remove("system.Authenticated")
        principals.remove("system.Everyone")
    kw['allowed'] = {'query': principals, 'operator': 'or'}
    if letter is None:
        letter = request.params.get('lastnamestartswith')
    if letter:
        kw['lastnamestartswith'] = letter.upper()
    body = request.params.get('body')
    if body:
        kw['texts'] = body.strip() + '*'
    return kw
开发者ID:lslaz1,项目名称:karl,代码行数:30,代码来源:peopledirectory.py


示例17: home_view

def home_view(request):
    roles = effective_principals(request)
    # login occurs in roles after 'system.Everyone' and 'system.Authenticated'
    login = roles[2]

    # Obtain user object and all class objects from database
    user = session.query(User).filter_by(username = login).first()
    classes = session.query(Class).all()

    # Determine values of remaining variables required by template
    isAdministrator = isTeacher = False
    interventions = classesTaught = []
    if 'administrator' in roles:
        isAdministrator = True
    elif 'teacher' in roles:
        isTeacher = True
        classesTaught = session.query(Class).filter_by(teacher_id=user.id).all()
	# Shows the 10 most recent interventions created
        interventions = session.query(Intervention).order_by(Intervention.id.desc()).limit(10).all()

    return {
        # Returns values required in templates
        'login' : login,
        'user' : user,
        'classes' : classes,
        'isAdministrator' : isAdministrator,
        'isTeacher' : isTeacher,
        'classesTaught' : classesTaught,
        'interventions': interventions,
        }
开发者ID:amarz121,项目名称:a2-computing,代码行数:30,代码来源:WorkingProject.py


示例18: students_view

def students_view(request):
    roles = effective_principals(request)
    # login occurs in roles after 'system.Everyone' and 'system.Authenticated'
    login = roles[2]
	
    # Locates user object with the same username as in 'effective_principals'
    user = session.query(User).filter_by(username = login).first()

    # List of all students in alphabetical order
    students = session.query(Student).order_by(Student.surname.asc(), Student.forename.asc(), Student.id.asc()).all()
    isAdministrator = isTeacher = False
    classesTaught = studentsTaught = []

    if 'administrator' in roles:
        isAdministrator = True
    if 'teacher' in roles:
        isTeacher = True
        # Finds all classes taught by the user
        classesTaught = session.query(Class).filter_by(teacher_id = user.id).all()
		
        # Use set comprehension to remove duplicate students
        setOfStudentsTaught = {st for cl in classesTaught for st in cl.students}
        # Use list comprehension to put in alphabetical order 
        studentsTaught = [st for st in students if st in setOfStudentsTaught]    

    return {
        'students' : students,
	'isAdministrator': isAdministrator,
	'isTeacher': isTeacher,
	'classesTaught': classesTaught,
	'studentsTaught': studentsTaught,
    }
开发者ID:amarz121,项目名称:a2-computing,代码行数:32,代码来源:WorkingProject.py


示例19: _show_communities_view_helper

def _show_communities_view_helper(context,
                                  request,
                                  prefix='',
                                  **kw
                                 ):
    # Grab the data for the two listings, main communities and portlet
    communities_path = resource_path(context)

    query = dict(
        sort_index='title',
        interfaces=[ICommunity],
        path={'query': communities_path, 'depth': 1},
        allowed={'query': effective_principals(request), 'operator': 'or'},
        **kw
        )

    qualifiers = []
    titlestartswith = request.params.get('titlestartswith')
    if titlestartswith:
        query['titlestartswith'] = (titlestartswith, titlestartswith)
        qualifiers.append(
                _(u"Communities that begin with '${titlestartswith}'",
                        mapping={'titlestartswith': titlestartswith}))

    body = request.params.get('body')
    if body:
        query['texts'] = body
        qualifiers.append('Search for "%s"' % body)

    error = None
    try:
        batch_info = get_catalog_batch_grid(context, request, **query)
    except ParseError, e:
        batch_info = {'entries': [], 'batching_required': False}
        error = _(u'Error: ${message}', mapping={'message': e})
开发者ID:gborelli,项目名称:localetest,代码行数:35,代码来源:communities.py


示例20: _add_view_to_spec

 def _add_view_to_spec(self, spec):
     principals = security.effective_principals(self.request)
     # Don't even bother modifying the spec if the user is in the superuser group.
     if 'group:superuser' in principals: return spec
     if spec is None: spec = {}
     spec['_view'] = {'$in': principals}
     return spec
开发者ID:eugeneai,项目名称:recms,代码行数:7,代码来源:folder.py



注:本文中的pyramid.security.effective_principals函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python security.forget函数代码示例发布时间:2022-05-27
下一篇:
Python security.authenticated_userid函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap