Пример #1
0
def do_group_import(group_object_dict):
    """Creates and Event and Place for the given event_object_dict
    """
    group = Group()

    # assure the correct fields get the right value types
    for field in GROUP_FIELDS:
        if field in group_object_dict:
            field_type = Group._meta.get_field_by_name(field)[0]
            if isinstance(field_type, FloatField):
                setattr(group, field, group_object_dict[field])
            else:
                if field_type.max_length:
                    setattr(
                        group, field,
                        unicode(
                            group_object_dict[field])[:field_type.max_length])
                else:
                    setattr(group, field, unicode(group_object_dict[field]))
    # Since the allow_anonymous_view is not included in the GROUP_FIELDS,
    # set it to False
    group.allow_anonymous_view = False
    group.save()

    return group
Пример #2
0
def do_group_import(group_object_dict):
    """Creates and Event and Place for the given event_object_dict
    """
    group = Group()

    # assure the correct fields get the right value types
    for field in GROUP_FIELDS:
        if field in group_object_dict:
            field_type = Group._meta.get_field_by_name(field)[0]
            if isinstance(field_type, FloatField):
                setattr(group, field, group_object_dict[field])
            else:
                if field_type.max_length:
                    setattr(group, field, unicode(group_object_dict[field])[:field_type.max_length])
                else:
                    setattr(group, field, unicode(group_object_dict[field]))
    # Since the allow_anonymous_view is not included in the GROUP_FIELDS,
    # set it to False
    group.allow_anonymous_view = False
    group.save()

    return group
Пример #3
0
def create_default_group(sender, app, **kwargs):
    """
    Auto-create a default group with id=1 if none exist.
    """
    if app == "user_groups":
        if not Group.objects.filter(pk=1):
            site_name = "Default"
            table_exists = Setting._meta.db_table in \
                connection.introspection.table_names()
            if table_exists and get_setting("site", "global", "sitedisplayname"):
                site_name = get_setting("site", "global", "sitedisplayname")

            group = Group()
            group.name = site_name
            group.label = site_name
            group.show_as_option = False
            group.allow_self_add = False
            group.allow_self_remove = False
            group.description = "Initial group auto-generated on site creation."
            group.id = 1

            group.save()
Пример #4
0
def create_default_group(sender, app, **kwargs):
    """
    Load default groups if none exist
    or create a group with id=1 if not exist.
    """
    def get_site_display_name():
        setting_table_exists = Setting._meta.db_table in \
                    connection.introspection.table_names()
        if setting_table_exists:
            return get_setting("site", "global", "sitedisplayname")
        return ''

    if app == "user_groups":
        site_name = get_site_display_name().strip()
        if not Group.objects.all():
            call_command("loaddata", "default_groups.json")
            if site_name:
                # update the name and label of the first default user group
                group = Group.objects.get(pk=1)
                group.name = site_name
                group.label = site_name
                group.save()
        else:
            if not Group.objects.filter(pk=1):
                if not site_name:
                    site_name = "Default"

                group = Group()
                group.name = site_name
                group.label = site_name
                group.show_as_option = False
                group.allow_self_add = False
                group.allow_self_remove = False
                group.description = "Initial group auto-generated on site creation."
                group.id = 1

                group.save()
Пример #5
0
    def save_model(self, request, object, form, change):
        instance = form.save(commit=False)

        # save the expiration method fields
        type_exp_method = form.cleaned_data['type_exp_method']
        type_exp_method_list = type_exp_method.split(",")
        for i, field in enumerate(form.type_exp_method_fields):
            if field == 'fixed_option2_can_rollover':
                if type_exp_method_list[i] == '':
                    type_exp_method_list[i] = ''
            else:
                if type_exp_method_list[i] == '':
                    type_exp_method_list[i] = "0"

            setattr(instance, field, type_exp_method_list[i])

        if not change:
            instance.creator = request.user
            instance.creator_username = request.user.username
            instance.owner = request.user
            instance.owner_username = request.user.username

            # create a group for this type
            group = Group()
            group.name = 'Membership: %s' % instance.name
            group.slug = slugify(group.name)
            # just in case, check if this slug already exists in group.
            # if it does, make a unique slug
            tmp_groups = Group.objects.filter(slug__istartswith=group.slug)
            if tmp_groups:
                t_list = [g.slug[len(group.slug):] for g in tmp_groups]
                num = 1
                while str(num) in t_list:
                    num += 1
                group.slug = '%s%s' % (group.slug, str(num))
                # group name is also a unique field
                group.name = '%s%s' % (group.name, str(num))

            group.label = instance.name
            group.type = 'system_generated'
            group.email_recipient = request.user.email
            group.show_as_option = 0
            group.allow_self_add = 0
            group.allow_self_remove = 0
            group.description = "Auto-generated with the membership type. Used for membership only"
            group.notes = "Auto-generated with the membership type. Used for membership only"
            #group.use_for_membership = 1
            group.creator = request.user
            group.creator_username = request.user.username
            group.owner = request.user
            group.owner_username = request.user.username

            group.save()

            instance.group = group

        # save the object
        instance.save()

        #form.save_m2m()

        return instance
