Example #1
0
def get_cached_user(request):
    from django.contrib.auth.models import AnonymousUser

    if not hasattr(request, '_cached_user'):
        try:
            key = CACHE_KEY % request.session[SESSION_KEY]
            user = cache.cache.get(key)
        except KeyError:
            user = AnonymousUser()
        else:
            if user is None:
                user = get_user(request)

                # Try to populate profile cache if profile is installed
                if profile_model:
                    try:
                        user.get_profile()
                    # Handle exception for user with no profile and AnonymousUser
                    except (profile_model.DoesNotExist, AttributeError):
                        pass

                cache.cache.set(key, user)

        request._cached_user = user

    return request._cached_user
Example #2
0
def get_cached_user(request):
    from django.contrib.auth.models import AnonymousUser

    if not hasattr(request, '_cached_user'):
        try:
            key = CACHE_KEY % request.session[SESSION_KEY]
            user = cache.cache.get(key)
        except KeyError:
            user = AnonymousUser()
        else:
            if user is None:
                user = get_user(request)

                # Try to populate profile cache if profile is installed
                if profile_model:
                    try:
                        user.get_profile()
                    # Handle exception for user with no profile and AnonymousUser
                    except (profile_model.DoesNotExist, AttributeError):
                        pass

                cache.cache.set(key, user)

        request._cached_user = user

    return request._cached_user
def get_cached_user(request):
    if not hasattr(request, "_cached_user"):
        try:
            key = CACHE_KEY % request.session[SESSION_KEY]
            user = cache.get(key)
        except KeyError:
            user = AnonymousUser()

        if user is None:
            user = get_user(request)
            user.get_profile()
            try:
                user.social = user.social_auth.all()[0]
            except IndexError:
                user.social = None
            cache.set(key, user)
        request._cached_user = user
    return request._cached_user
Example #4
0
    def has_perm(self, user_obj, perm, obj=None):
        '''
        main method, calls other methods based on permission type queried
        '''
        if not user_obj.is_authenticated():
            allowed_tokens = getattr(user_obj, 'allowed_tokens', [])
            user_obj = AnonymousUser()
            user_obj.allowed_tokens = allowed_tokens

        if obj is None:
            return False

        try:
            perm_label, perm_type = perm.split('.')
            perm_action, perm_ct = perm_type.split('_')
        except:
            return False

        if perm_label != self.app_label:
            return False

        ct = ContentType.objects.get_for_model(obj)
        if ct.name != perm_ct:
            return False

        method_name = '_has_%s_perm' % perm_action

        # run any custom perms per model, continue if not None
        # allows complete overriding of standard authorisation, eg for public
        # experiments
        model_spec_perm = getattr(obj, method_name,
                                  lambda *args, **kwargs: None)(user_obj)
        if type(model_spec_perm) == bool:
            return model_spec_perm

        #get_acls
        obj_acls = ObjectACL.objects.filter(
            content_type=ct, object_id=obj.id).filter(
                self.get_perm_bool(perm_action)).filter(
                    ObjectACL.get_effective_query())

        query = Q(pluginId='django_user',
                  entityId=str(user_obj.id))

        if user_obj.is_authenticated():
            for name, group in user_obj.get_profile().ext_groups:
                query |= Q(pluginId=name, entityId=str(group))
        else:
            # the only authorisation available for anonymous users is tokenauth
            tgp = TokenGroupProvider()
            for name, group in tgp.getGroups(user_obj):
                query |= Q(pluginId=name, entityId=str(group))

        return obj_acls.filter(query).count() > 0
