Beispiel #1
0
    def become_member(self, username, invited_by=None, accepted_by=None, password=None):
        """Either a user accepts an invitation or their application is accepted.
        XXX If application is accepted trigger an email with confirmation page to set password
        XXX if invitation is accepted by user then they go straight to set password page
        """
        u = create_user(username, self.email_address)
        if password:
            u.set_password(password)
        u.save()
        p = u.get_profile()
        p.first_name = self.first_name
        p.last_name = self.last_name
        p.email_address = self.email_address
        p.organisation = self.organisation
        p.location = self.location
        if invited_by:
            p.invited_by = invited_by
        if accepted_by:
            p.accepted_by = accepted_by
        h = p.get_host_info()
        h.find_out = self.find_out
        p.save()
        h.save()

        get_all_members_group().add_member(u)

        # do we want to delete the Contact if it becomes a User?
        
        # yes if this is merely a pending user, 
        # no if it's going to grow into a more sophisticated CRM system
        # self.delete()
        
        return u
Beispiel #2
0
def list_of_applications(request, resource_id=None, template_name="plus_contacts/applicant_list.html", **kwargs):
    group = resource_id
    all_members_group = get_all_members_group()
    if group == None or int(group) == all_members_group.id:
        group = get_all_members_group()
        title = settings.SITE_NAME
        applications = Application.objects.plus_filter(request.user, status=PENDING, group=group, interface_names=['Viewer', 'Accept', 'Reject'], required_interfaces=['Viewer', 'Accept'], all_or_any='ALL')
    else:
        applications = Application.objects.plus_filter(request.user, status=PENDING, group=group, interface_names=['Viewer', 'Accept', 'Reject'], required_interfaces=['Viewer', 'Accept'], all_or_any='ALL')
        title = TgGroup.objects.get(id=group).get_display_name()

    reject = False
    
    if len(applications):
        app = applications[0]
        try:
            app.reject

            reject = True
        except PlusPermissionsNoAccessException:
            pass

    return render_to_response(template_name, {
            'title': title,
            'applications' : applications,
            'reject':reject
            }, context_instance=RequestContext(request))
Beispiel #3
0
def user_post_create(user, permission_prototype='public') :
    
    user.save() # ensures our post_save signal is fired to create gen_ref, even if we came via syncer
    setup_user_security(user, permission_prototype)

    user.create_Profile(user,user=user)
    user.create_HostInfo(user,user=user)

    get_all_members_group().add_member(user)
    return user
Beispiel #4
0
def user_post_create(user, permission_prototype='public'):

    user.save(
    )  # ensures our post_save signal is fired to create gen_ref, even if we came via syncer
    setup_user_security(user, permission_prototype)

    user.create_Profile(user, user=user)
    user.create_HostInfo(user, user=user)

    get_all_members_group().add_member(user)
    return user
Beispiel #5
0
    def become_member(self,
                      username,
                      invited_by=None,
                      accepted_by=None,
                      password=None):
        """Either a user accepts an invitation or their application is accepted.
        XXX If application is accepted trigger an email with confirmation page to set password
        XXX if invitation is accepted by user then they go straight to set password page
        """
        u = create_user(username, self.email_address)
        if password:
            u.set_password(password)
        p = u.get_profile()
        p.first_name = self.first_name if self.first_name else username
        p.last_name = self.last_name
        p.email_address = self.email_address
        p.organisation = self.organisation
        p.post_or_zip = self.post_or_zip
        p.address = self.address
        p.country = self.country

        if accepted_by:
            p.accepted_by = accepted_by
        h = p.get_host_info()
        h.find_out = self.find_out
        p.save()
        h.save()

        u.is_active = True
        u.cc_messages_to_email = True

        u.save()

        self.user = u
        self.save()
        self.update_applications()
        self.update_invitations()
        for contact in Contact.objects.filter(
                email_address=self.email_address):
            contact.user = u
            contact.update_applications()
            contact.update_invitations()
        other_groups = u.groups.exclude(id=get_all_members_group().id)

        if other_groups.count() == 1:
            u.homehub = other_groups[0]
        else:
            u.homehub = get_all_members_group()
        u.save()

        return u
Beispiel #6
0
def group_post_create(group, user, permission_prototype=None):

    if not permission_prototype:
        permission_prototype = 'public'

    group.save(
    )  # ensures our post_save signal is fired to create gen_ref, even if we came via syncer

    if group.level == 'member':
        admin_group, created = TgGroup.objects.get_or_create(
            group_name=group.group_name + "_hosts",
            display_name=group.display_name + " Hosts",
            level='host',
            place=group.place,
            user=user,
            group_type='administrative',
            description="Admin Group for %s" % group.display_name,
        )

        setup_group_security(group, group, admin_group, user,
                             permission_prototype)

    elif group.level == 'host' or group.level == 'director':
        setup_group_security(group, group, group, user, 'private')

        from django.conf import settings
        if group.group_name != settings.VIRTUAL_HUB_NAME + '_hosts':
            site_admin = get_all_members_group().get_admin_group()
            group.add_member(site_admin)
            site_admin.flush_members_cache()
Beispiel #7
0
def group_post_create(group, user, permission_prototype=None) :

    if not permission_prototype :
        permission_prototype = 'public'

    group.save() # ensures our post_save signal is fired to create gen_ref, even if we came via syncer 

    if group.level == 'member':
        admin_group, created = TgGroup.objects.get_or_create(
            group_name=group.group_name + "_hosts", 
            display_name=group.display_name + " Hosts", 
            level='host',
            place=group.place,
            user=user, 
            group_type='administrative',
            description="Admin Group for %s" % group.display_name, 
            )

        setup_group_security(group, group, admin_group, user, permission_prototype)

    elif group.level == 'host' or group.level == 'director' :
        setup_group_security(group, group, group, user, 'private')

        from django.conf import settings
        if group.group_name != settings.VIRTUAL_HUB_NAME+'_hosts' :
            site_admin = get_all_members_group().get_admin_group()
            group.add_member(site_admin)
            site_admin.flush_members_cache()