Пример #6
0
    def authenticate(self, *args, **kwargs):
        """Authenticate user using social credentials

        Authentication is made if this is the correct backend, backend
        verification is made by kwargs inspection for current backend
        name presence.
        """
        # Validate backend and arguments. Require that the Social Auth
        # response be passed in as a keyword argument, to make sure we
        # don't match the username/password calling conventions of
        # authenticate.
        if not (self.name and kwargs.get(self.name) and 'response' in kwargs):
            return None

        response = kwargs.get('response')
        request = kwargs.get('request')
        details = self.get_user_details(response)
        uid = self.get_user_id(details, response)
        is_new = False
        try:
            social_user = UserSocialAuth.objects.select_related('user')\
                                                .get(provider=self.name,
                                                     uid=uid)
        except UserSocialAuth.DoesNotExist:
            user = kwargs.get('user')
            if user is None:  # new user
                if not CREATE_USERS:
                    return None

                email = details.get('email')
                if email and ASSOCIATE_BY_MAIL:
                    # try to associate accounts registered with the same email
                    # address, only if it's a single object. ValueError is
                    # raised if multiple objects are returned
                    try:
                        user = User.objects.get(email=email)
                    except MultipleObjectsReturned:
                        raise ValueError('Not unique email address supplied')
                    except User.DoesNotExist:
                        user = None
                if not user:
                    username = self.username(details)
                    user = User.objects.create_user(username=username,
                                                    email=email)
                    is_new = True
                    default_user_groups = [
                        g.strip() for g in (get_setting(
                            'module', 'users', 'defaultusergroup')).split(',')
                    ]
                    if default_user_groups:
                        from tendenci.apps.user_groups.models import Group, GroupMembership
                        from django.db.models import Q
                        for group_name in default_user_groups:
                            groups = Group.objects.filter(
                                Q(name=group_name)
                                | Q(label=group_name)).filter(
                                    allow_self_add=1,
                                    status=1,
                                    status_detail='active')
                            if groups:
                                group = groups[0]
                            else:
                                # group doesnot exist, so create the group
                                group = Group()
                                group.name = group_name
                                group.label = group_name
                                group.type = 'distribution'
                                group.show_as_option = 1
                                group.allow_self_add = 1
                                group.allow_self_remove = 1
                                group.creator = user
                                group.creator_username = user.username
                                group.owner = user
                                group.owner_username = user.username
                                try:
                                    group.save()
                                except:
                                    group = None

                            if group:
                                gm = GroupMembership()
                                gm.group = group
                                gm.member = user
                                gm.creator_id = user.id
                                gm.creator_username = user.username
                                gm.owner_id = user.id
                                gm.owner_username = user.username
                                gm.save()
                    log_defaults = {
                        'event_id':
                        121000,
                        'event_data':
                        '%s (%d) self added by form' %
                        (user._meta.object_name, user.pk),
                        'description':
                        '%s self added' % user._meta.object_name,
                        'user':
                        user,
                        'request':
                        request,
                        'instance':
                        user,
                    }
                    EventLog.objects.log(**log_defaults)
            social_user = self.associate_auth(user, uid, response, details)
        else:
            # This account was registered to another user, so we raise an
            # error in such case and the view should decide what to do on
            # at this moment, merging account is not an option because that
            # would imply update user references on other apps, that's too
            # much intrusive
            if 'user' in kwargs and kwargs['user'] != social_user.user:
                raise ValueError('Account already in use.', social_user)
            user = social_user.user

        # Update user account data.
        self.update_user_details(user, response, details, is_new)

        # Update extra_data storage, unless disabled by setting
        if LOAD_EXTRA_DATA:
            extra_data = self.extra_data(user, uid, response, details)
            if extra_data and social_user.extra_data != extra_data:
                social_user.extra_data = extra_data
                social_user.save()

        return user
