Esempio n. 1
0
def fix_permissions() :

    for u in permissions_failures_for(ed) :
        if u.username=='anon' :
            continue

        try :
            sc = u.get_security_context()
            print "tags ",sc.get_tags_for_interface('User.Viewer')
            sl = u.get_slider_level('User.Viewer')
        except Exception, e:
            print "ERROR"
            print e
            continue

        su = secure_wrap(u,ed)
        print "ed's access",su._interfaces
    
        try:
            su.username 
        except Exception :
            print "**excluded**"
            forbidden.add(u)
            sc.move_slider(all_members.get_ref(),'User.Viewer',skip_validation=True,no_user=True)
    
    
        sp = secure_wrap(u.get_profile(),ed)
        try :
            print "ed's access to profile",sp._interfaces
            sp.username
        except Exception :
            print "*** profile excluded"
            sc.move_slider(all_members.get_ref(),'Profile.Viewer',skip_validation=True,no_user=True)
Esempio n. 2
0
    def test_interfaces(self) :
        
        u = User(username='******', email_address='*****@*****.**')
        u.save()

        phil = User(username='******', email_address='*****@*****.**')
        phil.save()

        kx, created = TgGroup.objects.get_or_create(group_name='kingsX', display_name='Hub Kings Cross', level='member', user=u)
       
        caroline = User(username='******', email_address='*****@*****.**')
        caroline.save()
        all_members = get_all_members_group()
        all_members.add_member(caroline)

        carolines_kx_secure = secure_wrap(kx, caroline)
        #since caroline is only a site members she should be able to get the Viewer interface on TgGroup and OurPost, and Join TgGroup, but nothing else.
        carolines_kx_secure.about
        carolines_kx_secure.place
        carolines_kx_secure.join

        #
        def try_create_post(secure_kx):
            return secure_kx.create_OurPost(title='another post', body="Here's what", creator=caroline)
        self.assertRaises(PlusPermissionsNoAccessException, try_create_post, carolines_kx_secure)

        def view_attribute(sec_object, attr_name):
            getattr(carolines_kx_secure, attr_name)
        def edit_attribute(sec_object, attr_name, val):
            setattr(carolines_kx_secure, attr_name, val)

        self.assertRaises(PlusPermissionsReadOnlyException, edit_attribute, carolines_kx_secure, 'about', "Bernhard Lietar's Future of Money")
        self.assertRaises(PlusPermissionsNoAccessException, view_attribute, carolines_kx_secure, 'invite_member')
        kx.add_member(caroline)
        #now caroline can now also add blog posts to KX secure 
        carolines_kx_secure = secure_wrap(kx, caroline)
        blog = try_create_post(carolines_kx_secure)
        self.assertEquals(blog.__class__, SecureWrapper)
        
        blog.title = "blah"
        blog.body = "test"
        self.assertEquals(blog.title, "blah")
        self.assertEquals(blog.body, "test")
        
        phils_blog_secure = secure_wrap(blog, phil)
        self.assertRaises(PlusPermissionsReadOnlyException, edit_attribute, phils_blog_secure, "title", "Phils Blog")

        self.assertRaises(PlusPermissionsReadOnlyException, edit_attribute, carolines_kx_secure, "about", "Bernhard Lietar's Future of Money")
        kx.get_admin_group().add_member(caroline)
        carolines_kx_secure = secure_wrap(kx, caroline)        
        carolines_kx_secure.about = "Bernhard Lietar's Future of Money"
Esempio n. 3
0
def get_site(user):
    from apps.plus_permissions.interfaces import secure_wrap

    ss = Site.objects.all()
    if len(ss) > 0:
        return secure_wrap(ss[0], user)
    s = Site()
    s.save()

    admin = get_all_members_group().get_admin_group()
    # permission-wise, the site lives under the all_members_admin group
    s.acquires_from(admin)

    return secure_wrap(s, user)
Esempio n. 4
0
def get_site(user):
    from apps.plus_permissions.interfaces import secure_wrap

    ss = Site.objects.all()
    if len(ss) > 0:
        return secure_wrap(ss[0], user)
    s = Site()
    s.save()

    admin = get_all_members_group().get_admin_group()
    # permission-wise, the site lives under the all_members_admin group
    s.acquires_from(admin)

    return secure_wrap(s, user)
