Example #1
0
    def render(self, context, instance, placeholder):
        # Obtain user
        user = None  # type: User
        if hasattr(context, 'request') and hasattr(context.request, 'user'):
            user = context.request.user
        if 'user' in context:
            user = context['user']

        if not user:
            user = AnonymousUser()  # Should never happen

        # This could be coded more efficiently, but is this way for clarity
        if instance.mode == MODE_IN_GROUP:
            if user.groups.filter(id=instance.permitted_group.id).exists():
                context['instance'] = instance
        elif instance.mode == MODE_NOT_IN_GROUP:
            if not (user.is_anonymous() or user.groups.filter(
                    id=instance.permitted_group.id).exists()):
                context['instance'] = instance
        elif instance.mode == MODE_ANONYMOUS:
            if user.is_anonymous():
                context['instance'] = instance
        elif instance.mode == MODE_NOT_IN_GROUP_PLUS_ANON:
            if user.is_anonymous() or not user.groups.filter(
                    id=instance.permitted_group.id).exists():
                context['instance'] = instance

        return context
Example #2
0
def get_user(request):
    def get_response(data):
        return HttpResponse(json.dumps(data),
            content_type="application/json")

    response_data = {
        'errors': [],
    }

    try:
        session_key = request.GET['session_key']
    except KeyError:
        response_data['errors'].append('Session key (session_key) not provided')
        return get_response(response_data)

    response_data['isAnonymous'] = True
    response_data['isSuperuser'] = False

    try:
        session = Session.objects.get(session_key=session_key)
        uid = session.get_decoded()['_auth_user_id']
        user = User.objects.get(id=uid)
    except Session.DoesNotExist:
        response_data['errors'].append('Invalid session key')
        user = AnonymousUser()
        return get_response(response_data)

    response_data['isSuperuser'] = user.is_superuser
    response_data['isAnonymous'] = user.is_anonymous()

    if not user.is_anonymous():
        response_data['userId'] = user.id

    return get_response(response_data)
Example #3
0
def auth_org_perm(request):
    """
    Returns context variables required by apps that use Django's authentication
    system.

    If there is no 'user' attribute in the request, uses AnonymousUser (from
    django.contrib.auth).
    """
    if hasattr(request, 'user'):
        user = request.user
    else:
        from django.contrib.auth.models import AnonymousUser
        user = AnonymousUser()

    org = request.session.get('org', None)
    org_id = org and org.pk or 0

    def _is_root_org(org_id):
        try:
            org_id = int(org_id)
            if org_id:
                if Organization.objects.get(pk=org_id).parent:
                    return False
                else:
                    return True
            else:
                return False
        except:
            return False

    if user.is_anonymous() or not org_id or request.path == '/':
        return {
            'INDUSTRY': (org and org.style == 'retail') and 'retail'
            or 'restaurant'
        }

    return {
        'is_root_org':
        _is_root_org(org_id),
        'operms':
        OPermWrapper(user, org_id),
        'warehouse_perm':
        user.get_warehouses(org_id),
        'warehouse_write_perm':
        user.get_warehouses(org_id, perms=['warehouse_write']),
        'is_superior':
        user.is_org_superuser(org_id),
        #'wm_perm':user.get_warehouses(org_id,perms=['warehouse_manage']),
        #'pandian_perm':user.get_warehouses(org_id,perms=['warehouse_manage','warehouse_pandian_read','warehouse_pandian_write']),
        #'caigou_perm':user.get_warehouses(org_id,perms=['warehouse_manage','warehouse_caigou_read','warehouse_caigou_write']),
        #'tuihuo_perm':user.get_warehouses(org_id,perms=['warehouse_manage','warehouse_tuihuo_read','warehouse_tuihuo_write']),
        #'lingyong_perm':user.get_warehouses(org_id,perms=['warehouse_manage','warehouse_lingyong_read','warehouse_lingyong_write']),
        #'tuiliao_perm':user.get_warehouses(org_id,perms=['warehouse_manage','warehouse_tuiliao_read','warehouse_tuiliao_write']),
        #'xiaoshou_perm':user.get_warehouses(org_id,perms=['warehouse_manage','warehouse_xiaoshou_read','warehouse_xiaoshou_write']),
        'agile':
        STYLE == 'agile',
        'INDUSTRY': (org and org.style == 'retail') and 'retail'
        or 'restaurant'
    }