Пример #7
0
def register(request,
             success_url=None,
             form_class=RegistrationForm,
             profile_callback=None,
             template_name='registration/registration_form.html',
             event_id=None,
             extra_context=None):
    """
    Allow a new user to register an account.

    Following successful registration, issue a redirect; by default,
    this will be whatever URL corresponds to the named URL pattern
    ``registration_complete``, which will be
    ``/accounts/register/complete/`` if using the included URLConf. To
    change this, point that named pattern at another URL, or pass your
    preferred URL as the keyword argument ``success_url``.

    By default, ``registration.forms.RegistrationForm`` will be used
    as the registration form; to change this, pass a different form
    class as the ``form_class`` keyword argument. The form class you
    specify must have a method ``save`` which will create and return
    the new ``User``, and that method must accept the keyword argument
    ``profile_callback`` (see below).

    To enable creation of a site-specific user profile object for the
    new user, pass a function which will create the profile object as
    the keyword argument ``profile_callback``. See
    ``RegistrationManager.create_inactive_user`` in the file
    ``models.py`` for details on how to write this function.

    By default, use the template
    ``registration/registration_form.html``; to change this, pass the
    name of a template as the keyword argument ``template_name``.

    **Required arguments**

    None.

    **Optional arguments**

    ``form_class``
        The form class to use for registration.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``profile_callback``
        A function which will be used to create a site-specific
        profile instance for the new ``User``.

    ``success_url``
        The URL to redirect to on successful registration.

    ``template_name``
        A custom template to use.

    **Context:**

    ``form``
        The registration form.

    Any extra variables supplied in the ``extra_context`` argument
    (see above).

    **Template:**

    registration/registration_form.html or ``template_name`` keyword
    argument.

    """
    # check if this site allows self registration, if not, redirect to login page
    allow_self_registration = get_setting('module', 'users',
                                          'selfregistration')
    if not allow_self_registration:
        return HttpResponseRedirect(reverse('auth_login'))

    form_params = {}
    if request.session.get('form_params', None):
        form_params = request.session.pop('form_params')

    if request.method == 'POST':
        form = form_class(data=request.POST,
                          files=request.FILES,
                          **form_params)
        if form.is_valid():
            # This is for including a link in the reg email back to the event viewed
            event = None
            if event_id:  # the user signed up via an event
                from tendenci.apps.events.models import Event
                event = get_object_or_404(Event, pk=event_id)

            new_user = form.save(profile_callback=profile_callback,
                                 event=event)
            # success_url needs to be dynamically generated here; setting a
            # a default value using reverse() will cause circular-import
            # problems with the default URLConf for this application, which
            # imports this file.

            # add to the default group(s)
            default_user_groups = [
                g.strip()
                for g in (get_setting('module', 'users', 'defaultusergroup')
                          ).split(',')
            ]
            if default_user_groups:
                from tendenci.apps.user_groups.models import Group, GroupMembership
                from django.db.models import Q
                for group_name in default_user_groups:
                    groups = Group.objects.filter(
                        Q(name=group_name) | Q(label=group_name)).filter(
                            allow_self_add=1, status=1, status_detail='active')
                    if groups:
                        group = groups[0]
                    else:
                        # group doesnot exist, so create the group
                        group = Group()
                        group.name = group_name
                        group.label = group_name
                        group.type = 'distribution'
                        group.show_as_option = 1
                        group.allow_self_add = 1
                        group.allow_self_remove = 1
                        group.creator = new_user
                        group.creator_username = new_user.username
                        group.owner = new_user
                        group.owner_username = new_user.username
                        try:
                            group.save()
                        except:
                            group = None

                    if group:
                        gm = GroupMembership()
                        gm.group = group
                        gm.member = new_user
                        gm.creator_id = new_user.id
                        gm.creator_username = new_user.username
                        gm.owner_id = new_user.id
                        gm.owner_username = new_user.username
                        gm.save()

            EventLog.objects.log(instance=new_user)

            if form.openid and form.provider:
                usas = UserSocialAuth.objects.filter(uid=form.openid,
                                                     provider=form.provider)
                if not usas or len(usas) == 0:
                    usa = UserSocialAuth.objects.create(provider=form.provider,
                                                        uid=form.openid,
                                                        extra_data=None,
                                                        user_id=new_user.id)
                    usa.save()

            return HttpResponseRedirect(success_url
                                        or reverse('registration_complete'))
        elif form.similar_email_found:
            messages.add_message(
                request, messages.INFO,
                _(
                    u"An account already exists for the email %(email)s." % {
                        'email':
                        request.POST.get('email_0')
                        or request.POST.get('email_1')
                    }))

            querystring = 'registration=True'
            return HttpResponseRedirect(
                reverse('auth_password_reset') + "?%s" % querystring)

    else:
        allow_same_email = request.GET.get('registration_approved', False)
        openid = request.GET.get('openid', '')
        provider = request.GET.get('provider', '')
        form_params = {
            'allow_same_email': allow_same_email,
            'openid': openid,
            'provider': provider
        }
        request.session['form_params'] = form_params
        form = form_class(**form_params)

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    return render_to_response(template_name, {
        'form': form,
        'association_name': get_association_name(request)
    },
                              context_instance=context)