Esempio n. 5
0
def rss_explore(request, tag_string, s_type=None):
    from apps.plus_lib.redis_lib import redis
    feed_type = 'rss2.0'  # XXX decide how to send this as parameter to link
    key = "feed:" + feed_type + ":" + tag_string
    if redis.exists(key):
        return HttpResponse(redis.get(key), mimetype="application/xhtml+xml")
    else:
        feed = Rss201rev2Feed(
            title=settings.SITE_NAME + " : " + tag_string,
            link='http://' + settings.DOMAIN_NAME +
            reverse('explore_filtered_feed', args=(tag_string, )),
            description=_("Items tagged with %s" % tag_string))
        # XXX decide how to parameterize which feed type, title, description, link

        form = SearchForm(request.GET)
        if form.is_valid():
            search, order = set_search_order(request, form)
        else:
            search = ''
            order = ''

        side_search = side_search_args('', '')

        if s_type:
            search_types = narrow_search_types(s_type)
        else:
            search_types = get_search_types()

        head_title = settings.EXPLORE_NAME
        listing_args_dict = listing_args('explore',
                                         'explore_filtered',
                                         tag_string=tag_string,
                                         search_terms=search,
                                         multitabbed=True,
                                         order=order,
                                         template_base="site_base.html",
                                         search_type_label=head_title)
        search_dict = plus_search(listing_args_dict['tag_filter'], search,
                                  search_types, order)

        for item_ref in search_dict['All']:
            item = item_ref.obj
            item = secure_wrap(item, request.user)

            try:
                feed.add_item(title=item.get_display_name(),
                              link=item.get_url(),
                              description=item.get_description(),
                              author_name=item.get_author_name(),
                              author_copyright=item.get_author_copyright(),
                              pubdate=item.get_created_date(),
                              **(item.get_feed_extras()))
            except PlusPermissionsNoAccessException, e:
                pass

        feed_string = feed.writeString('utf-8')
        # uncomment the following when we start to cache
        #redis.set(key,feed_string)
        #redis.expire(key,60*60*1) # sets expire every 1 hour
        return HttpResponse(feed_string, mimetype="application/xhtml+xml")
Esempio n. 6
0
 def traced_wrap(self, user):
     # convenient way to trace an attempted secure_wrap
     obj = self.get_target()
     from apps.plus_permissions.interfaces import secure_wrap
     import ipdb
     ipdb.set_trace()
     so = secure_wrap(obj, user)
Esempio n. 7
0
    def update_followers(self, source, item) :            
        from apps.plus_permissions.interfaces import secure_wrap
        for f in Following.objects.followers_of(source) :
            # test permission
            secure_item = secure_wrap(item,f)
            if secure_item.has_interface('FeedItem.Viewer') :
                key = feed_for_key(f)
                redis.lpush(key,item.id)

        # if we mention someone in tweet ... add it to their queue and forward them a mail
        if '@' in item.short :   
            match = reply_rex.match(item.short)

            if match :
                replieds = User.objects.filter(username=match.group(2))
                if replieds :
                    replied = replieds[0]
                    key = feed_for_key(replied)
                    redis.lpush(key,item.id)
                    expanded = '\n\n%s'%item.expanded if (item.expanded and item.expanded != item.short) else ''
                    click = u'%s : %s' % (_('Follow this link to the item'),
                                          ('http://%s%s'%(settings.DOMAIN_NAME,
                                                          reverse('feed_item',args=[int(item.id)])
                                                          )
                                           )
                                          )
                    msg = u"""%s %s %s

%s%s

%s
"""% (source.get_display_name(), 'has replied to you on', settings.SITE_NAME_SHORT, item.short, expanded, click)
                    replied.email_user(u'%s %s' %(_('Message from'),source.get_display_name()), msg, settings.SUPPORT_EMAIL)

        return item
Esempio n. 8
0
 def traced_wrap(self, user) :
     # convenient way to trace an attempted secure_wrap
     obj = self.get_target()
     from apps.plus_permissions.interfaces import secure_wrap
     import ipdb
     ipdb.set_trace()
     so = secure_wrap(obj,user)
Esempio n. 9
0
def permissions_failures_for(viewer, cls=User, interface='User.Viewer'):
    """ Generates an iteration of users who viewer can't see"""
    from apps.plus_permissions.interfaces import secure_wrap
    for x in cls.objects.all().order_by('-id'):
        try:
            sx = secure_wrap(x, viewer)
            if interface not in sx._interfaces:
                yield x
        except Exception, e:
            print x.id, x, e
