Пример #1
0
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]
Пример #2
0
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
Пример #3
0
 def __init__(self, context, request):
     self._request = request
     self._context = context
     self._types = request.registry[TYPES]
     self._search_base = normalize_query(request)
     self._result = {
         '@context': request.route_path('jsonld_context'),
         'filters': [],
     }
     self._doc_types = request.params.getall('type')
     self._principals = effective_principals(request)
     self._elastic_search = request.registry[ELASTIC_SEARCH]
     self._es_index = RESOURCES_INDEX
     self._search_audit = request.has_permission('search_audit')
     self._search_term = prepare_search_term(request)
     self._request_cache = None
     self._facets = [
         ('type', {
             'title': 'Data Type'
         }),
     ]
     self.from_, self.size = get_pagination(request)
     from_, page_size = get_pagination(request)
     self._from_ = from_
     self._size = page_size
Пример #4
0
def user(request):
    from pyramid.security import authenticated_userid, effective_principals

    return {
        "authenticated_userid": authenticated_userid(request),
        "effective_principals": effective_principals(request),
    }
Пример #5
0
    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)
Пример #6
0
def get_images_batch(
        context,
        request,
        creator=None,  # 'My Recent' in imagedrawer
        community=None,  # 'This Community' in imagedrawer
        batch_start=0,
        batch_size=12,
        sort_index='creation_date',
        reverse=True,
        batcher=get_catalog_batch):  # For unit testing
    search_params = dict(
        interfaces=[
            IImage,
        ],
        allowed={
            'query': effective_principals(request),
            'operator': 'or'
        },
        sort_index=sort_index,
        reverse=reverse,
        batch_start=batch_start,
        batch_size=batch_size,
    )

    if creator is not None:
        search_params['creator'] = creator
    if community is not None:
        search_params['path'] = community

    return batcher(context, request, **search_params)
Пример #7
0
def recent_activity(context, request):
    community = find_community(context)
    if not community:
        return ''

    registry = request.registry
    community_path = resource_path(community)
    search = registry.getAdapter(context, ICatalogSearch)
    principals = effective_principals(request)
    recent_items = []
    num, docids, resolver = search(
        limit=10,
        path={'query': community_path},
        allowed={
            'query': principals,
            'operator': 'or'
        },
        sort_index='modified_date',
        reverse=True,
        interfaces=[ICommunityContent],
    )
    models = filter(None, map(resolver, docids))
    for model in models:
        adapted = registry.getMultiAdapter((model, request), IGridEntryInfo)
        recent_items.append(adapted)

    return {'recent_items': recent_items}
Пример #8
0
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
Пример #9
0
def archive_portlet(context, request):
    with context._p_jar._storage.ex_cursor() as cursor:
        community = find_community(context)
        community_cond = qbe.sql(context._p_jar, dict(community=community))
        cursor.execute(
            """
            select month, count(*) from (
              select substring(state->>'created' from 1 for 7) as month
              from newt natural join karlex
              where class_name = 'karl.content.models.blog.BlogEntry'
                and """ + community_cond + """
                and newt_can_view(state, %s)
              ) _
            group by month order by month desc
            """, (effective_principals(request), ))
        blog = find_interface(context, IBlog)
        return {
            'archive': [
                MonthlyActivity(
                    year, month, count,
                    request.resource_url(blog,
                                         query={
                                             'year': year,
                                             'month': month
                                         }))
                for (year, month, count) in ((month[:4], month[-2:], count)
                                             for month, count in cursor)
            ]
        }
Пример #10
0
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
Пример #11
0
def login(request):
    '''
    forbidden_view_config decorator indicates that this is the route to redirect to when an user
    has no access to a page
    '''

    # Get session id from cookie
    session_id = unauthenticated_userid(request)
    # Get roles
    principals = effective_principals(request)

    # Requests will be forwarded here when users aren't authorized to those pages
    # If they are unauthorized to those pages, they should have session id and principals
    # and, if there is a session id and principals, return 403
    # Here, we return 403 for users that has a role of None
    # This can be an user that has no role from IDP or has a role that we don't know of
    if Roles.get_invalid_role() in principals or (principals and session_id):
        write_security_event("Forbidden view being accessed",
                             SECURITY_EVENT_TYPE.WARN, session_id)
        return HTTPForbidden()

    # clear out the session if we found one in the cookie
    if session_id is not None:
        expire_session(session_id)

    handlers = [_handle_OAUTH2_Implicit_login_flow, _handle_SAML2_login_flow]
    for handler in handlers:
        response = handler(request)
        if response is not None:
            return response

    return HTTPForbidden()