Пример #8
0
    def save_model(self, request, object, form, change):
        instance = form.save(commit=False)

        # save the expiration method fields
        type_exp_method = form.cleaned_data["type_exp_method"]
        type_exp_method_list = type_exp_method.split(",")
        for i, field in enumerate(form.type_exp_method_fields):
            if field == "fixed_option2_can_rollover":
                if type_exp_method_list[i] == "":
                    type_exp_method_list[i] = ""
            else:
                if type_exp_method_list[i] == "":
                    type_exp_method_list[i] = "0"

            setattr(instance, field, type_exp_method_list[i])

        if not change:
            instance.creator = request.user
            instance.creator_username = request.user.username
            instance.owner = request.user
            instance.owner_username = request.user.username

            # create a group for this type
            group = Group()
            group.name = "Membership: %s" % instance.name
            group.slug = slugify(group.name)
            # just in case, check if this slug already exists in group.
            # if it does, make a unique slug
            tmp_groups = Group.objects.filter(slug__istartswith=group.slug)
            if tmp_groups:
                t_list = [g.slug[len(group.slug) :] for g in tmp_groups]
                num = 1
                while str(num) in t_list:
                    num += 1
                group.slug = "%s%s" % (group.slug, str(num))
                # group name is also a unique field
                group.name = "%s%s" % (group.name, str(num))

            group.label = instance.name
            group.type = "system_generated"
            group.email_recipient = request.user.email
            group.show_as_option = 0
            group.allow_self_add = 0
            group.allow_self_remove = 0
            group.description = "Auto-generated with the membership type. Used for membership only"
            group.notes = "Auto-generated with the membership type. Used for membership only"
            # group.use_for_membership = 1
            group.creator = request.user
            group.creator_username = request.user.username
            group.owner = request.user
            group.owner_username = request.user.username

            group.save()

            instance.group = group

        # save the object
        instance.save()

        # form.save_m2m()

        return instance
Пример #9
0
    def handle(self, *args, **kwargs):
        from tendenci.apps.site_settings.models import Setting
        from tendenci.apps.user_groups.models import Group, GroupMembership
        from tendenci.apps.corporate_memberships.models import CorpMembershipRep
        verbosity = int(kwargs['verbosity'])

        cmrg_setting, created = Setting.objects.get_or_create(
            name='corpmembershiprepsgroupid')
        description = 'This Group is for all corporate membership representatives. ' + \
                    'Adding or deleting a representative will automatically ' + \
                    'add (or remove) the user to (or from) this group.'
        if created:
            cmrg_setting.label = 'Corporate Membership Representatives Group Id'
            cmrg_setting.description = description
            cmrg_setting.data_type = 'int'
            cmrg_setting.value = '0'
            cmrg_setting.default_value = '0'
            cmrg_setting.input_type = 'text'
            cmrg_setting.input_value = ''
            cmrg_setting.client_editable = False
            cmrg_setting.store = True
            cmrg_setting.scope = 'module'
            cmrg_setting.scope_category = 'corporate_memberships'
            cmrg_setting.save()

        group = None
        group_id = int(cmrg_setting.value)
        if group_id:
            [group] = Group.objects.filter(id=group_id)[:1] or [None]

        if not group:
            # first check if we have a default group. if not, create one
            # so that this reps group won't become the one with id=1
            Group.objects.get_or_create_default()

            group = Group(name='Corporate Membership Representatives',
                          slug='corporate-membership-representatives',
                          label='Corporate Membership Representatives',
                          type='system_generated',
                          show_as_option=False,
                          allow_self_add=False,
                          allow_self_remove=False,
                          description=description,
                          allow_anonymous_view=False,
                          allow_user_view=False,
                          allow_member_view=False,
                          allow_user_edit=False,
                          allow_member_edit=False)
            group.save()
            cmrg_setting.value = str(group.id)
            cmrg_setting.save()
        else:
            # remove all non-reps from group
            for user in group.members.all():
                if not CorpMembershipRep.objects.filter(user=user).exists():
                    if verbosity >= 2:
                        print('Removing user "%s" from group' % user.username)
                    gm = GroupMembership.objects.get(group=group, member=user)
                    gm.delete()

        # add reps to group
        for rep in CorpMembershipRep.objects.all():
            user = rep.user
            if not group.is_member(user):
                if verbosity >= 2:
                    print('Adding user "%s" to group' % user.username)
                group.add_user(user)