class FacebookConnectEmailBackend(FacebookConnectBackend):
    """ Facebook backend that should be used together with
    some email authentication backend. Email is considered required
    and unique.
    """

    def get_user_data(self, params):
        # retrieve additional user info via facebook graph api
        api = facebook.GraphAPI(params['access_token'])
        try:
            data = api.get_object('me')
            # prevent fake email accounts creation
            if len(data.get('email', '')) > 75:
                data['email'] = None
            return data
        except facebook.GraphAPIError:
            return {'email': None}

    def create_facebook_profile(self, uid, params):
        # Check that the username and email is unique,
        # and if so, create a user and profile
        assert 'email' in facebook_connect.settings.FACEBOOK_REQUIRED_FIELDS
        user_data = self.get_user_data(params)

        email = user_data['email']

        # If there is no facebook email available then user must login first
        if not email:
            self._existing_user = AnonymousUser()
            return False

        try:
            self._existing_user = User.objects.get(Q(username=uid) | Q(email=email))
            return False
        except User.DoesNotExist:
            user = User.objects.create_user(
                username=uid,
                email=email,
                password=User.objects.make_random_password(16)
            )
            user.first_name = user_data.get('first_name', '')
            user.last_name = user_data.get('last_name', '')
            user.save()
            return FacebookProfile.objects.create(user=user, uid=uid)

    def associate_redirect(self, request):
        if self._existing_user.is_anonymous():
            return ('facebook_email_associate', [], {})
        return super(FacebookConnectEmailBackend, self).associate_redirect(request)
Example #5
0
def ajax_user(request, event_id):
    """Ajax query for user validation
    The parameters are email and memberid and pricing.
    The user that matches the given email/memberid will be checked
    if he/she can still register in the event with the given pricing.
    """
    event = get_object_or_404(Event, pk=event_id)
    
    if not get_setting('module', 'events', 'anonymousmemberpricing'):
        raise Http404
    
    memberid = request.GET.get('memberid', None)
    email = request.GET.get('email', None)
    pricingid = request.GET.get('pricingid', None)
    
    pricing = get_object_or_404(RegConfPricing, pk=pricingid)
    
    user = AnonymousUser()
    
    allow_memberid = get_setting('module', 'events', 'memberidpricing')
    if memberid and allow_memberid:# memberid takes priority over email
        membership = Membership.objects.first(member_number=memberid)
        if hasattr(membership, 'user'):
            user = membership.user
    elif email:
        users = User.objects.filter(email=email)
        if users:
            user = users[0]
    
    data = json.dumps(None)
    #check if already registered
    if not (user.is_anonymous() or pricing.allow_anonymous):
        used = Registrant.objects.filter(user=user)
        if used:
            if not (pricing.allow_anonymous or user.profile.is_superuser):
                data = json.dumps({"error":"REG"})
            else:
                data = json.dumps({"message":"REG"})
    
    #check if can use
    can_use = can_use_pricing(event, user, pricing)
    if not can_use:
        if not get_setting('module', 'events', 'sharedpricing'):
            data = json.dumps({"error":"INVALID"})
        else:
            data = json.dumps({"error":"SHARED"})
    
    return HttpResponse(data, mimetype="text/plain")
Example #6
0
def ajax_user(request, event_id):
    """Ajax query for user validation
    The parameters are email and memberid and pricing.
    The user that matches the given email/memberid will be checked
    if he/she can still register in the event with the given pricing.
    """
    event = get_object_or_404(Event, pk=event_id)

    if not get_setting('module', 'events', 'anonymousmemberpricing'):
        raise Http404

    memberid = request.GET.get('memberid', None)
    email = request.GET.get('email', None)
    pricingid = request.GET.get('pricingid', None)

    pricing = get_object_or_404(RegConfPricing, pk=pricingid)

    user = AnonymousUser()

    allow_memberid = get_setting('module', 'events', 'memberidpricing')
    if memberid and allow_memberid:  # memberid takes priority over email
        membership = Membership.objects.first(member_number=memberid)
        if hasattr(membership, 'user'):
            user = membership.user
    elif email:
        users = User.objects.filter(email=email)
        if users:
            user = users[0]

    data = json.dumps(None)
    #check if already registered
    if not (user.is_anonymous() or pricing.allow_anonymous):
        used = Registrant.objects.filter(user=user)
        if used:
            if not (pricing.allow_anonymous or user.profile.is_superuser):
                data = json.dumps({"error": "REG"})
            else:
                data = json.dumps({"message": "REG"})

    #check if can use
    can_use = can_use_pricing(event, user, pricing)
    if not can_use:
        if not get_setting('module', 'events', 'sharedpricing'):
            data = json.dumps({"error": "INVALID"})
        else:
            data = json.dumps({"error": "SHARED"})

    return HttpResponse(data, mimetype="text/plain")