Пример #12
0
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,
    )
Пример #13
0
def user_latest_meeting_entries(context, request, va, **kw):
    view = kw['view']
    query = {}
    # context is the user profile, but if within a meeting it's importat to preform a check
    # wether you're allowed to view entries
    # If the view that calls this is invoked outside a meeting, only admins and owners
    # will be able to view it.
    if request.meeting:
        query['path'] = resource_path(request.meeting)
        query['allowed_to_view'] = {
            'operator': 'or',
            'query': effective_principals(request)
        }
    else:
        query['path'] = resource_path(request.root)
    query['creator'] = context.userid
    query['type_name'] = {
        'query': ('Proposal', 'DiscussionPost'),
        'operator': 'ANY'
    }
    query['sort_index'] = 'created'
    query['reverse'] = True
    query['limit'] = 5
    response = dict(
        last_entries=view.catalog_search(resolve=True, **query),
        context=context,
    )
    return render(
        'voteit.core:templates/snippets/user_latest_meeting_entries.pt',
        response,
        request=request)
Пример #14
0
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,
    )
Пример #15
0
def all_forums_view(context, request):
    page_title = "Message Boards"
    api = TemplateAPI(context, request, page_title)

    # Don't use the forums folder as the starting point, use its
    # parent (the community) to allow recursion
    context_path = model_path(context.__parent__)

    searcher = ICatalogSearch(context)
    total, docids, resolver = searcher(
        interfaces=[ICommunity],
        path={'query': context_path, 'include_path': True},
        allowed={'query': effective_principals(request),
                 'operator': 'or'},
        sort_index='title',
    )

    community_data = []

    for docid in docids:
        community = resolver(docid)
        if community is not None:
            forum_data = get_forum_data(community, request)
            if forum_data:
                community_data.append({'title': community.title,
                                       'forum_data': forum_data})

    return render_to_response(
        'templates/all_forums.pt',
        {'api': api,
         'community_data': community_data},
        request=request
    )
Пример #16
0
def user_latest_meeting_entries(context, request, va, **kw):
    api = kw['api']
    query = {}
    #context is the user profile, but if within a meeting it's importat to preform a check
    #wether you're allowed to view entries
    #If the view that calls this is invoked outside a meeting, only admins and owners
    #will be able to view it.
    if api.meeting:
        query['path'] = resource_path(api.meeting)
        query['allowed_to_view'] = {
            'operator': 'or',
            'query': effective_principals(request)
        }
    else:
        query['path'] = resource_path(api.root)
    query['creators'] = context.userid
    query['content_type'] = {
        'query': ('Proposal', 'DiscussionPost'),
        'operator': 'or'
    }
    query['sort_index'] = 'created'
    query['reverse'] = True
    query['limit'] = 5
    response = dict(
        last_entries=api.get_metadata_for_query(**query),
        api=api,
        context=context,
        truncate=strip_and_truncate,
    )
    return render('../templates/snippets/user_latest_meeting_entries.pt',
                  response,
                  request=request)
Пример #17
0
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)
    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
Пример #18
0
    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)
Пример #19
0
 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
Пример #20
0
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()
Пример #21
0
def get_members_batch(community, request, size=10):
    mods = list(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]
Пример #22
0
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
Пример #23
0
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
Пример #24
0
def discover_community_members_json(context, request):
    """ Return users who share a community with the given user.

    Query string may include:

    - 'userid':  the user whose communities we enumerate (defaults to the
                 current user).
    """
    users = find_users(context)
    userid = request.GET.get('userid', None)
    if userid is None:
        userid = authenticated_userid(request)
        principals = effective_principals(request)
        communities = [x[0] for x in get_community_groups(principals)]
    else:
        info = users.get(userid)
        communities = [x[0] for x in get_community_groups(info['groups'])]
    c_groups = [(x,
                 _quippers_from_users(
                     context, request,
                     users.users_in_group('group.community:%s:members' % x)))
                for x in communities]
    return {
        'userid': userid,
        'members': dict(c_groups),
    }
Пример #25
0
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,
        }
Пример #26
0
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,
    }
Пример #27
0
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
Пример #28
0
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})
Пример #29
0
def userid(instance, subschema):
    request = get_current_request()
    principals = effective_principals(request)
    for principal in principals:
        if principal.startswith('userid.'):
            return principal[7:]
    return NO_DEFAULT