Esempio n. 10
0
 def f(self, creator, **kwargs):
     resource = child_type(**kwargs)
     resource.save()
     # now create its security_context etc.
     resource.acquires_from(self)
     ref = resource.get_ref()
     ref.creator = creator
     ref.save()
     assert resource.get_creator() == creator
     return secure_wrap(resource, creator)
Esempio n. 11
0
def secure(request, cls, resource_id, required_interfaces=None, with_interfaces=None, all_or_any='ALL'):
    """all_or_any refers to whether the object must have 'ALL' or 'ANY' 
    """
    resource = get_resource(cls, resource_id)
    if not resource:
        return None
    sec_resource = secure_wrap(resource, request.user, interface_names=with_interfaces)
    if required_interfaces:
        check_interfaces(sec_resource, cls, required_interfaces, all_or_any)
    return sec_resource
Esempio n. 12
0
def permissions_failures_for(viewer, cls=User, interface='User.Viewer') :
    """ Generates an iteration of users who viewer can't see"""
    from apps.plus_permissions.interfaces import secure_wrap
    for x in cls.objects.all().order_by('-id') :
        try :
            sx = secure_wrap(x, viewer)
            if interface not in sx._interfaces :
                yield x
        except Exception, e :
            print x.id, x, e
Esempio n. 13
0
def get_links_for(target, context):
    target_type = ContentType.objects.get_for_model(target)
    secured_links = [
        secure_wrap(obj,
                    context.get('request').user,
                    interface_names=['Manager', 'Viewer'])
        for obj in Link.objects.filter(target_object_id=target.id,
                                       target_content_type=target_type)
    ]
    return secured_links
Esempio n. 14
0
def secure(request, cls, resource_id, required_interfaces=None, with_interfaces=None, all_or_any='ALL'):
    """all_or_any refers to whether the object must have 'ALL' or 'ANY' of the required interfaces
    """
    resource = get_resource(cls, resource_id)
    if not resource:
        return None
    sec_resource = secure_wrap(resource, request.user, interface_names=with_interfaces)
    if required_interfaces:
        check_interfaces(sec_resource, cls, required_interfaces, all_or_any)
    return sec_resource
Esempio n. 15
0
def rss_explore(request, tag_string, s_type=None) :
    from apps.plus_lib.redis_lib import redis
    feed_type = 'rss2.0' # XXX decide how to send this as parameter to link
    key = "feed:"+feed_type+":"+tag_string
    if redis.exists(key) :
        return HttpResponse(redis.get(key),mimetype="application/xhtml+xml")
    else :
        feed = Rss201rev2Feed(title=settings.SITE_NAME+" : "+tag_string,
                              link='http://'+settings.DOMAIN_NAME+reverse('explore_filtered_feed',args=(tag_string,)),
                              description=_("Items tagged with %s" % tag_string) )
        # XXX decide how to parameterize which feed type, title, description, link

        form = SearchForm(request.GET)
        if form.is_valid():
            search, order = set_search_order(request, form)
        else:
            search = ''
            order = ''

        side_search = side_search_args('', '')

        if s_type :
            search_types = narrow_search_types(s_type)
        else :
            search_types = get_search_types()

        head_title = settings.EXPLORE_NAME
        listing_args_dict = listing_args('explore', 'explore_filtered', tag_string=tag_string, search_terms=search, multitabbed=True, order=order, template_base="site_base.html", search_type_label=head_title)
        search_dict = plus_search(listing_args_dict['tag_filter'], search, search_types, order)

        for item_ref in search_dict['All']:
            item = item_ref.obj
            item=secure_wrap(item,request.user)

            try :
                feed.add_item(title=item.get_display_name(), 
                          link=item.get_url(), 
                          description=item.get_description(),
                          author_name=item.get_author_name(),
                          author_copyright=item.get_author_copyright(),
                          pubdate=item.get_created_date(),
                          **(item.get_feed_extras())
                          )
            except PlusPermissionsNoAccessException, e :
                pass


        feed_string = feed.writeString('utf-8')
        # uncomment the following when we start to cache
        #redis.set(key,feed_string)
        #redis.expire(key,60*60*1) # sets expire every 1 hour
        return HttpResponse(feed_string, mimetype="application/xhtml+xml")