Beispiel #8
0
    def test_become_member(self):
        u2 = get_admin_user()

        # now upgrade to a user
        u3 = self.ct.become_member('tom.salfield',
                                   invited_by=self.u,
                                   accepted_by=u2)
        self.assertEquals(u2.__class__, User)

        # the following commented test was to confirm that becoming a member deleted the Contact
        # as I'm not deleting contacts at the moment, this test is redundant
        # self.assertEquals(len(Contact.objects.filter(id=self.ct.id)), 0)

        p = u3.get_profile()
        self.assertEquals(p.first_name, self.ct.first_name)
        self.assertEquals(p.last_name, self.ct.last_name)
        self.assertEquals(p.email_address, self.ct.email_address)
        self.assertEquals(p.location, self.ct.location)
        self.assertEquals(p.get_host_info().find_out, self.ct.find_out)
        self.assertTrue(p.was_invited())
        self.assertTrue(p.was_accepted())
        self.assertEquals(p.invited_by.username, self.u.username)
        self.assertEquals(p.accepted_by.username, u2.username)

        self.assertTrue(u3.is_member_of(get_all_members_group()))
Beispiel #9
0
def get_slider_agents(scontext)  : 
    return [
            ('anonymous_group', get_anonymous_group().get_ref()),
            ('all_members_group', get_all_members_group().get_ref()), 
            ('context_agent', scontext.context_agent), 
            ('context_admin', scontext.context_admin)
           ]
Beispiel #10
0
    def accept(self, sponsor, site_root, **kwargs):
        if self.is_site_application():
            #applicant is a contact
            self.status = ACCEPTED_PENDING_USER_SIGNUP
            #self.applicant.save()  # wot?
        else:
            self.status = ACCEPTED
            self.group.join(self.applicant)

        if kwargs.has_key('admin_comment'):
            self.admin_comment = kwargs['admin_comment']

        self.accepted_by = sponsor
        self.save()
        #send and email if the application is a site application and contact hasn't yet been ACCEPTED through another application
        if self.is_site_application():
            if not self.applicant.has_accepted_application:
                self.applicant.accept_mail(sponsor, site_root, self.id)
                self.applicant.has_accepted_application = True
                self.applicant.save()

            all_members_group = get_all_members_group()
            #if this isn't an application to the site_members_group, find the application to the all_members_group and change its status to ACCEPTED_PENDING_USER_SIGNUP.
            if self.group.id != all_members_group.id:
                try:
                    site_app = Application.objects.get(applicant_object_id=self.applicant.id, 
                                                       applicant_content_type=ContentType.objects.get_for_model(Contact), 
                                                       status=PENDING, 
                                                       group=all_members_group)
                    site_app.accept(sponsor, site_app, **kwargs)
                except Application.DoesNotExist:
                    pass
        return True
Beispiel #11
0
def import_one(folder) :
  
    print ('%s, %s, %s, %s, %s' % (folder['title'], folder['mainparentuid'], folder['mainparenttype'], folder['parentuid'], folder['parenttype'])).encode('utf-8')
    if reverse.has_key(folder['mainparentuid']) :
        mainpar = folder['mainparentuid']
        print ("main parent: (%s,%s)" % (e_type(mainpar),title(mainpar))).encode('utf-8')
        if title(mainpar) != 'RESOURCES' :
            print title(mainpar).encode('utf-8')

        path  = []
        tags = []
        main = get_top_container(folder['uid'],path,tags)
        print (','.join(path)).encode('utf-8')
        print (','.join(['%s'% t for t in tags])).encode('utf-8')

        if main.__class__ == User :
            container = TgGroup.objects.get(group_name='resources')
            creator = main
            f_name=make_file_name(folder['id'],folder['uid']) 

            try :
                create_resource(container, creator, folder['id'], f_name, folder, tags)
            except Exception, e:
                print e
                import ipdb
                ipdb.set_trace()
                log.append(folder['uid'])

        elif main.__class__ == TgGroup :
            print "((()))",tags
            container = main
            creator_uid= folder['creatoruid']
            try:
                creator = get_user_for(creator_uid)
            except:
                print "No user corresponds to %s" % creator_uid
                print maps[creator_uid]

                creator = get_admin_user()
                print creator
                ipdb.set_trace()

            site_hosts = get_all_members_group().get_admin_group()
            if not creator.is_member_of(site_hosts) :
                site_hosts.add_member(creator)
                flag = True
            else :
                flag = False

            f_name = make_file_name(folder['id'],folder['uid'])
            try :
                create_resource(container, creator, folder['id'], f_name, folder, tags)
            except Exception, e :
                print e
                import ipdb
                ipdb.set_trace()
                log.append(folder['uid'])

            if flag :
                site_hosts.remove_member(creator)
def patch_in_profiles():
    """create profiles and setup security hubspace users 
    """

    site_members_group = get_all_members_group()
    site_members = site_members_group.users.all()

    users = User.objects.all()
    for user in users:
        if user not in site_members and user.username != 'anon':
            site_members_group.users.add(user)
        if not user.homeplace :
            user.homeplace = get_or_create_root_location()
            user.save()
            print "%s at %s" % (user.username, user.homeplace)

    users = User.objects.filter(profile__isnull=True)
    no_of_users = users.count()

    for user in users:
        print user.username
        create_reference(User, user)
        setup_user_security(user,'public')
        profile = user.create_Profile(user, user=user)
        profile.save()
        print `profile`

    print "patched %s users to have profiles" % str(no_of_users)
