def __init__(self, *args, **kwargs): from base.http import Http403 from site_settings.utils import get_setting from perms.utils import is_member, is_admin from memberships.models import Membership self.user = kwargs.pop('user', None) super(ExportForm, self).__init__(*args, **kwargs) who_can_export = get_setting('module','memberships','memberexport') if who_can_export == 'admin-only': if not is_admin(self.user): raise Http403 elif who_can_export == 'membership-of-same-type': if not is_member(self.user): raise Http403 membership_types = self.user.memberships.values_list('membership_type').distinct() self.fields['app'].queryset = App.objects.filter(membership_types__in=membership_types) elif who_can_export == 'members': if not is_member(self.user): raise Http403 elif who_can_export == 'users': if not self.user.is_authenticated(): raise Http403
def user_sqs(sqs, **kwargs): """ people between admin and anon permission (status+status_detail+(anon OR user)) OR (who_can_view__exact) """ user = kwargs.get('user') member_perms = get_setting('module', 'memberships', 'memberprotection') anon_q = Q(allow_anonymous_view=True) user_q = Q(allow_user_view=True) status_q = Q(status=1, status_detail='active') perm_q = Q(users_can_view__in=user.username) q = reduce(operator.or_, [anon_q, user_q]) q = reduce(operator.and_, [status_q, q]) q = reduce(operator.or_, [q, perm_q]) filtered_sqs = sqs.filter(q) if not is_member(user): # all-members means members can view all other members if member_perms == "all-members": filtered_sqs = filtered_sqs.none() # member type means members can only view members of their same type if member_perms == "member-type": filtered_sqs = filtered_sqs.none() return filtered_sqs
def get_job_price(user, job, pricing): if is_member(user): if job.list_type == 'regular': return pricing.regular_price_member else: return pricing.premium_price_member else: if job.list_type == 'regular': return pricing.regular_price else: return pricing.premium_price
def _permissions_sqs(self, sqs, user, status, status_detail, **kwargs): from perms.utils import is_admin, is_member, is_developer if is_admin(user) or is_developer(user): sqs = sqs.all() else: if user.is_anonymous(): sqs = self._anon_sqs(sqs, status=status, status_detail=status_detail) elif is_member(user): sqs = self._member_sqs(sqs, user, status=status, status_detail=status_detail) else: sqs = self._user_sqs(sqs, user, status=status, status_detail=status_detail) return sqs
def pricing_choices(user): """ Since the list type of a job cannot be determined without the job, Both regular and premium price will be included in the label. """ choices = [] pricings = JobPricing.objects.all() for pricing in pricings: if is_member(user): prices = "%s/%s" % (pricing.regular_price_member, pricing.premium_price_member) else: prices = "%s/%s" % (pricing.regular_price, pricing.premium_price) label = "%s: %s Days for %s" % (pricing.get_title(), pricing.duration, prices) choices.append((pricing.pk, label)) return choices
def roles(self): from perms.utils import is_developer, is_admin, is_member role_set = [] if is_developer(self.user): role_set.append('developer') if is_admin(self.user): role_set.append('admin') if is_member(self.user): role_set.append('member') if self.user.is_active: role_set.append('user') return role_set or ['disabled']
def get_available_pricings(event, user): """ Returns the available pricings of an event for a given user. """ pricings = RegConfPricing.objects.filter( reg_conf=event.registration_configuration, start_dt__lte=datetime.now(), end_dt__gt=datetime.now(), status=True, ) if is_admin(user): # return all if admin is user return pricings if not user.is_authenticated(): # public pricings only pricings = pricings.filter(allow_anonymous=True) else: exclude_list = [] # user permitted pricings for price in pricings: # shown to all users if price.allow_anonymous or price.allow_user: continue # Members allowed if price.allow_member and is_member(user): continue # Group members allowed if price.group and price.group.is_member(user): continue # user failed all permission checks exclude_list.append(price.pk) # exclude pricings user failed permission checks with pricings = pricings.exclude(pk__in=exclude_list) # return the QUERYSET return pricings
def get_available_addons(event, user): """ Returns the available addons of an event for a given user. """ addons = get_active_addons(event) if is_admin(user): # return all if admin is user return addons if not user.is_authenticated(): # public addons only addons = addons.filter(allow_anonymous=True) else: exclude_list = [] # user permitted addons for addon in addons: # shown to all users if addon.allow_anonymous or addon.allow_user: continue # Members allowed if addon.allow_member and is_member(user): continue # Group members allowed if addon.group and addon.group.is_member(user): continue # user failed all permission checks exclude_list.append(addon.pk) # exclude addons user failed permission checks with addons = addons.exclude(pk__in=exclude_list) # return the QUERYSET return addons
def search(self, query=None, *args, **kwargs): """ Search the Django Haystack search index Returns a SearchQuerySet object """ from perms.utils import is_admin, is_member, is_developer sqs = kwargs.get('sqs', SearchQuerySet()) # user information user = kwargs.get('user') or AnonymousUser() user = self._impersonation(user) self.user = user # if the status_detail is something like "published" # then you can specify the kwargs to override status_detail = kwargs.get('status_detail', 'active') if query: sqs = sqs.auto_query(sqs.query.clean(query)) if is_admin(user) or is_developer(user): sqs = sqs.all() else: if user.is_anonymous(): sqs = anon3_sqs(sqs, status_detail=status_detail) elif is_member(user): sqs = self._member_sqs(sqs, user=user, status_detail=status_detail) else: sqs = user3_sqs(sqs, user=user, status_detail=status_detail) # pass return sqs.models(self.model)
def has_perm(self, user, perm, obj=None): # check codename, return false if its a malformed codename try: perm_type = perm.split('.')[-1].split('_')[0] codename = perm.split('.')[1] except IndexError: return False # check group and user permissions, it check the regular users permissions and # the custom groups user permissions if perm in self.get_all_permissions(user): return True if not obj: return False # they are non-admin, should not view any content with status=0 - GJQ if hasattr(obj, "status") and obj.status == 0: return False # object anonymous and use bits if perm_type == 'view': has_attr_aov = hasattr(obj, "allow_anonymous_view") has_attr_auv = hasattr(obj, "allow_user_view") has_attr_amv = hasattr(obj, "allow_member_view") if all([has_attr_aov, has_attr_auv, has_attr_amv]): if obj.allow_anonymous_view: return True if user.is_authenticated() and obj.allow_user_view: return True if is_member(user) and obj.allow_member_view: return True if perm_type == 'change': has_attr_aoe = hasattr(obj, "allow_anonymous_edit") has_attr_aue = hasattr(obj, "allow_user_edit") has_attr_ame = hasattr(obj, "allow_member_edit") if all([has_attr_aoe, has_attr_aue, has_attr_ame]): if obj.allow_anonymous_edit: return True if user.is_authenticated() and obj.allow_user_edit: return True if is_member(user) and obj.allow_member_edit: return True # no anonymous user currently if not user.is_authenticated(): return False if not isinstance(obj, Model): return False # lets check the search index for view permissions # before we ever hit the database, faster if 'view' in perm: try: # test for an index and make the query from haystack import site index = site.get_index(obj.__class__) if can_view(user, obj): return True except: pass # check the permissions on the object level of groups or user perm = '%s.%s' % (obj.pk, perm) if perm in self.get_all_object_permissions(user, obj): return True
def get_pricing(user, event, pricing=None): """ Get a list of qualified pricing in a dictionary form with keys as helpers: qualified: boolean that tells you if they qualify to use this price price: instance of the RegConfPricing model type: string that holds what price type (early, regular or late) failure_type: string of what permissions it failed on """ pricing_list = [] limit = event.registration_configuration.limit spots_taken = get_event_spots_taken(event) spots_left = limit - spots_taken if not pricing: pricing = RegConfPricing.objects.filter( reg_conf=event.registration_configuration, status=True, ) # iterate and create a dictionary based # on dates and permissions # gen_pricing_dict(price_instance, qualifies) for price in pricing: qualifies = True # Admins are always true # This should always be at the top of this code if is_admin(user): qualifies = True pricing_list.append(gen_pricing_dict( price, qualifies, '', admin=True) ) continue # limits if limit > 0: if spots_left < price.quantity: qualifies = False pricing_list.append(gen_pricing_dict( price, qualifies, 'limit') ) continue # public pricing is always true if price.allow_anonymous: qualifies = True pricing_list.append(gen_pricing_dict( price, qualifies, '') ) continue # Admin only price if not any([price.allow_user, price.allow_anonymous, price.allow_member, price.group]): if not is_admin(user): continue # User permissions if price.allow_user and not user.is_authenticated(): qualifies = False pricing_list.append(gen_pricing_dict( price, qualifies, 'user') ) continue # Group and Member permissions if price.group and price.allow_member: qualifies = False if price.group.is_member(user) or is_member(user): qualifies = True pricing_list.append(gen_pricing_dict( price, qualifies, '') ) continue # Group permissions if price.group and not price.group.is_member(user): qualifies = False pricing_list.append(gen_pricing_dict( price, qualifies, 'group') ) continue # Member permissions if price.allow_member and not is_member(user): qualifies = False pricing_list.append(gen_pricing_dict( price, qualifies, 'member') ) continue # pricing is true if doesn't get stopped above pricing_list.append(gen_pricing_dict( price, qualifies, '') ) # pop out the empty ones if they exist pricing_list = [i for i in pricing_list if i] # sort the pricing from smallest to largest # by price sorted_pricing_list = [] if pricing_list: sorted_pricing_list = sorted( pricing_list, key=lambda k: k['amount'] ) # set a default pricing on the first # one that qualifies for price in sorted_pricing_list: if price['qualifies']: price.update({ 'default': True, }) break return sorted_pricing_list
def application_details(request, slug=None, cmb_id=None, imv_id=0, imv_guid=None, secret_hash="", membership_id=0, template_name="memberships/applications/details.html"): """ Display a built membership application and handle submission. """ if not slug: raise Http404 user = request.user app = get_object_or_404(App, slug=slug) if not app.allow_view_by(user): raise Http403 # if this app is for corporation individuals, redirect them to corp-pre page if # they have not passed the security check. is_corp_ind = False corporate_membership = None if hasattr(app, 'corp_app') and app.corp_app: if not cmb_id: # redirect them to the corp_pre page return redirect(reverse('membership.application_details_corp_pre', args=[app.slug])) is_corp_ind = True corporate_membership = get_object_or_404(CorporateMembership, id=cmb_id) # check if they have verified their email or entered the secret code is_verified = False if is_admin(request.user) or app.corp_app.authentication_method == 'admin': is_verified = True elif app.corp_app.authentication_method == 'email': try: indiv_veri = IndivMembEmailVeri8n.objects.get(pk=imv_id, guid=imv_guid) if indiv_veri.verified: is_verified = True except IndivMembEmailVeri8n.DoesNotExist: pass elif app.corp_app.authentication_method == 'secret_code': tmp_secret_hash = md5('%s%s' % (corporate_membership.secret_code, request.session.get('corp_hash_random_string', ''))).hexdigest() if secret_hash == tmp_secret_hash: is_verified = True if not is_verified: return redirect(reverse('membership.application_details_corp_pre', args=[slug])) # log application details view EventLog.objects.log(**{ 'event_id' : 655000, 'event_data': '%s (%d) viewed by %s' % (app._meta.object_name, app.pk, user), 'description': '%s viewed' % app._meta.object_name, 'user': user, 'request': request, 'instance': app, }) initial_dict = {} if hasattr(user, 'memberships'): membership = user.memberships.get_membership() is_only_a_member = [ is_developer(user) == False, is_admin(user) == False, is_member(user) == True, ] if corporate_membership: # exclude corp. reps, creator and owner - they should be able to add new is_only_a_member.append(corporate_membership.allow_edit_by(user)==False) # deny access to renew memberships if all(is_only_a_member): initial_dict = membership.get_app_initial(app) if not membership.can_renew(): return render_to_response("memberships/applications/no-renew.html", { "app": app, "user":user, "membership": membership}, context_instance=RequestContext(request)) pending_entries = [] if hasattr(user, 'appentry_set'): pending_entries = user.appentry_set.filter( is_approved__isnull = True, # pending ) # if an application entry was submitted # after your current membership was created if user.memberships.get_membership(): pending_entries.filter( entry_time__gte = user.memberships.get_membership().subscribe_dt ) app_entry_form = AppEntryForm( app, request.POST or None, request.FILES or None, user=user, corporate_membership=corporate_membership, initial=initial_dict, ) if request.method == "POST": if app_entry_form.is_valid(): entry = app_entry_form.save(commit=False) entry_invoice = entry.save_invoice() if user.is_authenticated(): entry.user = user entry.is_renewal = all(is_only_a_member) # add all permissions and save the model entry = update_perms_and_save(request, app_entry_form, entry) # administrators go to approve/disapprove page if is_admin(user): return redirect(reverse('membership.application_entries', args=[entry.pk])) # send "joined" notification Notice.send_notice( entry=entry, request = request, emails=entry.email, notice_type='join', membership_type=entry.membership_type, ) if entry_invoice.total == 0: if not entry_invoice.is_tendered: entry_invoice.tender(request.user) # online payment if entry_invoice.total>0 and entry.payment_method and entry.payment_method.is_online: return HttpResponseRedirect(reverse( 'payments.views.pay_online', args=[entry_invoice.pk, entry_invoice.guid] )) if not entry.approval_required(): entry.approve() # silence old memberships within renewal period Membership.objects.silence_old_memberships(entry.user) # get user from the membership since it's null in the entry entry.user = entry.membership.user membership_total = Membership.objects.filter(status=True, status_detail='active').count() # send "approved" notification Notice.send_notice( request = request, emails=entry.email, notice_type='approve', membership=entry.membership, membership_type=entry.membership_type, ) if not user.is_authenticated(): from django.core.mail import send_mail from django.utils.http import int_to_base36 from django.contrib.auth.tokens import default_token_generator from site_settings.utils import get_setting token_generator = default_token_generator site_url = get_setting('site', 'global', 'siteurl') site_name = get_setting('site', 'global', 'sitedisplayname') # send new user account welcome email (notification) notification.send_emails([entry.user.email],'user_welcome', { 'site_url': site_url, 'site_name': site_name, 'uid': int_to_base36(entry.user.id), 'user': entry.user, 'username': entry.user.username, 'token': token_generator.make_token(entry.user), }) # log - entry approval EventLog.objects.log(**{ 'event_id' : 1082101, 'event_data': '%s (%d) approved by %s' % (entry._meta.object_name, entry.pk, entry.judge), 'description': '%s viewed' % entry._meta.object_name, 'user': user, 'request': request, 'instance': entry, }) # log - entry submission EventLog.objects.log(**{ 'event_id' : 1081000, 'event_data': '%s (%d) submitted by %s' % (entry._meta.object_name, entry.pk, request.user), 'description': '%s viewed' % entry._meta.object_name, 'user': user, 'request': request, 'instance': entry, }) return redirect(entry.confirmation_url) return render_to_response(template_name, { 'app': app, 'app_entry_form': app_entry_form, 'pending_entries': pending_entries, }, context_instance=RequestContext(request))