Пример #10
0
def register(request, success_url=None,
             form_class=RegistrationForm, profile_callback=None,
             template_name='registration/registration_form.html',
             event_id=None,
             extra_context=None):
    """
    Allow a new user to register an account.

    Following successful registration, issue a redirect; by default,
    this will be whatever URL corresponds to the named URL pattern
    ``registration_complete``, which will be
    ``/accounts/register/complete/`` if using the included URLConf. To
    change this, point that named pattern at another URL, or pass your
    preferred URL as the keyword argument ``success_url``.

    By default, ``registration.forms.RegistrationForm`` will be used
    as the registration form; to change this, pass a different form
    class as the ``form_class`` keyword argument. The form class you
    specify must have a method ``save`` which will create and return
    the new ``User``, and that method must accept the keyword argument
    ``profile_callback`` (see below).

    To enable creation of a site-specific user profile object for the
    new user, pass a function which will create the profile object as
    the keyword argument ``profile_callback``. See
    ``RegistrationManager.create_inactive_user`` in the file
    ``models.py`` for details on how to write this function.

    By default, use the template
    ``registration/registration_form.html``; to change this, pass the
    name of a template as the keyword argument ``template_name``.

    **Required arguments**

    None.

    **Optional arguments**

    ``form_class``
        The form class to use for registration.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``profile_callback``
        A function which will be used to create a site-specific
        profile instance for the new ``User``.

    ``success_url``
        The URL to redirect to on successful registration.

    ``template_name``
        A custom template to use.

    **Context:**

    ``form``
        The registration form.

    Any extra variables supplied in the ``extra_context`` argument
    (see above).

    **Template:**

    registration/registration_form.html or ``template_name`` keyword
    argument.

    """
    # check if this site allows self registration, if not, redirect to login page
    allow_self_registration = get_setting('module', 'users', 'selfregistration')
    if not allow_self_registration:
        return HttpResponseRedirect(reverse('auth_login'))

    form_params = {}
    if request.session.get('form_params', None):
        form_params = request.session.pop('form_params')

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES, **form_params)
        if form.is_valid():
            # This is for including a link in the reg email back to the event viewed
            event = None
            if event_id: # the user signed up via an event
                from tendenci.apps.events.models import Event
                event = get_object_or_404(Event, pk=event_id)

            new_user = form.save(profile_callback=profile_callback, event=event)
            # success_url needs to be dynamically generated here; setting a
            # a default value using reverse() will cause circular-import
            # problems with the default URLConf for this application, which
            # imports this file.

            # add to the default group(s)
            default_user_groups =[g.strip() for g in (get_setting('module', 'users', 'defaultusergroup')).split(',')]
            if default_user_groups:
                from tendenci.apps.user_groups.models import Group, GroupMembership
                from django.db.models import Q
                for group_name in default_user_groups:
                    groups = Group.objects.filter(Q(name=group_name) | Q(label=group_name)).filter(allow_self_add=1, status=1, status_detail='active')
                    if groups:
                        group = groups[0]
                    else:
                        # group doesnot exist, so create the group
                        group = Group()
                        group.name  = group_name
                        group.label = group_name
                        group.type = 'distribution'
                        group.show_as_option = 1
                        group.allow_self_add = 1
                        group.allow_self_remove = 1
                        group.creator = new_user
                        group.creator_username = new_user.username
                        group.owner =  new_user
                        group.owner_username = new_user.username
                        try:
                            group.save()
                        except:
                            group = None

                    if group:
                        gm = GroupMembership()
                        gm.group = group
                        gm.member = new_user
                        gm.creator_id = new_user.id
                        gm.creator_username = new_user.username
                        gm.owner_id =  new_user.id
                        gm.owner_username = new_user.username
                        gm.save()


            EventLog.objects.log(instance=new_user)

            return HttpResponseRedirect(success_url or reverse('registration_complete'))
        elif form.similar_email_found:
            messages.add_message(
                request, messages.INFO,
                _(u"An account already exists for the email %(email)s." % {
                    'email': request.POST.get('email_0') or request.POST.get('email_1')}))

            querystring = 'registration=True'
            return HttpResponseRedirect(reverse('auth_password_reset')+ "?%s" % querystring)

    else:
        allow_same_email = request.GET.get('registration_approved', False)
        form_params = {'allow_same_email' : allow_same_email }
        request.session['form_params'] = form_params
        form = form_class(**form_params)

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    return render_to_response(template_name,
                              { 'form': form },
                              context_instance=context)
Пример #11
0
    def handle(self, *args, **kwargs):
        from tendenci.apps.site_settings.models import Setting
        from tendenci.apps.user_groups.models import Group, GroupMembership
        from tendenci.apps.corporate_memberships.models import CorpMembershipRep
        verbosity = int(kwargs['verbosity'])

        cmrg_setting, created = Setting.objects.get_or_create(
                        name='corpmembershiprepsgroupid')
        description = 'This Group is for all corporate membership representatives. ' + \
                    'Adding or deleting a representative will automatically ' + \
                    'add (or remove) the user to (or from) this group.'
        if created:
            cmrg_setting.label = 'Corporate Membership Representatives Group Id'
            cmrg_setting.description = description
            cmrg_setting.data_type = 'int'
            cmrg_setting.value = '0'
            cmrg_setting.default_value = '0'
            cmrg_setting.input_type = 'text'
            cmrg_setting.input_value = ''
            cmrg_setting.client_editable = False
            cmrg_setting.store = True
            cmrg_setting.scope = 'module'
            cmrg_setting.scope_category = 'corporate_memberships'
            cmrg_setting.save()

        group = None
        group_id = int(cmrg_setting.value)
        if group_id:
            [group] = Group.objects.filter(id=group_id)[:1] or [None]

        if not group:
            # first check if we have a default group. if not, create one
            # so that this reps group won't become the one with id=1
            Group.objects.get_or_create_default()

            group = Group(
                      name='Corporate Membership Representatives',
                      slug='corporate-membership-representatives',
                      label='Corporate Membership Representatives',
                      type='system_generated',
                      show_as_option=False,
                      allow_self_add=False,
                      allow_self_remove=False,
                      description=description,
                      allow_anonymous_view=False,
                      allow_user_view=False,
                      allow_member_view=False,
                      allow_user_edit=False,
                      allow_member_edit=False)
            group.save()
            cmrg_setting.value = str(group.id)
            cmrg_setting.save()
        else:
            # remove all non-reps from group
            for user in group.members.all():
                if not CorpMembershipRep.objects.filter(user=user).exists():
                    if verbosity >= 2:
                        print('Removing user "%s" from group' % user.username)
                    gm = GroupMembership.objects.get(group=group,
                                                 member=user)
                    gm.delete()

        # add reps to group
        for rep in CorpMembershipRep.objects.all():
            user = rep.user
            if not group.is_member(user):
                if verbosity >= 2:
                    print('Adding user "%s" to group' % user.username)
                group.add_user(user)