Beispiel #13
0
    def accept(self, sponsor, site_root, **kwargs):
        if self.is_site_application():
            #applicant is a contact
            self.status = ACCEPTED_PENDING_USER_SIGNUP
            #self.applicant.save()  # wot?
        else:
            self.status = ACCEPTED
            self.group.join(self.applicant)

        if kwargs.has_key('admin_comment'):
            self.admin_comment = kwargs['admin_comment']

        self.accepted_by = sponsor
        self.save()
        #send and email if the application is a site application and contact hasn't yet been ACCEPTED through another application
        if self.is_site_application():
            if not self.applicant.has_accepted_application:
                self.applicant.accept_mail(sponsor, site_root, self.id)
                self.applicant.has_accepted_application = True
                self.applicant.save()

            all_members_group = get_all_members_group()
            #if this isn't an application to the site_members_group, find the application to the all_members_group and change its status to ACCEPTED_PENDING_USER_SIGNUP.
            if self.group.id != all_members_group.id:
                try:
                    site_app = Application.objects.get(
                        applicant_object_id=self.applicant.id,
                        applicant_content_type=ContentType.objects.
                        get_for_model(Contact),
                        status=PENDING,
                        group=all_members_group)
                    site_app.accept(sponsor, site_app, **kwargs)
                except Application.DoesNotExist:
                    pass
        return True
def fix_site():

    phil = User.objects.get(username='******')

    site = Site.objects.all()[0]
    site.save()

    alls = get_all_members_group()
    sa = alls.get_admin_group()

    import ipdb
    ipdb.set_trace()

    print site.get_security_context().id, site.get_security_context(
    ).get_target().id
    print sa, sa.id, sa.get_security_context().id, sa.get_security_context(
    ).get_target(), sa.get_security_context().get_target().id

    site.acquires_from(sa)
    sc = site.create_custom_security_context()

    ref = site.get_ref()
    ref.acquired_scontext = None
    ref.save()

    site.acquires_from(sa)
    sc = site.use_acquired_security_context()
    print site.get_security_context().id, site.get_security_context(
    ).get_target().id
Beispiel #15
0
        def post_leave(self, user_or_group):
            """ this method, a break out of other stuff which happens when members leave groups,
            can be called as an independent function from syncer"""

            from apps.plus_permissions.types.Profile import ProfileInterfaces
            from apps.plus_permissions.default_agents import get_all_members_group, get_admin_user
            # remove host erpermissions on profile when join/leave Hub
            admin = get_admin_user()
            admin_group = self.get_admin_group()
            if self.group_type == 'hub':
                for prof in ProfileInterfaces:
                    user_or_group.get_security_context(
                    ).remove_arbitrary_agent(admin_group, 'Profile.%s' % prof,
                                             admin)

            from apps.plus_feed.models import FeedItem
            FeedItem.post_LEAVE(user_or_group, self)

            # stop following any group you leave .. not 100% certain this is what we want but our best guess
            from apps.microblogging.models import Following
            Following.objects.unfollow(user_or_group, self)

            # if I was the homehome for this user, change
            if user_or_group.homehub == self:
                user_or_group.homehub = get_all_members_group()
                user_or_group.save()
Beispiel #16
0
        def post_leave(self, user_or_group) :
            """ this method, a break out of other stuff which happens when members leave groups,
            can be called as an independent function from syncer"""

            from apps.plus_permissions.types.Profile import ProfileInterfaces
            from apps.plus_permissions.default_agents import get_all_members_group, get_admin_user
            # remove host erpermissions on profile when join/leave Hub
            admin = get_admin_user()
            admin_group = self.get_admin_group()
            if self.group_type == 'hub':
                for prof in ProfileInterfaces:
                    user_or_group.get_security_context().remove_arbitrary_agent(admin_group, 'Profile.%s' % prof, admin)

            from apps.plus_feed.models import FeedItem
            FeedItem.post_LEAVE(user_or_group, self)

            # stop following any group you leave .. not 100% certain this is what we want but our best guess
            from apps.microblogging.models import Following
            Following.objects.unfollow(user_or_group,self)


            # if I was the homehome for this user, change
            if user_or_group.homehub == self :
                user_or_group.homehub = get_all_members_group()
                user_or_group.save()
def fix_site() :
    
    phil = User.objects.get(username='******')
    
    site  = Site.objects.all()[0]
    site.save()

    alls = get_all_members_group()
    sa = alls.get_admin_group()

    import ipdb
    ipdb.set_trace()
    
    print site.get_security_context().id, site.get_security_context().get_target().id
    print sa,sa.id,sa.get_security_context().id, sa.get_security_context().get_target(), sa.get_security_context().get_target().id


    site.acquires_from(sa)
    sc=site.create_custom_security_context()

    ref = site.get_ref()
    ref.acquired_scontext = None
    ref.save()

    site.acquires_from(sa)   
    sc=site.use_acquired_security_context()
    print site.get_security_context().id, site.get_security_context().get_target().id
Beispiel #18
0
    def become_member(self, username, invited_by=None, accepted_by=None, password=None):
        """Either a user accepts an invitation or their application is accepted.
        XXX If application is accepted trigger an email with confirmation page to set password
        XXX if invitation is accepted by user then they go straight to set password page
        """
        u = create_user(username, self.email_address)
        if password:
            u.set_password(password)
        p = u.get_profile()
        p.first_name = self.first_name if self.first_name else username
        p.last_name = self.last_name
        p.email_address = self.email_address
        p.organisation = self.organisation
        p.post_or_zip = self.post_or_zip
        p.address = self.address
        p.country = self.country

        if accepted_by:
            p.accepted_by = accepted_by
        h = p.get_host_info()
        h.find_out = self.find_out
        p.save()
        h.save()

        u.is_active = True
        u.cc_messages_to_email = True

        u.save()
        
        self.user = u
        self.save()
        self.update_applications()
        self.update_invitations()
        for contact in Contact.objects.filter(email_address=self.email_address):
            contact.user = u
            contact.update_applications()
            contact.update_invitations()
        other_groups = u.groups.exclude(id=get_all_members_group().id) 
 
        if other_groups.count()==1:
            u.homehub = other_groups[0]
        else:
            u.homehub = get_all_members_group()
        u.save()

        return u