Example #7
0
    def test_anonymous_user_is_anonymous_authenticated_method_deprecation(self):
        a = AnonymousUser()
        deprecation_message = (
            'Using user.is_authenticated() and user.is_anonymous() as a '
            'method is deprecated. Remove the parentheses to use it as an '
            'attribute.'
        )
        # Backwards-compatibility callables
        with warnings.catch_warnings(record=True) as warns:
            warnings.simplefilter('always')  # prevent warnings from appearing as errors
            self.assertTrue(a.is_anonymous())
            self.assertEqual(len(warns), 1)
            self.assertEqual(str(warns[0].message), deprecation_message)

        with warnings.catch_warnings(record=True) as warns:
            warnings.simplefilter('always')  # prevent warnings from appearing as errors
            self.assertFalse(a.is_authenticated())
            self.assertEqual(len(warns), 1)
            self.assertEqual(str(warns[0].message), deprecation_message)
Example #8
0
def ajax_pricing(request, event_id, template_name="events/registration/pricing.html"):
    """Ajax query for pricing info.
    The parameters are email and memberid.
    Both are not unique to a user but are assumed to be unique.
    On cases that there are multiple matches,
    the first match will be the basis of the pricing list.
    If the setting "sharedpricing" is enabled this ajax check will consider
    the emails associated with the session.
    ** This now also returns ADDON info in the same format.
    """
    event = get_object_or_404(Event, pk=event_id)
    
    if not get_setting('module', 'events', 'anonymousmemberpricing'):
        raise Http404
    
    memberid = request.GET.get('memberid', None)
    email = request.GET.get('email', None)
    
    user = AnonymousUser()
    allow_memberid = get_setting('module', 'events', 'memberidpricing')
    shared_pricing = get_setting('module', 'events', 'sharedpricing')
    
    if memberid and allow_memberid:  # memberid takes priority over email
        membership = Membership.objects.first(member_number=memberid)
        if hasattr(membership, 'user'):
            user = membership.user
    elif email:
        users = User.objects.filter(email=email)
        if users:
            user = users[0]
    
    # register user in user list
    user_pks = request.session.get('user_list', [])
    if not user.is_anonymous():
        user_pks.append(user.pk)
    request.session['user_list'] = user_pks

    # Set up available pricings
    all_pricings = get_active_pricings(event)
    if shared_pricing:
        # use entire user list
        shareable_users = User.objects.filter(pk__in=user_pks)
        available_pricings = get_pricings_for_list(event, shareable_users)
    else:
        shareable_users = None
        available_pricings = get_available_pricings(event, user)
    pricing_list = []
    for pricing in all_pricings:
        p_dict = {
            'title':pricing.title,
            'quantity':pricing.quantity,
            'price':str(pricing.price),
            'pk':pricing.pk,
            'enabled':True,
            'is_public':pricing.allow_anonymous,
        }
        
        if pricing not in available_pricings:
            p_dict['enabled'] = False
        
        pricing_list.append(p_dict)
        
    all_addons = get_active_addons(event)
    if shared_pricing:
        available_addons = get_addons_for_list(event, shareable_users)
    else:
        available_addons = get_available_addons(event, user)
    
    a_list = []
    for addon in all_addons:
        d = model_to_dict(addon)
        d['options'] = addon.options
        if addon in available_addons:
            # temporarily allow anon viewing for this email
            d['allow_anonymous'] = True
        a_list.append(d)
    
    form = render_to_string('events/addons/addon-add-box.html',
        {'addons':a_list, 'anon_pricing':True},
        RequestContext(request))
            
    data = json.dumps({
        'pricings':pricing_list,
        'add-addons-form':form,
    })
    return HttpResponse(data, mimetype="text/plain")