Esempio n. 16
0
 def f(self, creator, **kwargs) :
     # check for validity of the entered name
     if hasattr(child_type, 'check_name') and 'name' in kwargs and 'in_agent' in kwargs:
         child_type.check_name(kwargs['name'], kwargs['in_agent'])
     resource = child_type(**kwargs)
     resource.save()
     # now create its security_context etc.
     resource.acquires_from(self)
     ref = resource.get_ref()
     ref.creator = creator
     ref.save()
     assert(resource.get_creator()==creator)
     return secure_wrap(resource, creator)
Esempio n. 17
0
 def secure_results_set(self, resources, p_user, interface_names=None, required_interfaces=None, all_or_any='ALL'):
     wrapped_resources = []
     for resource in resources:
         wrapped = secure_wrap(resource, p_user, interface_names=interface_names)
         if required_interfaces:
             try:
                 check_interfaces(wrapped, resource.__class__, required_interfaces=required_interfaces, all_or_any=all_or_any)
                 wrapped_resources.append(wrapped)
             except PlusPermissionsNoAccessException:
                 pass
         else:
             wrapped_resources.append(wrapped)
     return wrapped_resources
Esempio n. 18
0
 def f(self, creator, **kwargs):
     # check for validity of the entered name
     if hasattr(child_type,
                'check_name') and 'name' in kwargs and 'in_agent' in kwargs:
         child_type.check_name(kwargs['name'], kwargs['in_agent'])
     resource = child_type(**kwargs)
     resource.save()
     # now create its security_context etc.
     resource.acquires_from(self)
     ref = resource.get_ref()
     ref.creator = creator
     ref.save()
     assert (resource.get_creator() == creator)
     return secure_wrap(resource, creator)
Esempio n. 19
0
def list_of_applications(request, template_name="plus_contacts/applicant_list.html"):
    applications= Application.objects.plus_filter(request.user, status=PENDING)


    # filter the application so that if they're ALSO applications to groups, 
    # I only see the ones where I have permission to accept them to their chosen group
    # XXX there's probably a more efficient way of doing this filtering
    groups = set([])
    for application in applications :
        if application.group :
            group = secure_wrap(application.group, request.user)
            try : 
                group.add_member
                groups.add(group)
            except PlusPermissionsNoAccessException, e :
                pass # can't add member to this group so we don't care about it
Esempio n. 20
0
    def get_from_permissioned(self, source, user) :
        from apps.plus_permissions.interfaces import secure_wrap

        rets = []
        # absurdly inefficient
        count = 0
        for fi in self.get_from(source) :
            sfi = secure_wrap(fi,user) 
            try :
                sfi.source
                rets.append(sfi)
                count=count+1
                if count > 50 : 
                    break
            except Exception, e:
                pass
Esempio n. 21
0
def recreate_feed(key, agent) :
    """ Recreates the queue of feed items for agent """
    from apps.plus_permissions.interfaces import secure_wrap
    subscriptions = Following.objects.followed_by(agent)

    ids = set([])
    for sub in subscriptions :
        for item in FeedItem.feed_manager.get_from(sub) :
            secure_item = secure_wrap(item, agent) 
            if secure_item.has_interface('FeedItem.Viewer') :
                ids.add(item.id)

    pipe = redis.pipeline()
    for item_id in ids :
        pipe.lpush(key, item_id)
    pipe.execute()
    return ids
Esempio n. 22
0
def plus_links(context, target_class, target_id, errors=None, form_data=None) :
    """links should be checked for the view permission
    """
    target_cls = ContentType.objects.get(id=target_class).model_class()
    target = target_cls.objects.get(id=target_id)
    target = secure_wrap(target, context.get('request').user, interface_names=['CreateLink'])
    links = get_links_for(target, context)
    links = [(link, hasattr(link, 'delete')) for link in links]
    can_create = hasattr(target, 'create_Link')
    return {
        'links' :links,
        'target':target,
        'can_create':can_create,
        'target_id':target_id,
        'target_class_name':target_cls.__name__,
        'errors':errors,
        'form_data':form_data
        }
Esempio n. 23
0
def plus_links(context, target_class, target_id, errors=None, form_data=None):
    """links should be checked for the view permission
    """
    target_cls = ContentType.objects.get(id=target_class).model_class()
    target = target_cls.objects.get(id=target_id)
    target = secure_wrap(target,
                         context.get('request').user,
                         interface_names=['CreateLink'])
    links = get_links_for(target, context)
    links = [(link, hasattr(link, 'delete')) for link in links]
    can_create = hasattr(target, 'create_Link')
    return {
        'links': links,
        'target': target,
        'can_create': can_create,
        'target_id': target_id,
        'target_class_name': target_cls.__name__,
        'errors': errors,
        'form_data': form_data
    }