Beispiel #19
0
def setup_group_security(group, context_agent, context_admin, creator, permission_prototype):
    group.to_security_context()
    sec_context = group.get_security_context() 
    sec_context.set_context_agent(context_agent.get_ref())
    sec_context.set_context_admin(context_admin.get_ref())
    sec_context.save()
    group.add_member(creator)
    group.add_member(context_admin)

    group.save()
    group.get_security_context().set_up(permission_prototype)
    
    ref = group.get_ref()
    ref.creator = creator
    ref.permission_prototype = permission_prototype
    ref.save()

    if group.id != get_all_members_group().id :
        get_all_members_group().add_member(group)
Beispiel #20
0
def home(request, success_url=None):
    """
    Let's base homepage on the microblog personal now.
    """
    if not request.user.is_authenticated():
        return render_to_response(
            "home/clients/%s/home.html" % settings.PROJECT_THEME, {}, context_instance=RequestContext(request)
        )

    twitter_account = twitter_account_for_user(request.user)
    template_name = "home/clients/%s/home_logged_in.html" % settings.PROJECT_THEME
    form_class = TweetForm

    if request.method == "POST":
        form = form_class(request.user, request.POST)
        if form.is_valid():
            text = form.cleaned_data["text"]
            form.save()
            if request.POST.get("pub2twitter", False):
                twitter_account.PostUpdate(text)
            if success_url is None:
                success_url = reverse("home")
            return HttpResponseRedirect(success_url)
        reply = None
    else:
        reply = request.GET.get("reply", None)
        form = form_class()
        if reply:
            form.fields["text"].initial = u"@%s " % reply

    tweets = FeedItem.feed_manager.get_for(request.user).order_by("-sent")
    global_tweets = FeedItem.feed_manager.all_permissioned(request.user)

    all_members_group = get_all_members_group()

    if has_access(request.user, None, "Application.Accept", all_members_group.get_security_context()):
        has_accept = True
    else:
        has_accept = False

    return render_to_response(
        template_name,
        {
            "head_title": "Home",
            "head_title_status": "",
            "form": form,
            "reply": reply,
            "tweets": tweets,
            "global_tweets": global_tweets,
            "twitter_authorized": twitter_verify_credentials(twitter_account),
            "site_members_group": all_members_group,
            "has_accept": has_accept,
        },
        context_instance=RequestContext(request),
    )
Beispiel #21
0
def home(request, success_url=None):
    """
    Let's base homepage on the microblog personal now.
    """
    if not request.user.is_authenticated():
        return render_to_response('home/clients/%s/home.html' %
                                  settings.PROJECT_THEME, {},
                                  context_instance=RequestContext(request))

    twitter_account = twitter_account_for_user(request.user)
    template_name = "home/clients/%s/home_logged_in.html" % settings.PROJECT_THEME
    form_class = TweetForm

    if request.method == "POST":
        form = form_class(request.user, request.POST)
        if form.is_valid():
            text = form.cleaned_data['text']
            form.save()
            if request.POST.get("pub2twitter", False):
                twitter_account.PostUpdate(text)
            if success_url is None:
                success_url = reverse('home')
            return HttpResponseRedirect(success_url)
        reply = None
    else:
        reply = request.GET.get("reply", None)
        form = form_class()
        if reply:
            form.fields['text'].initial = u"@%s " % reply

    tweets = FeedItem.feed_manager.get_for(request.user).order_by("-sent")
    global_tweets = FeedItem.feed_manager.all_permissioned(request.user)

    all_members_group = get_all_members_group()

    if has_access(request.user, None, 'Application.Accept',
                  all_members_group.get_security_context()):
        has_accept = True
    else:
        has_accept = False

    return render_to_response(
        template_name, {
            "head_title": "Home",
            "head_title_status": '',
            "form": form,
            "reply": reply,
            "tweets": tweets,
            "global_tweets": global_tweets,
            "twitter_authorized": twitter_verify_credentials(twitter_account),
            "site_members_group": all_members_group,
            "has_accept": has_accept
        },
        context_instance=RequestContext(request))
Beispiel #22
0
def invite_url(parser, token):
    """
    """
    group = token.split_contents()[1]
    try:
        group = str(int(group))
    except ValueError:
        group = None

    if group == None:
        group = str(get_all_members_group().id)
    return UrlNode("acct_invite")
Beispiel #23
0
def invite_url(parser, token):
    """
    """
    group = token.split_contents()[1]
    try:
        group = str(int(group))
    except ValueError:
        group = None

    if group==None:
        group = str(get_all_members_group().id)
    return UrlNode("acct_invite")
Beispiel #24
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"
Beispiel #25
0
def setup_user_security(user, permission_prototype, overwrite=False):
    user.to_security_context()
    sec_context = user.get_security_context()
                    
    sec_context.set_context_agent(user.get_ref())
    sec_context.set_context_admin(get_all_members_group().get_admin_group().get_ref())
    sec_context.save()
        
    sec_context.set_up(permission_prototype, overwrite=overwrite)

    ref = user.get_ref()
    ref.creator = user
    ref.permission_prototype = permission_prototype
    ref.save()
Beispiel #26
0
    def post_LEAVE(cls, leaver, left) :
        all_members = get_all_members_group()
        if left.id == all_members.id :
            return
        leaver_item = leaver.create_FeedItem(leaver.get_creator(), type=LEAVE, source=leaver.get_ref(),
                                             short = clip('has left the group %s' % left.get_display_name()),
                                             target = left.get_ref())

        FeedManager().update_followers(leaver, leaver_item)

        left_item = left.create_FeedItem(left.get_creator(), type=LEAVE, source=left.get_ref(),
                                         short =  clip('%s has left the group.' % leaver.get_display_name()),
                                         target = leaver.get_ref())
        FeedManager().update_followers(left, left_item)