Example #9
0
def ajax_pricing(request,
                 event_id,
                 template_name="events/registration/pricing.html"):
    """Ajax query for pricing info.
    The parameters are email and memberid.
    Both are not unique to a user but are assumed to be unique.
    On cases that there are multiple matches,
    the first match will be the basis of the pricing list.
    If the setting "sharedpricing" is enabled this ajax check will consider
    the emails associated with the session.
    ** This now also returns ADDON info in the same format.
    """
    event = get_object_or_404(Event, pk=event_id)

    if not get_setting('module', 'events', 'anonymousmemberpricing'):
        raise Http404

    memberid = request.GET.get('memberid', None)
    email = request.GET.get('email', None)

    user = AnonymousUser()
    allow_memberid = get_setting('module', 'events', 'memberidpricing')
    shared_pricing = get_setting('module', 'events', 'sharedpricing')

    if memberid and allow_memberid:  # memberid takes priority over email
        membership = Membership.objects.first(member_number=memberid)
        if hasattr(membership, 'user'):
            user = membership.user
    elif email:
        users = User.objects.filter(email=email)
        if users:
            user = users[0]

    # register user in user list
    user_pks = request.session.get('user_list', [])
    if not user.is_anonymous():
        user_pks.append(user.pk)
    request.session['user_list'] = user_pks

    # Set up available pricings
    all_pricings = get_active_pricings(event)
    if shared_pricing:
        # use entire user list
        shareable_users = User.objects.filter(pk__in=user_pks)
        available_pricings = get_pricings_for_list(event, shareable_users)
    else:
        shareable_users = None
        available_pricings = get_available_pricings(event, user)
    pricing_list = []
    for pricing in all_pricings:
        p_dict = {
            'title': pricing.title,
            'quantity': pricing.quantity,
            'price': str(pricing.price),
            'pk': pricing.pk,
            'enabled': True,
            'is_public': pricing.allow_anonymous,
        }

        if pricing not in available_pricings:
            p_dict['enabled'] = False

        pricing_list.append(p_dict)

    all_addons = get_active_addons(event)
    if shared_pricing:
        available_addons = get_addons_for_list(event, shareable_users)
    else:
        available_addons = get_available_addons(event, user)

    a_list = []
    for addon in all_addons:
        d = model_to_dict(addon)
        d['options'] = addon.options
        if addon in available_addons:
            # temporarily allow anon viewing for this email
            d['allow_anonymous'] = True
        a_list.append(d)

    form = render_to_string('events/addons/addon-add-box.html', {
        'addons': a_list,
        'anon_pricing': True
    }, RequestContext(request))

    data = json.dumps({
        'pricings': pricing_list,
        'add-addons-form': form,
    })
    return HttpResponse(data, mimetype="text/plain")
Example #10
0
def login(request):
    redirect_to = request.POST.get("next", request.GET.get("next"))
    request_token = request.POST.get("request_token", request.GET.get("request_token"))
    api_key = request.POST.get("api_key", request.GET.get("api_key"))

    if not (redirect_to and request_token and api_key):
        # return HttpResponse("parameter missing", status=403)
        return TemplateResponse(request, 'djssoserver/403.html', {"errormsg":"parameter missing",
                    "source":urlparse.urljoin(redirect_to, '/')}, status=403)

    rt = RequestToken.load_info(request_token)
    if not rt:
        # return HttpResponse("invalid request token", status=403)
        return TemplateResponse(request, 'djssoserver/403.html', {"errormsg":"invalid request token",
                    "source":urlparse.urljoin(redirect_to, '/')}, status=403)

    # verify remote host
    url_info_to = urlparse.urlparse(redirect_to)
    try:
        SSO.objects.get(host=url_info_to.netloc, credential__apikey=api_key)
    except SSO.DoesNotExist:
        # return HttpResponse("request deny for remote host", status=403)
        return TemplateResponse(request, 'djssoserver/403.html', {"errormsg":"request deny for remote host",
                    "source":urlparse.urljoin(redirect_to, '/')}, status=403)

    okresp = HttpResponseRedirect(append_tokens(redirect_to,
                                                request_token=request_token,
                                                auth_token=gen_auth_token(request_token)))

    ssouser = request.user  # current logged-in user by default

    if request.method == "POST":
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            RequestToken.bind_info(request_token, form.get_user())
            return okresp
    else:  # GET
        form = AuthenticationForm(request)
        bContinueWithCurrentAccount = request.GET.get("cwca", None)

        if bContinueWithCurrentAccount == "yes":  # confirmed: continue with logged in account
            RequestToken.bind_info(request_token, request.user)
            return okresp
        elif bContinueWithCurrentAccount == "no":  # confirmed: login with another account
            ssouser = AnonymousUser()
        else:  # ask to login with current account or switch to a new account, or login form if not logged-in
            if request.GET.get("noconfirm", '0') == '1' and not ssouser.is_anonymous():
                RequestToken.bind_info(request_token, request.user)
                return okresp
            pass

    current_site = get_current_site(request)

    context = {
        'form': form,
        "next": redirect_to,
        'site': current_site,
        'site_name': current_site.name,
        'remote_app': url_info_to.netloc,
        "sso_timeout": SSO_REQUEST_TOKEN_TTL,
        "ssouser": ssouser,
        "req": request  # name req will not confilict with request if django.core.context_processors.request enabled

    }

    return TemplateResponse(request, 'djssoserver/ssologin.html', context)