Пример #12
0
    def handle(self, *args, **options):
        from tendenci.apps.entities.models import Entity
        from tendenci.apps.user_groups.models import Group
        from tendenci.apps.site_settings.utils import get_setting
        from tendenci.apps.perms.models import TendenciBaseModel

        verbosity = int(options['verbosity'])

        [entity] = Entity.objects.filter(pk=1)[:1] or [None]
        [user] = User.objects.filter(pk=1)[:1] or [None]

        site_display_name = get_setting('site', 'global', 'sitedisplayname')
        if not site_display_name:
            site_display_name = 'Default'

        site_contact_name = get_setting('site', 'global', 'sitecontactname')
        site_contact_email = get_setting('site', 'global', 'sitecontactemail')
        site_phone_number = get_setting('site', 'global', 'sitephonenumber')
        site_url = get_setting('site', 'global', 'siteurl')
        # if there is no entity, create one.
        if not entity:
            params = {
                'id': 1,
                'entity_name': site_display_name,
                'entity_type': '',
                'contact_name': site_contact_name,
                'phone': site_phone_number,
                'email': site_contact_email,
                'fax': '',
                'website': site_url,
                'summary': '',
                'notes': '',
                'admin_notes': 'system auto created',
                'allow_anonymous_view': True,
                'status': True,
                'status_detail': 'active'
            }
            if user:
                params.update({
                    'creator': user,
                    'creator_username': user.username,
                    'owner': user,
                    'owner_username': user.username
                })
            else:
                params.update({'creator_username': '', 'owner_username': ''})
            entity = Entity(**params)

            entity.save()
            print('entity created: ', entity.entity_name)

        # loop through all the tables and populate
        # the entity field only if it's null.
        models = apps.get_models()
        # exclude legacy tables
        tables_excluded = [
            'corporate_memberships_corporatemembership',
            'corporate_memberships_corporatemembershiparchive'
        ]
        table_updated = []
        for model in models:
            if TendenciBaseModel in model.__bases__:
                if hasattr(model, 'entity'):
                    table_name = model._meta.db_table
                    if table_name in tables_excluded:
                        continue
                    for row in model.objects.all():
                        if not row.entity:
                            row.entity = entity
                            row.save(update_fields=['entity'])
                    table_updated.append(table_name)

        if verbosity >= 2:
            print()
            print('List of tables updated: ')
            print('\n'.join(table_updated))
            print()

        # GROUP - check if we have a group associated with
        group_exists = Group.objects.filter(entity=entity).exists()
        if not group_exists:
            params = {
                'name': site_display_name,
                'entity': entity,
                'type': 'distribution',
                'email_recipient': site_contact_email,
                'allow_anonymous_view': True,
                'status': True,
                'status_detail': 'active'
            }
            if user:
                params.update({
                    'creator': user,
                    'creator_username': user.username,
                    'owner': user,
                    'owner_username': user.username
                })
            else:
                params.update({'creator_username': '', 'owner_username': ''})
            group = Group(**params)

            try:
                group.save()
                print('Group created: ', group.name)
            except Exception as e:
                print(e)

        print('All done.')