Beispiel #27
0
def on_user_change(request, data) :
    print "in on_user_changed"
    u = User.objects.plus_get(request.user, id=data['id'])

    if not u.homehub or u.homehub.place != u.homeplace :
        from apps.plus_permissions.default_agents import get_or_create_root_location, get_all_members_group
        if u.homeplace == get_or_create_root_location() :
            u.homehub = get_all_members_group()
        else :
            u.homehub = TgGroup.objects.get(place=u.homeplace,level='member')

    u.save()
    u.post_save()
    print "user %s was changed by an external application" % u.username
Beispiel #28
0
def on_user_change(request, data):
    print "in on_user_changed"
    u = User.objects.plus_get(request.user, id=data['id'])

    if not u.homehub or u.homehub.place != u.homeplace:
        from apps.plus_permissions.default_agents import get_or_create_root_location, get_all_members_group
        if u.homeplace == get_or_create_root_location():
            u.homehub = get_all_members_group()
        else:
            u.homehub = TgGroup.objects.get(place=u.homeplace, level='member')

    u.save()
    u.post_save()
    print "user %s was changed by an external application" % u.username
Beispiel #29
0
    def post_UNFOLLOW(cls, follower, followed) :
        all_members = get_all_members_group()
        if followed == all_members :
            return
 
        follower_item = follower.create_FeedItem(follower.get_creator(), type=FOLLOW, source=follower.get_ref(),
                                                 short = clip('stopped following %s' % followed.get_display_name()),
                                                 target = followed.get_ref())
        FeedManager().update_followers(follower, follower_item)

        followed_item = followed.create_FeedItem(followed.get_creator(), type=FOLLOW, source=followed.get_ref(),
                                                 short = clip('%s stopped following me' % follower.get_display_name() ),
                                                 target = follower.get_ref())
        FeedManager().update_followers(followed, followed_item)
Beispiel #30
0
def setup_user_security(user, permission_prototype, overwrite=False):
    user.to_security_context()
    sec_context = user.get_security_context()

    sec_context.set_context_agent(user.get_ref())
    sec_context.set_context_admin(
        get_all_members_group().get_admin_group().get_ref())
    sec_context.save()

    sec_context.set_up(permission_prototype, overwrite=overwrite)

    ref = user.get_ref()
    ref.creator = user
    ref.permission_prototype = permission_prototype
    ref.save()
Beispiel #31
0
    def save(self, user):
        group = self.cleaned_data.pop('group')
        members_group = get_all_members_group()
        if not group:
            group = members_group
        invitee = group.create_Contact(user, 
                                       email_address = self.cleaned_data['email_address'], 
                                       first_name=self.cleaned_data['first_name'],
                                       last_name=self.cleaned_data['last_name'])

        group.invite_member(user, 
                            invitee,
                            message=self.cleaned_data['message'])
        if not group:
            group = members_group
        return group
Beispiel #32
0
    def save(self, user):
        group = self.cleaned_data.pop('group')
        members_group = get_all_members_group()
        if not group:
            group = members_group
        invitee = group.create_Contact(
            user,
            email_address=self.cleaned_data['email_address'],
            first_name=self.cleaned_data['first_name'],
            last_name=self.cleaned_data['last_name'])

        group.invite_member(user,
                            invitee,
                            message=self.cleaned_data['message'])
        if not group:
            group = members_group
        return group
Beispiel #33
0
def individual_changes():
    # make admin user active
    admin = get_admin_user()
    admin.active = True
    admin.save()
    all_members_group = get_all_members_group()
    all_members_group.group_name = settings.VIRTUAL_HUB_NAME
    all_members_group.display_name = settings.VIRTUAL_HUB_DISPLAY_NAME
    all_members_group.group_type = "hub"
    all_members_group.save()
    all_members_hosts = all_members_group.get_admin_group()
    all_members_hosts.group_name = "hubplus_hosts"
    all_members_hosts.display_name = "Hub+ Hosts" 
    all_members_hosts.group_type = 'administrative'
    all_members_hosts.save()

    for gr in TgGroup.objects.filter(level='host'):
        all_members_hosts.add_member(gr)
        gr.save()
Beispiel #34
0
    def post_JOIN(cls, joiner, joined) :
        all_members = get_all_members_group()
        if joined.id == all_members.id :
            short = u'%s %s' % (_('has joined'), settings.SITE_NAME_SENTENCE)
            joiner_item = joiner.create_FeedItem(joiner.get_creator(), type=JOIN, source=joiner.get_ref(),
                                                 short = clip(short)
                                                 )
            FeedManager().update_followers(joiner,joiner_item)
            return
            
        joiner_item = joiner.create_FeedItem(joiner.get_creator(), type=JOIN, source=joiner.get_ref(),
                                             short = clip('has joined the group %s' % joined.get_display_name()),
                                             target = joined.get_ref())

        FeedManager().update_followers(joiner, joiner_item)

        joined_item = joined.create_FeedItem(joined.get_creator(), type=JOIN, source=joined.get_ref(),
                                             short = clip('%s has joined the group' % joiner.get_display_name()),
                                             target = joiner.get_ref())
        FeedManager().update_followers(joined, joined_item)