Example #5
0
 def create_session(self, username, timestamp, auth):
     """ Get a new session """
     # Create a new session key
     session = sha1(str(random.random())[2:]).hexdigest()
     # Check the time skew
     time_now = datetime.now()
     try:
         time_client = datetime.strptime(str(timestamp), TIME_FORMAT)
     except ValueError:
         return {'status': 'BADCALL Invalid time format.'}
     if time_client < time_now - TIME_SKEW or time_client > time_now + TIME_SKEW:
         return {'status': 'BADSESSION Clock skew too great. Maximum of %s minutes allowed.' % settings.XMLRPC_MAX_TIME_SKEW}
     # Find the user
     try:
         user = User.objects.get(username = username)
     except User.DoesNotExist:
         # No such user
         user = AnonymousUser()
         if settings.XMLRPC_DEBUG:
             return {'status': 'BADSESSION User not found: %s' % username}
     else:
         # Check the permissions
         if user.has_perm('xmlrpc.access_xmlrpc'):
             # Get the user's shared secret
             user_profile = user.get_profile()
             # Check the authentication
             vrf_auth = sha1(username + str(timestamp) + user_profile.xmlrpc_key).hexdigest()
             if auth == vrf_auth:
                 # Create the new authentication
                 new_auth = sha1(user.username + session + user_profile.xmlrpc_key).hexdigest()
                 xmlrpc_session = self.create(user = user, session = session, auth = new_auth)
             elif settings.XMLRPC_DEBUG:
                 # Authentication failed
                 return {'status': 'BADSESSION Initial authentication failed.'}
         elif settings.XMLRPC_DEBUG:
             # Not allowed
             return {'status': 'FORBIDDEN You are not allowed to access the XML-RPC interface.'}
     # Return the status and the session key
     return {'status': 'OK', 'session': session}
Example #6
0
    def has_perm(self, user_obj, perm, obj=None):
        '''
        main method, calls other methods based on permission type queried
        '''
        if not user_obj.is_authenticated():
            allowed_tokens = getattr(user_obj, 'allowed_tokens', [])
            user_obj = AnonymousUser()
            user_obj.allowed_tokens = allowed_tokens

        if obj is None:
            return False

        try:
            perm_label, perm_type = perm.split('.')
            # the following is necessary because of the ridiculous naming
            # of 'Dataset_File'......
            type_list = perm_type.split('_')
            perm_action = type_list[0]
            perm_ct = '_'.join(type_list[1:])
        except:
            return False

        if perm_label != self.app_label:
            return False

        ct = ContentType.objects.get_for_model(obj)
        if ct.model != perm_ct:
            return False

        method_name = '_has_%s_perm' % perm_action

        # run any custom perms per model, continue if not None
        # allows complete overriding of standard authorisation, eg for public
        # experiments
        model_spec_perm = getattr(obj, method_name,
                                  lambda *args, **kwargs: None)(user_obj)
        if type(model_spec_perm) == bool:
            return model_spec_perm
        elif model_spec_perm is not None:
            # pass auth to a different object, if False try this ACL
            # works when returned object is parent.
            # makes it impossible to 'hide' child objects
            if type(model_spec_perm) not in (list, set, QuerySet):
                model_spec_perm = [model_spec_perm]
            for msp in model_spec_perm:
                new_ct = ContentType.objects.get_for_model(msp)
                new_perm = '%s.%s_%s' % (perm_label, perm_action, new_ct)
                if user_obj.has_perm(new_perm, msp):
                    return True

        #get_acls
        obj_acls = ObjectACL.objects\
            .filter(content_type=ct, object_id=obj.id)\
            .filter(self.get_perm_bool(perm_action))\
            .filter(ObjectACL.get_effective_query())

        query = Q(pluginId='django_user',
                  entityId=str(user_obj.id))

        if user_obj.is_authenticated():
            for name, group in user_obj.get_profile().ext_groups:
                query |= Q(pluginId=name, entityId=str(group))
        else:
            # the only authorisation available for anonymous users is tokenauth
            tgp = TokenGroupProvider()
            for group in tgp.getGroups(user_obj):
                query |= Q(pluginId=tgp.name, entityId=str(group))

        return obj_acls.filter(query).count() > 0