Пример #30
0
 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
Пример #31
0
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
Пример #32
0
def userid(property, subschema):
    request = get_current_request()
    principals = effective_principals(request)
    for principal in principals:
        if principal.startswith('userid.'):
            return principal[7:]
    return NO_DEFAULT
Пример #33
0
def related_communities_ajax_view(context, request):
    assert ICommunity.providedBy(context), str(type(context))

    related = []
    principals = effective_principals(request)
    searcher = ICatalogSearch(context)
    search = ' OR '.join(context.title.lower().split())
    total, docids, resolver = searcher(
        interfaces=[ICommunity],
        limit=5,
        reverse=True,
        sort_index="modified_date",
        texts=search,
        allowed={
            'query': principals,
            'operator': 'or'
        },
    )
    for docid in docids:
        model = resolver(docid)
        if model is not None:
            if model is not context:
                adapted = getMultiAdapter((model, request), IGridEntryInfo)
                related.append(adapted)

    return {'items': related}
Пример #34
0
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
Пример #35
0
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
Пример #36
0
def builder(request):
    if authenticated_userid(request):
        awarded_assertions = request.db.get_assertions_by_email(
            authenticated_userid(request))
    else:
        awarded_assertions = None

    # set came_from so we can get back home after openid auth.
    request.session['came_from'] = request.route_url('builder')

    # get default creator field
    default_creator = None
    user = request.db.get_person(person_email=authenticated_userid(request))
    if user:
        default_creator = user.nickname or user.email

    badge_yaml = None
    if request.POST:
        badge_yaml = generate_badge_yaml(request.POST)

    return dict(
        auth_principals=effective_principals(request),
        awarded_assertions=awarded_assertions,
        default_creator=default_creator,
        badge_yaml=badge_yaml,
    )
Пример #37
0
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,
        }
Пример #38
0
    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)
Пример #39
0
 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
Пример #40
0
    def recent_items(self):
        if self._recent_items is None:
            community = find_interface(self.context, ICommunity)
            if community is not None:
                community_path = resource_path(community)
                search = getAdapter(self.context, ICatalogSearch)
                principals = effective_principals(self.request)
                self._recent_items = []
                num, docids, resolver = search(
                    limit=10,
                    path={'query': community_path},
                    allowed={
                        'query': principals,
                        'operator': 'or'
                    },
                    sort_index='modified_date',
                    reverse=True,
                    interfaces=[ICommunityContent],
                )
                models = filter(None, map(resolver, docids))
                for model in models:
                    adapted = getMultiAdapter((model, self.request),
                                              IGridEntryInfo)
                    self._recent_items.append(adapted)

        return self._recent_items
Пример #41
0
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("Communities that begin with '%s'" % 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 = 'Error: %s' % e
Пример #42
0
def builder(request):
    if authenticated_userid(request):
        awarded_assertions = request.db.get_assertions_by_email(
                                 authenticated_userid(request))
    else:
        awarded_assertions = None

    # set came_from so we can get back home after openid auth.
    request.session['came_from'] = request.route_url('builder')

    # get default creator field
    default_creator = None
    user = request.db.get_person(person_email=authenticated_userid(request))
    if user:
        default_creator = user.nickname or user.email

    badge_yaml = None
    if request.POST:
        badge_yaml = generate_badge_yaml(request.POST)

    return dict(
        auth_principals=effective_principals(request),
        awarded_assertions=awarded_assertions,
        default_creator=default_creator,
        badge_yaml=badge_yaml,
    )
Пример #43
0
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
        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
Пример #44
0
    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)