Beispiel #35
0
def get_or_create(group_name=None, display_name=None, place=None, level=None, user=None, 
                  group_type='interest', description='', permission_prototype='public') :
    """get or create a group
    """
    # note : we can't use get_or_create for TgGroup, because the created date clause won't match on a different day
    # from the day the record was created.
    
    if not user:
        raise TypeError("We must have a user to create a group, since otherwise it will be inaccessible")
    if not place:
        place = get_or_create_root_location()


    xs = TgGroup.objects.filter(group_name=group_name)
    if len(xs) > 0 :
        group = xs[0]
        created = False
    else :
        created = True
        group = TgGroup(group_name=group_name, display_name=display_name, level=level, 
                        place=place, description=description, group_type=group_type)
        group.save()

        if level == 'member':
            admin_group, created = TgGroup.objects.get_or_create(
                group_name=group_name + "_hosts", 
                display_name=display_name + " Hosts", 
                level='host',
                place=place,
                user=user, 
                description="Admin Group for %s" % display_name, 
                )

            setup_group_security(group, group, admin_group, user, permission_prototype)
        elif level == 'host':
            setup_group_security(group, group, group, user, 'private')

            if group.group_name != "all_members_hosts" :
                group.add_member(get_all_members_group().get_admin_group())

    return group, created
Beispiel #36
0
    def save(self, user):
        site = get_site(get_admin_user())
        about_and_why = self.cleaned_data.pop("about_and_why")

        group = self.cleaned_data.pop('group')
        members_group = get_all_members_group()

        had_group = True
        if not group:
            had_group = False
            group = members_group

        contact = group.create_Contact(user, **self.cleaned_data)
        site_application = members_group.apply(user,
                                               applicant=contact,
                                               about_and_why=about_and_why)

        if had_group:
            group.apply(user, applicant=contact, about_and_why=about_and_why)

        return group
Beispiel #37
0
def patch_in_profiles(request):
    """create profiles and setup security hubspace users
    """

    site_members_group = get_all_members_group()
    site_members = site_members_group.users.all()

    users = User.objects.all()
    for user in users:
        if user not in site_members:
            site_members_group.users.add(user)

    users = User.objects.filter(profile__isnull=True)
    no_of_users = users.count()

    for user in users:
        create_reference(User, user)
        setup_user_security(user)
        profile = user.create_Profile(user, user=user)
        profile.save()
    
    return HttpResponse("patched %s users to have profiles" % str(no_of_users))
Beispiel #38
0
    def test_become_member(self):
        u2 = get_admin_user()

        # now upgrade to a user
        u3 = self.ct.become_member('tom.salfield',  invited_by=self.u, accepted_by=u2)
        self.assertEquals(u2.__class__, User)

        # the following commented test was to confirm that becoming a member deleted the Contact
        # as I'm not deleting contacts at the moment, this test is redundant
        # self.assertEquals(len(Contact.objects.filter(id=self.ct.id)), 0)
        
        p = u3.get_profile() 
        self.assertEquals(p.first_name, self.ct.first_name)
        self.assertEquals(p.last_name, self.ct.last_name)
        self.assertEquals(p.email_address, self.ct.email_address)
        self.assertEquals(p.location, self.ct.location)
        self.assertEquals(p.get_host_info().find_out, self.ct.find_out)
        self.assertTrue(p.was_invited())
        self.assertTrue(p.was_accepted())
        self.assertEquals(p.invited_by.username, self.u.username)
        self.assertEquals(p.accepted_by.username, u2.username)

        self.assertTrue(u3.is_member_of(get_all_members_group()))
Beispiel #39
0
def show_profile(context, profile):
    if isinstance(profile, GenericReference):
        profile = profile.obj
    if profile.homehub :
        homehub = profile.homehub 
    else :
        from apps.plus_permissions.default_agents import get_all_members_group
        homehub = get_all_members_group()
        
    #profile = TemplateSecureWrapper(secure_wrap(profile, context['request'].user, interface_names=['Viewer'], required_interfaces=['Viewer']))
    user = profile.user

    is_me, i_follow, follows_me = False, False, False
    if context['request'].user.username == user.username :
        is_me = True
    if context['request'].user :
        if context['request'].user.is_following(user) :
            i_follow = True
        if user.is_following(context['request'].user) :
            follows_me = True

    return {"homehub":homehub, "profile":profile, "user": user, 
            "main_hub_name":main_hub_name(), "follows_me":follows_me, "i_follow":i_follow}
Beispiel #40
0
    def save(self, user):
        site = get_site(get_admin_user())
        about_and_why = self.cleaned_data.pop("about_and_why")
 
        group = self.cleaned_data.pop('group')
        members_group = get_all_members_group()

        had_group = True
        if not group:
            had_group = False
            group = members_group

        contact = group.create_Contact(user, **self.cleaned_data)
        site_application = members_group.apply(user, 
                                               applicant=contact,
                                               about_and_why=about_and_why)

        if had_group: 
            group.apply(user, 
                        applicant=contact,
                        about_and_why=about_and_why)

        return group
Beispiel #41
0
from django.contrib.auth.models import User
from apps.plus_permissions.default_agents import get_all_members_group, get_virtual_members_group, get_or_create_root_location

default_home = get_all_members_group()
default_home.location = get_or_create_root_location()

virtual_group = get_virtual_members_group()


def patch_home_hubs():
    for u in User.objects.all():
        if (not u.homehub) or (u.homehub == virtual_group):
            u.homehub = default_home
            default_home.join(u)
            if not u.homeplace:
                u.homeplace = u.homehub.location
            print u.username, u.homeplace.name, u.homehub
            u.save()


patch_home_hubs()
Beispiel #42
0
def get_slider_agents(scontext):
    return [('anonymous_group', get_anonymous_group().get_ref()),
            ('all_members_group', get_all_members_group().get_ref()),
            ('context_agent', scontext.context_agent),
            ('context_admin', scontext.context_admin)]
Beispiel #43
0
from apps.plus_permissions.default_agents import get_all_members_group