Example #7
0
    def has_perm(self, user_obj, perm, obj=None):
        '''
        main method, calls other methods based on permission type queried
        '''
        if not user_obj.is_authenticated():
            allowed_tokens = getattr(user_obj, 'allowed_tokens', [])
            user_obj = AnonymousUser()
            user_obj.allowed_tokens = allowed_tokens

        if obj is None:
            return False

        try:
            perm_label, perm_type = perm.split('.')
            # the following is necessary because of the ridiculous naming
            # of 'Dataset_File'......
            type_list = perm_type.split('_')
            perm_action = type_list[0]
            perm_ct = '_'.join(type_list[1:])
        except:
            return False

        if perm_label != self.app_label:
            return False

        ct = ContentType.objects.get_for_model(obj)
        if ct.model != perm_ct:
            return False

        method_name = '_has_%s_perm' % perm_action

        # run any custom perms per model, continue if not None
        # allows complete overriding of standard authorisation, eg for public
        # experiments
        model_spec_perm = getattr(obj, method_name,
                                  lambda *args, **kwargs: None)(user_obj)
        if type(model_spec_perm) == bool:
            return model_spec_perm
        elif model_spec_perm is not None:
            # pass auth to a different object, if False try this ACL
            # works when returned object is parent.
            # makes it impossible to 'hide' child objects
            if type(model_spec_perm) not in (list, set, QuerySet):
                model_spec_perm = [model_spec_perm]
            for msp in model_spec_perm:
                new_ct = ContentType.objects.get_for_model(msp)
                new_perm = '%s.%s_%s' % (perm_label, perm_action, new_ct)
                if user_obj.has_perm(new_perm, msp):
                    return True

        #get_acls
        obj_acls = ObjectACL.objects\
            .filter(content_type=ct, object_id=obj.id)\
            .filter(self.get_perm_bool(perm_action))\
            .filter(ObjectACL.get_effective_query())

        query = Q(pluginId='django_user', entityId=str(user_obj.id))

        if user_obj.is_authenticated():
            for name, group in user_obj.get_profile().ext_groups:
                query |= Q(pluginId=name, entityId=str(group))
        else:
            # the only authorisation available for anonymous users is tokenauth
            tgp = TokenGroupProvider()
            for group in tgp.getGroups(user_obj):
                query |= Q(pluginId=tgp.name, entityId=str(group))

        return obj_acls.filter(query).count() > 0
Example #8
0
def userregister(request):
    """
    A registration form endpoint for registering and logging in.
    
    This view will permit a user to register if their username is unique, 
    their password is not empty, and an email address is provided. 
    This view returns JSON, with a 'success' property if registration or
    login was successful.

    If registration was successful, the JSON also contains
    a 'redirect' property.

    If registration was unsuccessful, the JSON also contains
    a 'message' property, describing why the registration failed.
    
    Parameters:
        request -- An HttpRequest, with the form submitted parameters.
        
    Returns:
        A JSON object indicating if registration/login was successful.
    """
    username = request.POST.get('newusername', None)
    password = request.POST.get('newpassword1', None)
    email = request.POST.get('email', None)
    fname = request.POST.get('firstname', None)
    lname = request.POST.get('lastname', None)
    hint = request.POST.get('passwordhint', None)
    org = request.POST.get('organization', None)
    anonymous = False
    status = { 'success':False }
    if username != '' and password != '':
        if (username == 'anonymous' and password == 'anonymous'):
            user = AnonymousUser()
        else:
            name_exists = User.objects.filter(username__exact=username)
            if name_exists:
                status['message'] ='name exists'
                return HttpResponse(json.dumps(status), mimetype='application/json')

            email_exists = email != '' and User.objects.filter(email__exact = email)
            if email_exists:
                status['message'] ='email exists'
                return HttpResponse(json.dumps(status), mimetype='application/json')

            try:
                User.objects.create_user(username, email, password)
            except Exception as error:
                status['message'] = 'Sorry, we weren\'t able to create your account.'
                return HttpResponse(json.dumps(status), mimetype='application/json')

            # authenticate the user, and add additional registration info
            user = authenticate(username=username, password=password)

            user.first_name = fname
            user.last_name = lname
            user.save()

            profile = user.get_profile()
            profile.organization = org
            profile.pass_hint = hint
            profile.save()

            login( request, user )

        status['success'] = True
        status['redirect'] = '/districtmapping/plan/0/view/'
        return HttpResponse(json.dumps(status), mimetype='application/json')
    else:
        status['message'] = 'Username cannot be empty.'
        return HttpResponse(json.dumps(status), mimetype='application/json')