Пример #45
0
    def __init__(self, context, request, page_title=None):
        self.settings = dict(get_settings(context))
        self.settings.update(self.config_settings)
        self.site = site = find_site(context)
        self.context = context
        self.request = request
        self.userid = authenticated_userid(request)
        self.app_url = app_url = request.application_url
        self.profile_url = app_url + '/profiles/%s' % self.userid
        self.here_url = self.context_url = resource_url(context, request)
        self.view_url = resource_url(context, request, request.view_name)
        self.read_only = not is_normal_mode(request.registry)
        self.static_url = get_static_url(request)
        self.resource_devel_mode = is_resource_devel_mode()
        self.browser_upgrade_url = request.registry.settings.get(
            'browser_upgrade_url', '')

        # this data will be provided for the client javascript
        self.karl_client_data = {}

        # Provide a setting in the INI to fully control the entire URL
        # to the static.  This is when the proxy runs a different port
        # number, or to "pipeline" resources on a different URL path.
        full_static_path = self.settings.get('full_static_path', False)
        if full_static_path:
            if '%d' in full_static_path:
                # XXX XXX note self._start_time is needed... and not _start_time
                # XXX XXX since this was a trivial bug, there is chance that
                # XXX XXX this actually never runs! TODO testing???
                full_static_path = full_static_path % self._start_time
            self.static_url = full_static_path
        self.page_title = page_title
        self.system_name = self.title = self.settings.get('title', 'KARL')
        self.user_is_admin = 'group.KarlAdmin' in effective_principals(request)
        self.can_administer = has_permission('administer', site, request)
        self.can_email = has_permission('email', site, request)
        self.admin_url = resource_url(site, request, 'admin.html')
        date_format = get_user_date_format(context, request)
        self.karl_client_data['date_format'] = date_format
        # XXX XXX XXX This will never work from peoples formish templates
        # XXX XXX XXX (edit_profile and derivates) because, in those form
        # XXX XXX XXX controllers, the api is instantiated from __init__,
        # XXX XXX XXX where request.form is still unset!!! (From all other
        # XXX XXX XXX formcontrollers the api is instantiated from __call__,
        # XXX XXX XXX which is why this works. A chicken-and-egg problem, really.
        if hasattr(request, 'form') and getattr(request.form, 'errors', False):
            # This is a failed form submission request, specify an error message
            self.error_message = u'Please correct the indicated errors.'

        self.site_announcements = getattr(self.site, "site_announcements", [])
        profiles = find_profiles(self.site)
        profile = profiles is not None and profiles.get(self.userid,
                                                        None) or None
        self.unseen_site_announcements = []
        if profile is not None and hasattr(profile, "_seen_announcements") \
                and hasattr(site, "site_announcements"):
            for item in site.site_announcements:
                if item['hash'] not in profile._seen_announcements:
                    self.unseen_site_announcements.append(item)
Пример #46
0
    def sem_auth_control(self):

        """
        Se o usuário está logado e veio parar aqui quer dizer que ele não tem autorização para acessar
        alguma view. então devo retornar uma mensagem dizendo que ele não tem permissão, ou uma página de não permissão.
        Se o usuário não estiver logado ele vai para a tela de login
        :return:
        """

        print("Sem auth control")
        print(effective_principals(self.request))
        if 'system.Authenticated' in effective_principals(self.request):
            print("Usuário sem permissão: %r" % self.logged_in)
            return HTTPUnauthorized() #mudar para HTTPFound e criar uma tela de não permissão.
        else:
            print("Usuário não logado. redirecionando para login")
            return HTTPFound(location=self.request.application_url + '/login') #redirecionado pra tela de login
Пример #47
0
def number_of_comments(forum, request):
    searcher = ICatalogSearch(forum)
    total, docids, resolver = searcher(
        interfaces=[IComment],
        path={'query': resource_path(forum)},
        allowed={'query': effective_principals(request), 'operator': 'or'},
        )
    return total
Пример #48
0
def get_recent_items_batch(community, request, size=10):
    batch = get_catalog_batch_grid(
        community, request, interfaces=[ICommunityContent],
        sort_index="modified_date", reverse=True, batch_size=size,
        path={'query': resource_path(community)},
        allowed={'query': effective_principals(request), 'operator': 'or'},
    )
    return batch
Пример #49
0
def get_recent_items_batch(community, request, size=10):
    batch = get_catalog_batch_grid(
        community, request, interfaces=[ICommunityContent],
        sort_index="modified_date", reverse=True, batch_size=size,
        path={'query': resource_path(community)},
        allowed={'query': effective_principals(request), 'operator': 'or'},
    )
    return batch