all =get_all_members_group()
from django.conf import settings
all.display_name = settings.ALL_MEMBERS_NAME
all.save()
Beispiel #44
0
def create_messages(sender, instance, **kwargs):

    if instance is None:
        return
    application = instance
    if application.status == PENDING:
        approvers = instance.get_approvers()
        for approver in approvers:
            if isinstance(application.applicant, User):
                sender = application.applicant
            else:
                sender = get_admin_user()

            review_url = 'http://' + settings.DOMAIN_NAME + reverse('plus_groups:list_open_applications', args=[application.group.id])

            if application.group.id == get_all_members_group().id:
                group_name = settings.SITE_NAME.encode('utf-8')
            else:    
                group_name = application.group.get_display_name()

            find_out = ""
            country = ""
            if isinstance(application.applicant, Contact):
                find_out = application.applicant.find_out
                from apps.plus_lib.countryfield import country_name
                country = country_name(application.applicant.country)

            context = Context({'first_name':application.applicant.first_name,
                               'last_name':application.applicant.last_name,
                               'email_address':application.applicant.email_address,
                               'organisation':application.applicant.organisation,
                               'group_name':group_name,
                               'request':application.request,
                               'review_url':review_url,
                               'find_out':find_out,
                               'country':country})

            msg = Template(settings.APPLICATION_MESSAGE).render(context)
            approver.message(sender=sender, 
                         subject="Application to %s from %s" %(group_name, application.applicant.get_display_name()), 
                         body=msg)

    #if the application has a user then we want to message them
    if not application.is_site_application():
        if application.status == ACCEPTED:
            group = application.group
            accepted_by = application.accepted_by
            applicant = application.applicant
            data = {'group_name':group.get_display_name(),
                    'accepted_by': accepted_by.get_display_name(),
                    'applicant':applicant.get_display_name(),
                    'group_url':reverse('plus_groups:group', args=[group.id])}

            msg = settings.ACCEPTED_TO_GROUP % data
            
            applicant.message(sender=accepted_by,
                         subject="Your application to %(group_name)s was accepted" % data,
                         body=msg)

        elif application.status == REJECTED:
            group = application.group
            rejected_by = application.rejected_by
            applicant = application.applicant
            data = {'group_name':group.get_display_name(),
                    'rejected_by': rejected_by.get_display_name(),
                    'applicant':applicant.get_display_name(),
                    'group_url':reverse('plus_groups:group', args=[group.id])}

            context = Context(data)
            msg = Template(settings.APPLICATION_REJECT_TEMPLATE).render(context)

            applicant.message(sender=rejected_by,
                         subject="Your application to %(group_name)s was declined" % data,
                         body=msg)
Beispiel #45
0
def unhost(username) :
    if User.objects.filter(username=username) :
        u = User.objects.get(username=username)
        for group in u.get_enclosures() :
            if group.id != get_all_members_group().id :
                group.remove_member(u)
Beispiel #46
0
def import_one(folder):

    print('%s, %s, %s, %s, %s' %
          (folder['title'], folder['mainparentuid'], folder['mainparenttype'],
           folder['parentuid'], folder['parenttype'])).encode('utf-8')
    if reverse.has_key(folder['mainparentuid']):
        mainpar = folder['mainparentuid']
        print("main parent: (%s,%s)" %
              (e_type(mainpar), title(mainpar))).encode('utf-8')
        if title(mainpar) != 'RESOURCES':
            print title(mainpar).encode('utf-8')

        path = []
        tags = []
        main = get_top_container(folder['uid'], path, tags)
        print(','.join(path)).encode('utf-8')
        print(','.join(['%s' % t for t in tags])).encode('utf-8')

        if main.__class__ == User:
            container = TgGroup.objects.get(group_name='resources')
            creator = main
            f_name = make_file_name(folder['id'], folder['uid'])

            try:
                create_resource(container, creator, folder['id'], f_name,
                                folder, tags)
            except Exception, e:
                print e
                import ipdb
                ipdb.set_trace()
                log.append(folder['uid'])

        elif main.__class__ == TgGroup:
            print "((()))", tags
            container = main
            creator_uid = folder['creatoruid']
            try:
                creator = get_user_for(creator_uid)
            except:
                print "No user corresponds to %s" % creator_uid
                print maps[creator_uid]

                creator = get_admin_user()
                print creator
                ipdb.set_trace()

            site_hosts = get_all_members_group().get_admin_group()
            if not creator.is_member_of(site_hosts):
                site_hosts.add_member(creator)
                flag = True
            else:
                flag = False

            f_name = make_file_name(folder['id'], folder['uid'])
            try:
                create_resource(container, creator, folder['id'], f_name,
                                folder, tags)
            except Exception, e:
                print e
                import ipdb
                ipdb.set_trace()
                log.append(folder['uid'])

            if flag:
                site_hosts.remove_member(creator)
Beispiel #47
0
 def get_approvers(self):
     return [u for u in get_all_members_group().get_admin_group().get_users()]
Beispiel #48
0

def patch_groups():
    for g in TgGroup.objects.all():
        g.group_type = g.group_type.lower()
        print g.display_name.encode('utf-8'), g.group_type
        g.save()


from apps.plus_permissions.default_agents import get_all_members_group, get_virtual_members_group
from django.conf import settings


def set_type(g, type):
    g.group_type = type
    print g.display_name, g.group_type
    g.save()


set_type(get_all_members_group(), settings.GROUP_HUB_TYPE)

import ipdb
ipdb.set_trace()
g = get_all_members_group()
g.display_name = settings.ALL_MEMBERS_NAME
g.save()

set_type(get_virtual_members_group(), 'internal')

#patch_groups()
Beispiel #49
0
def unhost(username):
    if User.objects.filter(username=username):
        u = User.objects.get(username=username)
        for group in u.get_enclosures():
            if group.id != get_all_members_group().id:
                group.remove_member(u)