Пример #13
0
    def authenticate(self, *args, **kwargs):
        """Authenticate user using social credentials

        Authentication is made if this is the correct backend, backend
        verification is made by kwargs inspection for current backend
        name presence.
        """
        # Validate backend and arguments. Require that the Social Auth
        # response be passed in as a keyword argument, to make sure we
        # don't match the username/password calling conventions of
        # authenticate.
        if not (self.name and kwargs.get(self.name) and 'response' in kwargs):
            return None

        response = kwargs.get('response')
        request = kwargs.get('request')
        details = self.get_user_details(response)
        uid = self.get_user_id(details, response)
        is_new = False
        try:
            social_user = UserSocialAuth.objects.select_related('user')\
                                                .get(provider=self.name,
                                                     uid=uid)
        except UserSocialAuth.DoesNotExist:
            user = kwargs.get('user')
            if user is None:  # new user
                if not CREATE_USERS:
                    return None

                email = details.get('email')
                if email and ASSOCIATE_BY_MAIL:
                    # try to associate accounts registered with the same email
                    # address, only if it's a single object. ValueError is
                    # raised if multiple objects are returned
                    try:
                        user = User.objects.get(email=email)
                    except MultipleObjectsReturned:
                        raise ValueError('Not unique email address supplied')
                    except User.DoesNotExist:
                        user = None
                if not user:
                    username = self.username(details)
                    user = User.objects.create_user(username=username,
                                                    email=email)
                    is_new = True
                    default_user_groups =[g.strip() for g in (get_setting('module', 'users', 'defaultusergroup')).split(',')]
                    if default_user_groups:
                        from tendenci.apps.user_groups.models import Group, GroupMembership
                        from django.db.models import Q
                        for group_name in default_user_groups:
                            groups = Group.objects.filter(Q(name=group_name) | Q(label=group_name)).filter(allow_self_add=1, status=1, status_detail='active')
                            if groups:
                                group = groups[0]
                            else:
                                # group doesnot exist, so create the group
                                group = Group()
                                group.name  = group_name
                                group.label = group_name
                                group.type = 'distribution'
                                group.show_as_option = 1
                                group.allow_self_add = 1
                                group.allow_self_remove = 1
                                group.creator = user
                                group.creator_username = user.username
                                group.owner =  user
                                group.owner_username = user.username
                                try:
                                    group.save()
                                except:
                                    group = None
                                
                            if group:
                                gm = GroupMembership()
                                gm.group = group
                                gm.member = user
                                gm.creator_id = user.id
                                gm.creator_username = user.username
                                gm.owner_id =  user.id
                                gm.owner_username = user.username
                                gm.save()
                    log_defaults = {
                        'event_id' : 121000,
                        'event_data': '%s (%d) self added by form' % (user._meta.object_name, user.pk),
                        'description': '%s self added' % user._meta.object_name,
                        'user': user,
                        'request': request,
                        'instance': user,
                    }
                    EventLog.objects.log(**log_defaults)
            social_user = self.associate_auth(user, uid, response, details)
        else:
            # This account was registered to another user, so we raise an
            # error in such case and the view should decide what to do on
            # at this moment, merging account is not an option because that
            # would imply update user references on other apps, that's too
            # much intrusive
            if 'user' in kwargs and kwargs['user'] != social_user.user:
                raise ValueError('Account already in use.', social_user)
            user = social_user.user

        # Update user account data.
        self.update_user_details(user, response, details, is_new)

        # Update extra_data storage, unless disabled by setting
        if LOAD_EXTRA_DATA:
            extra_data = self.extra_data(user, uid, response, details)
            if extra_data and social_user.extra_data != extra_data:
                social_user.extra_data = extra_data
                social_user.save()

        return user
Пример #14
0
    def handle(self, *args, **options):
        from tendenci.apps.entities.models import Entity
        from tendenci.apps.user_groups.models import Group
        from tendenci.core.site_settings.utils import get_setting
        from tendenci.core.perms.models import TendenciBaseModel

        verbosity = int(options['verbosity'])

        [entity] = Entity.objects.filter(pk=1)[:1] or [None]
        user = User.objects.get(pk=1)

        site_display_name = get_setting('site',
                                        'global',
                                        'sitedisplayname')
        if not site_display_name:
            site_display_name = 'Default'

        site_contact_name = get_setting('site',
                                        'global',
                                        'sitecontactname')
        site_contact_email = get_setting('site',
                                         'global',
                                         'sitecontactemail')
        site_phone_number = get_setting('site',
                                        'global',
                                        'sitephonenumber')
        site_url = get_setting('site',
                               'global',
                               'siteurl')
        # if there is no entity, create one.
        if not entity:
            entity = Entity(entity_name=site_display_name,
                            entity_type='',
                            contact_name=site_contact_name,
                            phone=site_phone_number,
                            email=site_contact_email,
                            fax='',
                            website=site_url,
                            summary='',
                            notes='',
                            admin_notes='system auto created',
                            allow_anonymous_view=True,
                            creator=user,
                            creator_username=user.username,
                            owner=user,
                            owner_username=user.username,
                            status=True,
                            status_detail='active',
                            id=1)

            entity.save()
            print 'entity created: ', entity.entity_name

        # loop through all the tables and populate
        # the entity field only if it's null.
        models = get_models()
        table_updated = []
        for model in models:
            if TendenciBaseModel in model.__bases__:
                if hasattr(model, 'entity'):
                    table_name = model._meta.db_table
                    for row in model.objects.all():
                        if not row.entity:
                            row.entity = entity
                            row.save()
                    table_updated.append(table_name)

        if verbosity >= 2:
            print
            print 'List of tables updated: '
            print '\n'.join(table_updated)
            print

        # GROUP - check if we have a group associated with
        group_exists = Group.objects.filter(
            name=site_display_name).exists()
        if not group_exists:
            group = Group(name=site_display_name,
                          entity=entity,
                          type='distribution',
                          email_recipient=site_contact_email,
                          allow_anonymous_view=True,
                          creator=user,
                          creator_username=user.username,
                          owner=user,
                          owner_username=user.username,
                          status=True,
                          status_detail='active')

            group.save()
            print 'Group created: ', group.name

        print 'All done.'