from django.contrib.auth.models import AnonymousUser
from django.core.urlresolvers import reverse
from django.test import TestCase

from mock import MagicMock
from test_utils import RequestFactory

from ..middleware import ProfileMiddleware
from ..models import Profile


complete_user = AnonymousUser()
complete_user.is_authenticated = MagicMock(return_value=True)
complete_user.get_profile = MagicMock(return_value=Profile(name="Mock name"))

incomplete_user = AnonymousUser()
incomplete_user.is_authenticated = MagicMock(return_value=True)
incomplete_user.get_profile = MagicMock(return_value=Profile())


class TestProfileMiddleware(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def test_safe_view_request(self):
        request = self.factory.get(reverse("users_edit"))
        middleware = ProfileMiddleware()
        response = middleware.process_request(request)
        self.assertFalse(response)

    def test_safe_path_request(self):
Example #10
0
def userregister(request):
    """
    A registration form endpoint for registering and logging in.
    
    This view will permit a user to register if their username is unique, 
    their password is not empty, and an email address is provided. 
    This view returns JSON, with a 'success' property if registration or
    login was successful.

    If registration was successful, the JSON also contains
    a 'redirect' property.

    If registration was unsuccessful, the JSON also contains
    a 'message' property, describing why the registration failed.
    
    Parameters:
        request -- An HttpRequest, with the form submitted parameters.
        
    Returns:
        A JSON object indicating if registration/login was successful.
    """
    username = request.POST.get('newusername', None)
    password = request.POST.get('newpassword1', None)
    email = request.POST.get('email', None)
    fname = request.POST.get('firstname', None)
    lname = request.POST.get('lastname', None)
    hint = request.POST.get('passwordhint', None)
    org = request.POST.get('organization', None)
    anonymous = False
    status = {'success': False}
    if username != '' and password != '':
        if (username == 'anonymous' and password == 'anonymous'):
            user = AnonymousUser()
        else:
            name_exists = User.objects.filter(username__exact=username)
            if name_exists:
                status['message'] = 'name exists'
                return HttpResponse(json.dumps(status),
                                    mimetype='application/json')

            email_exists = email != '' and User.objects.filter(
                email__exact=email)
            if email_exists:
                status['message'] = 'email exists'
                return HttpResponse(json.dumps(status),
                                    mimetype='application/json')

            try:
                User.objects.create_user(username, email, password)
            except Exception as error:
                status[
                    'message'] = 'Sorry, we weren\'t able to create your account.'
                return HttpResponse(json.dumps(status),
                                    mimetype='application/json')

            # authenticate the user, and add additional registration info
            user = authenticate(username=username, password=password)

            user.first_name = fname
            user.last_name = lname
            user.save()

            profile = user.get_profile()
            profile.organization = org
            profile.pass_hint = hint
            profile.save()

            login(request, user)

        status['success'] = True
        status['redirect'] = '/districtmapping/plan/0/view/'
        return HttpResponse(json.dumps(status), mimetype='application/json')
    else:
        status['message'] = 'Username cannot be empty.'
        return HttpResponse(json.dumps(status), mimetype='application/json')
from mock import MagicMock
from django.contrib.auth.models import AnonymousUser
from django.core.urlresolvers import reverse
from django.test import TestCase
from test_utils import RequestFactory

from ..middleware import ProfileMiddleware
from ..models import Profile


complete_user = AnonymousUser()
complete_user.is_authenticated = MagicMock(return_value=True)
complete_user.get_profile = MagicMock(return_value=Profile(name='Mock name'))

incomplete_user = AnonymousUser()
incomplete_user.is_authenticated = MagicMock(return_value=True)
incomplete_user.get_profile = MagicMock(return_value=Profile())


class TestProfileMiddleware(TestCase):

    def setUp(self):
        self.factory = RequestFactory()

    def test_safe_view_request(self):
        request = self.factory.get(reverse('users_edit'))
        middleware = ProfileMiddleware()
        response = middleware.process_request(request)
        self.assertFalse(response)

    def test_safe_path_request(self):