Beispiel #50
0
    def test_application(self):

        god = get_admin_user(
        )  # now a standard user, and member of the site_members_group's admin
        site = get_site(god)

        contact = site.create_Contact(god,
                                      first_name='kate',
                                      last_name='smith',
                                      email_address='*****@*****.**')
        contact.save()

        self.assertTrue(contact.get_inner().get_creator())

        group = site.create_TgGroup(god,
                                    group_name='sexy_salad',
                                    display_name='Sexy Salad',
                                    level='member')

        self.assertTrue(
            group.get_inner().get_creator())  # group should have a creator
        self.assertEquals(group.get_inner().get_creator().id, god.id)

        application = site.create_Application(god,
                                              applicant=contact,
                                              request='I want to join in')

        # the following should be true because application was created by god
        # so god is its "creator" and default for Application.Editor is "creator"

        self.assertTrue(has_access(god, application, 'Application.Editor'))
        application.group = group.get_inner()
        application.save()

        self.assertTrue(has_access(group, application, 'Application.Viewer'))

        self.assertEquals(application.date.date(),
                          datetime.datetime.today().date())

        self.assertTrue(application.applicant.s_eq(contact))
        self.assertEquals(application.request, 'I want to join in')
        self.assertTrue(application.group.s_eq(group))
        self.assertEquals(application.status, PENDING)
        self.assertEquals(application.admin_comment, '')
        self.assertEquals(application.accepted_by, None)

        # adding a couple more

        ap2 = site.create_Application(god,
                                      applicant=contact,
                                      request='ap2',
                                      group=get_anonymous_group())
        ap3 = site.create_Application(god,
                                      applicant=contact,
                                      request='ap3',
                                      group=get_all_members_group())

        self.assertEquals(self.count(Application.objects.filter()), 3)
        self.assertEquals(
            self.count(Application.objects.filter(request='ap2')), 1)

        mable = User(username='******', email_address='*****@*****.**')
        mable.save()
        self.assertEquals(Application.objects.plus_count(mable), 0)

        # now there's a security tag which links "group" as context to the interface "ApplicationViewer"
        site.get_inner().get_security_context().add_arbitrary_agent(
            group, 'Application.Viewer', god)

        self.assertTrue(has_access(group, ap2, 'Application.Viewer'))

        self.assertFalse(has_access(mable, ap2, 'Application.Viewer'))

        self.assertEquals(Application.objects.plus_count(group), 3)

        s_application = Application.objects.plus_get(mable, id=application.id)

        def f(application, sponsor):
            application.accept(sponsor)

        self.assertRaises(PlusPermissionsNoAccessException, f, s_application,
                          mable)

        self.assertEquals(s_application.get_inner().status, PENDING)

        application = Application.objects.get(id=application.id)

        application.accept(mable, 'site_root', admin_comment='great choice')

        self.assertEquals(application.status, WAITING_USER_SIGNUP)
        self.assertEquals(application.admin_comment, 'great choice')
        self.assertEquals(application.accepted_by, mable)
Beispiel #51
0
    def test_invite(self):
        site = get_site(get_admin_user())
        all_members = get_all_members_group()

        u = create_user('fred', '*****@*****.**')
Beispiel #52
0
from apps.plus_permissions.default_agents import get_all_members_group

all = get_all_members_group()
from django.conf import settings
all.display_name = settings.ALL_MEMBERS_NAME
all.save()
Beispiel #53
0
def create_messages(sender, instance, **kwargs):

    if instance is None:
        return
    application = instance
    if application.status == PENDING:
        approvers = instance.get_approvers()
        for approver in approvers:
            if isinstance(application.applicant, User):
                sender = application.applicant
            else:
                sender = get_admin_user()

            review_url = 'http://' + settings.DOMAIN_NAME + reverse(
                'plus_groups:list_open_applications',
                args=[application.group.id])

            if application.group.id == get_all_members_group().id:
                group_name = settings.SITE_NAME.encode('utf-8')
            else:
                group_name = application.group.get_display_name()

            find_out = ""
            country = ""
            if isinstance(application.applicant, Contact):
                find_out = application.applicant.find_out
                from apps.plus_lib.countryfield import country_name
                country = country_name(application.applicant.country)

            context = Context({
                'first_name': application.applicant.first_name,
                'last_name': application.applicant.last_name,
                'email_address': application.applicant.email_address,
                'organisation': application.applicant.organisation,
                'group_name': group_name,
                'request': application.request,
                'review_url': review_url,
                'find_out': find_out,
                'country': country
            })

            msg = Template(settings.APPLICATION_MESSAGE).render(context)
            approver.message(
                sender=sender,
                subject="Application to %s from %s" %
                (group_name, application.applicant.get_display_name()),
                body=msg)

    #if the application has a user then we want to message them
    if not application.is_site_application():
        if application.status == ACCEPTED:
            group = application.group
            accepted_by = application.accepted_by
            applicant = application.applicant
            data = {
                'group_name': group.get_display_name(),
                'accepted_by': accepted_by.get_display_name(),
                'applicant': applicant.get_display_name(),
                'group_url': reverse('plus_groups:group', args=[group.id])
            }

            msg = settings.ACCEPTED_TO_GROUP % data

            applicant.message(
                sender=accepted_by,
                subject="Your application to %(group_name)s was accepted" %
                data,
                body=msg)

        elif application.status == REJECTED:
            group = application.group
            rejected_by = application.rejected_by
            applicant = application.applicant
            data = {
                'group_name': group.get_display_name(),
                'rejected_by': rejected_by.get_display_name(),
                'applicant': applicant.get_display_name(),
                'group_url': reverse('plus_groups:group', args=[group.id])
            }

            context = Context(data)
            msg = Template(
                settings.APPLICATION_REJECT_TEMPLATE).render(context)

            applicant.message(
                sender=rejected_by,
                subject="Your application to %(group_name)s was declined" %
                data,
                body=msg)