Esempio n. 24
0
 def secure_results_set(self,
                        resources,
                        p_user,
                        interface_names=None,
                        required_interfaces=None,
                        all_or_any='ALL'):
     wrapped_resources = []
     for resource in resources:
         wrapped = secure_wrap(resource,
                               p_user,
                               interface_names=interface_names)
         if required_interfaces:
             try:
                 check_interfaces(wrapped,
                                  resource.__class__,
                                  required_interfaces=required_interfaces,
                                  all_or_any=all_or_any)
                 wrapped_resources.append(wrapped)
             except PlusPermissionsNoAccessException:
                 pass
         else:
             wrapped_resources.append(wrapped)
     return wrapped_resources
Esempio n. 25
0
def site_create_group(self, user, **kwargs):
    from apps.plus_permissions.types.TgGroup import get_or_create
    group, created =  get_or_create(user=user, **kwargs)
    return secure_wrap(group, user)
Esempio n. 26
0
def site_create_group(self, user, **kwargs):
    from apps.plus_permissions.types.TgGroup import get_or_create
    group, created =  get_or_create(user=user, **kwargs)
    return secure_wrap(group, user)
Esempio n. 27
0
def f() :
    u = User.objects.get(username='******')
    g = TgGroup.objects.get(group_name='all_members')

    print u, g
    secure_wrap(g,u)
Esempio n. 28
0
def secure_wrap_for(self, user=User, diagnose=False):
    return secure_wrap(self, user, diagnose=diagnose)
Esempio n. 29
0
 def plus_get(self, p_user, **kwargs):
     a = super(self.__class__, self).get(**kwargs)
     return secure_wrap(a, p_user)
Esempio n. 30
0
 def plus_get(self, p_user, interface_names=None, **kwargs):
     a = super(self.__class__, self).get(**kwargs)
     return secure_wrap(a, p_user, interface_names=interface_names)
Esempio n. 31
0
 def test(x):
     sx = secure_wrap(x, agent)
     return sx.has_interface('FeedItem.Viewer')
Esempio n. 32
0
def f():
    u = User.objects.get(username='******')
    g = TgGroup.objects.get(group_name='all_members')

    print u, g
    secure_wrap(g, u)
Esempio n. 33
0
from apps.plus_permissions.interfaces import secure_wrap

from datetime import datetime

uu = User.objects.get(username='******')
gg = TgGroup.objects.get(id=456)

import ipdb
from apps.plus_lib.redis_lib import redis, CACHE_ON

redis.flushall()
print redis.dbsize()

print
print "Start"
ss = secure_wrap(gg, uu)
print gg.has_member(uu)
print ss._interfaces

print
print "Joining"
gg.add_member(uu)
ss = secure_wrap(gg, uu)
print gg.has_member(uu)
print ss._interfaces

print
print "Leaving"
gg.remove_member(uu)
ipdb.set_trace()
ss = secure_wrap(gg, uu)
Esempio n. 34
0
def get_links_for(target, context):
    target_type = ContentType.objects.get_for_model(target)
    secured_links = [secure_wrap(obj, context.get('request').user, interface_names=['Manager', 'Viewer']) for obj in Link.objects.filter(target_object_id=target.id, target_content_type=target_type)]
    return secured_links
Esempio n. 35
0
 def plus_get(self, p_user, interface_names=None, **kwargs) :
     a = super(self.__class__, self).get(**kwargs)
     return secure_wrap(a, p_user, interface_names=interface_names)
Esempio n. 36
0
from datetime import datetime

uu = User.objects.get(username='******')
gg = TgGroup.objects.get(id=456)

import ipdb
from apps.plus_lib.redis_lib import redis, CACHE_ON

redis.flushall()
print redis.dbsize()


print
print "Start"
ss = secure_wrap(gg,uu)
print gg.has_member(uu)
print ss._interfaces

print
print "Joining"
gg.add_member(uu)
ss = secure_wrap(gg,uu)
print gg.has_member(uu)
print ss._interfaces

print
print "Leaving"
gg.remove_member(uu)
ipdb.set_trace()
ss = secure_wrap(gg,uu)
Esempio n. 37
0
def secure_wrap_for(self, user=User, diagnose=False) :
    return secure_wrap(self, user, diagnose=diagnose)