Пример #50
0
def get_catalog_events(context, request,
                       searchterm=None, year=None, month=None,
                       past_events=None):

    # Build up a query
    query = dict(
        path={'query': resource_path(context)},
        allowed={'query': effective_principals(request), 'operator': 'or'},
        interfaces=[ICalendarEvent],
        sort_index="start_date",
        reverse=True,
        use_cache=False,
        )

    if searchterm is not None:
        query['texts'] = searchterm

    if searchterm is not None and year is None and month is None:
        # all years, all months, don't add anything to the query
        pass
    elif year is not None or month is not None:
        if year is not None:
            year = int(year)
        else:
            # No year given, assume this year
            year = datetime.datetime.now().year

        if month is not None:
            month = int(month)
            last_day = calendar.monthrange(year, month)[1]
            first_moment = coarse_datetime_repr(
                datetime.datetime(year, month, 1))
            last_moment = coarse_datetime_repr(
                datetime.datetime(year, month, last_day, 23, 59, 59))

        else:
            # No month given, search entire year
            first_moment = coarse_datetime_repr(datetime.datetime(year, 1, 1))
            last_moment = coarse_datetime_repr(datetime.datetime(year+1, 1, 1))

        query['start_date'] = (None, last_moment)
        query['end_date'] = (first_moment, None)

    else:
        # Show either all future or all past events
        now = coarse_datetime_repr(datetime.datetime.now())
        if past_events:
            # Past; show the most recent first
            query['end_date'] = (None, now)
            query['reverse'] = True
        else:
            # Future; show the soonest first
            query['end_date'] = (now, None)
            query['reverse'] = False

    batch = get_catalog_batch_grid(context, request, **query)

    return batch
Пример #51
0
def index(request):

    n = 5 # n is the number of items displayed in each column.

    if authenticated_userid(request):
        awarded_assertions = request.db.get_assertions_by_email(
                                 authenticated_userid(request))
    else:
        awarded_assertions = None
    # set came_from so we can get back home after openid auth.
    request.session['came_from'] = request.route_url('home')

    persons_assertions = request.db.get_all_assertions().join(
                            m.Person).filter(
                            m.Person.opt_out == False)
    from collections import defaultdict
    top_persons = defaultdict(int) # person: assertion count
    for item in persons_assertions:
        top_persons[item.person] += 1

    top_persons_sorted = sorted(sorted(top_persons,
                                key=lambda person: person.id),
                                key=top_persons.get,
                                reverse=True)
    # Limit the sorted top persons to the top 10% and then take
    # a random sample of 5 persons from that pool.
    num_users_at_top = max(int(len(top_persons_sorted) * 0.1),
                           min(len(top_persons_sorted), 5))
    # This is not actually a sample yet, but it's about to be...
    top_persons_sample = top_persons_sorted[:num_users_at_top]
    try:
        top_persons_sample = random.sample(top_persons_sample, 5)
    except ValueError:
        # The sample is probably larger than the num of top users,
        # so let's just take all the users in the top 10%, in a
        # random order.
        random.shuffle(top_persons_sample)

    # Get latest awards.
    latest_awards = persons_assertions.order_by(
                    sa.desc(m.Assertion.issued_on)).limit(n).all()

    # Register our websocket handler callback
    if asbool(request.registry.settings['tahrir.use_websockets']):
        socket = make_websocket_handler(request.registry.settings)
        socket.display()

    return dict(
        auth_principals=effective_principals(request),
        latest_awards=latest_awards,
        newest_persons=request.db.get_all_persons().filter(
                        m.Person.opt_out == False).order_by(
                        sa.desc(m.Person.created_on)).limit(n).all(),
        top_persons=top_persons,
        top_persons_sample=top_persons_sample,
        awarded_assertions=awarded_assertions,
        moksha_socket=get_moksha_socket(request.registry.settings),
    )
Пример #52
0
def leaderboard(request):
    """ Render a top users view. """
    if authenticated_userid(request):
        awarded_assertions = request.db.get_assertions_by_email(
                                authenticated_userid(request))
    else:
        awarded_assertions = None

    # Get top persons.
    persons_assertions = request.db.get_all_assertions().join(m.Person)
    from collections import defaultdict
    top_persons = defaultdict(int) # person: assertion count
    for item in persons_assertions:
        top_persons[item.person] += 1

    # top_persons and top_persons_sorted contain all persons, ordered
    top_persons_sorted = sorted(sorted(top_persons,
                                key=lambda person: person.id),
                                key=top_persons.get,
                                reverse=True)

    # Get total user count.
    user_count = len(top_persons)

    if authenticated_userid(request):
        # Get rank.
        try:
            rank = top_persons_sorted.index(request.db.get_person(
                                person_email=authenticated_userid(
                                             request))) + 1
        except ValueError:
            rank = 0
        # Get percentile.
        try:
            percentile = (float(rank) / float(user_count)) * 100
        except ZeroDivisionError:
            percentile = 0

        # Get a list of nearby competetors (5 users above the current
        # user and 5 users ranked below).
        competitors = top_persons_sorted[max(rank - 3, 0):\
                                     min(rank + 2, len(top_persons_sorted))]

    else:
        rank = None
        percentile = None
        competitors = None

    return dict(
            auth_principals=effective_principals(request),
            awarded_assertions=awarded_assertions,
            top_persons=top_persons,
            top_persons_sorted=top_persons_sorted,
            rank=rank,
            user_count=user_count,
            percentile=percentile,
            competitors=competitors,
            )