Пример #15
0
    def handle(self, *args, **options):
        from tendenci.apps.entities.models import Entity
        from tendenci.apps.user_groups.models import Group
        from tendenci.apps.site_settings.utils import get_setting
        from tendenci.apps.perms.models import TendenciBaseModel

        verbosity = int(options['verbosity'])

        [entity] = Entity.objects.filter(pk=1)[:1] or [None]
        [user] = User.objects.filter(pk=1)[:1] or [None]

        site_display_name = get_setting('site',
                                        'global',
                                        'sitedisplayname')
        if not site_display_name:
            site_display_name = 'Default'

        site_contact_name = get_setting('site',
                                        'global',
                                        'sitecontactname')
        site_contact_email = get_setting('site',
                                         'global',
                                         'sitecontactemail')
        site_phone_number = get_setting('site',
                                        'global',
                                        'sitephonenumber')
        site_url = get_setting('site',
                               'global',
                               'siteurl')
        # if there is no entity, create one.
        if not entity:
            params = {'id': 1,
                      'entity_name': site_display_name,
                      'entity_type': '',
                      'contact_name': site_contact_name,
                      'phone': site_phone_number,
                      'email': site_contact_email,
                      'fax': '',
                      'website': site_url,
                      'summary': '',
                      'notes': '',
                      'admin_notes': 'system auto created',
                      'allow_anonymous_view': True,
                      'status': True,
                      'status_detail': 'active'
                      }
            if user:
                params.update({'creator': user,
                               'creator_username': user.username,
                               'owner': user,
                               'owner_username': user.username
                               })
            else:
                params.update({'creator_username': '',
                               'owner_username': ''
                               })
            entity = Entity(**params)

            entity.save()
            print('entity created: ', entity.entity_name)

        # loop through all the tables and populate
        # the entity field only if it's null.
        models = apps.get_models()
        # exclude legacy tables
        tables_excluded = ['corporate_memberships_corporatemembership',
                           'corporate_memberships_corporatemembershiparchive']
        table_updated = []
        for model in models:
            if TendenciBaseModel in model.__bases__:
                if hasattr(model, 'entity'):
                    table_name = model._meta.db_table
                    if table_name in tables_excluded:
                        continue
                    for row in model.objects.all():
                        if not row.entity:
                            row.entity = entity
                            row.save(update_fields=['entity'])
                    table_updated.append(table_name)

        if verbosity >= 2:
            print()
            print('List of tables updated: ')
            print('\n'.join(table_updated))
            print()

        # GROUP - check if we have a group associated with
        group_exists = Group.objects.filter(entity=entity).exists()
        if not group_exists:
            params = {'name': site_display_name,
                      'entity': entity,
                      'type': 'distribution',
                      'email_recipient': site_contact_email,
                      'allow_anonymous_view': True,
                      'status': True,
                      'status_detail': 'active'
                      }
            if user:
                params.update({'creator': user,
                               'creator_username': user.username,
                               'owner': user,
                               'owner_username': user.username
                               })
            else:
                params.update({'creator_username': '',
                               'owner_username': ''
                               })
            group = Group(**params)

            try:
                group.save()
                print('Group created: ', group.name)
            except Exception as e:
                print(e)

        print('All done.')
Пример #16
0
def create_default_group(sender, app, **kwargs):
    """
    Load default groups if none exist
    or create a group with id=1 if not exist.
    """
    def get_site_display_name():
        setting_table_exists = Setting._meta.db_table in \
                    connection.introspection.table_names()
        if setting_table_exists:
            return get_setting("site", "global", "sitedisplayname")
        return ''

    if app == "user_groups":
        site_name = get_site_display_name().strip()
        if not Group.objects.all():
            call_command("loaddata", "default_groups.json")
            if site_name:
                # update the name and label of the first default user group
                group = Group.objects.get(pk=1)
                group.name = site_name
                group.label = site_name
                group.save()
        else:
            if not Group.objects.filter(pk=1):
                if not site_name:
                    site_name = "Default"

                group = Group()
                group.name = site_name
                group.label = site_name
                group.show_as_option = False
                group.allow_self_add = False
                group.allow_self_remove = False
                group.description = "Initial group auto-generated on site creation."
                group.id = 1

                group.save()