Пример #53
0
def index(request):

    n = 5 # n is the number of items displayed in each column.

    if authenticated_userid(request):
        awarded_assertions = request.db.get_assertions_by_email(
                                 authenticated_userid(request))
    else:
        awarded_assertions = None
    # set came_from so we can get back home after openid auth.
    request.session['came_from'] = request.route_url('home')

    persons_assertions = request.db.get_all_assertions().join(
                            m.Person).filter(
                            m.Person.opt_out == False)
    from collections import defaultdict
    top_persons = defaultdict(int) # person: assertion count
    for item in persons_assertions:
        top_persons[item.person] += 1

    top_persons_sorted = sorted(sorted(top_persons,
                                key=lambda person: person.id),
                                key=top_persons.get,
                                reverse=True)
    # Limit the sorted top persons to the top 10% and then take
    # a random sample of 5 persons from that pool.
    num_users_at_top = max(int(len(top_persons_sorted) * 0.1),
                           min(len(top_persons_sorted), 5))
    # This is not actually a sample yet, but it's about to be...
    top_persons_sample = top_persons_sorted[:num_users_at_top]
    try:
        top_persons_sample = random.sample(top_persons_sample, 5)
    except ValueError:
        # The sample is probably larger than the num of top users,
        # so let's just take all the users in the top 10%, in a
        # random order.
        random.shuffle(top_persons_sample)

    # Get latest awards.
    latest_awards = persons_assertions.order_by(
                    sa.desc(m.Assertion.issued_on)).limit(n).all()

    # Register our websocket handler callback
    if asbool(request.registry.settings['tahrir.use_websockets']):
        socket = make_websocket_handler(request.registry.settings)
        socket.display()

    return dict(
        auth_principals=effective_principals(request),
        latest_awards=latest_awards,
        newest_persons=request.db.get_all_persons().filter(
                        m.Person.opt_out == False).order_by(
                        sa.desc(m.Person.created_on)).limit(n).all(),
        top_persons=top_persons,
        top_persons_sample=top_persons_sample,
        awarded_assertions=awarded_assertions,
        moksha_socket=get_moksha_socket(request.registry.settings),
    )
Пример #54
0
def get_recent_items_batch(community, request, size=10):
    batch = get_catalog_batch_grid(
        community, request, interfaces=[ICommunityContent],
        sort_index="modified_date", reverse=True, batch_size=size,
        community=community,
        can_view={'query': effective_principals(request), 'operator': 'or'},
        catalog_iface=ISQLCatalogSearch,
    )
    return batch
Пример #55
0
def show_communities_view(context, request):
    default = 'active'
    if 'groups.KarlAffiliate' in effective_principals(request):
        default = 'all'
    which = request.cookies.get(_VIEW_COOKIE, default)
    urlname = _VIEW_URL_LOOKUP[which]
    target = resource_url(context, request, urlname)
    response = HTTPFound(location=target)
    return response
Пример #56
0
def info(context, request):
    email = urllib.unquote(request.matchdict['email'])
    principals = effective_principals(request)

    # a "normal" user get info about itself.
    if not set(('admin', email)) & set(principals):
        return generate_empty_response(HTTPForbidden(), request, 403)

    return User.get(request.db_session, email).to_dict()
Пример #57
0
def user(request):
    from pyramid.security import (
        authenticated_userid,
        effective_principals,
    )
    return {
        'authenticated_userid': authenticated_userid(request),
        'effective_principals': effective_principals(request),
    }
Пример #58
0
def show_communities_view(context, request):
    default = 'active'
    if 'groups.KarlAffiliate' in effective_principals(request):
        default = 'all'
    which = request.cookies.get(_VIEW_COOKIE, default)
    urlname = _VIEW_URL_LOOKUP[which]
    target = resource_url(context, request, urlname)
    response = HTTPFound(location=target)
    return response