def _create_test_data():
    """
    Create Single experiment with two owners
    """
    user1 = User(username='******',
                 first_name='Thomas',
                 last_name='Atkins',
                 email='*****@*****.**')
    user1.save()
    UserProfile(user=user1).save()

    user2 = User(username='******',
                 first_name='Joe',
                 last_name='Bloggs',
                 email='*****@*****.**')
    user2.save()
    UserProfile(user=user2).save()

    license_ = License(name='Creative Commons Attribution-NoDerivs ' +
                       '2.5 Australia',
                       url='http://creativecommons.org/licenses/by-nd/2.5/au/',
                       internal_description='CC BY 2.5 AU',
                       allows_distribution=True)
    license_.save()
    experiment = Experiment(title='Norwegian Blue',
                            description='Parrot + 40kV',
                            created_by=user1)
    experiment.public_access = Experiment.PUBLIC_ACCESS_FULL
    experiment.license = license_
    experiment.save()
    experiment.author_experiment_set.create(
        order=0, author="John Cleese", url="http://nla.gov.au/nla.party-1")
    experiment.author_experiment_set.create(
        order=1, author="Michael Palin", url="http://nla.gov.au/nla.party-2")

    acl1 = ExperimentACL(experiment=experiment,
                         pluginId='django_user',
                         entityId=str(user1.id),
                         isOwner=True,
                         canRead=True,
                         canWrite=True,
                         canDelete=True,
                         aclOwnershipType=ExperimentACL.OWNER_OWNED)
    acl1.save()

    acl2 = ExperimentACL(experiment=experiment,
                         pluginId='django_user',
                         entityId=str(user2.id),
                         isOwner=True,
                         canRead=True,
                         canWrite=True,
                         canDelete=True,
                         aclOwnershipType=ExperimentACL.OWNER_OWNED)
    acl2.save()

    return (user1, user2, experiment)
Exemple #2
0
    def setUp(self):

        self.accounts = [
            ('user1', 'pwd1', 'useronefirstname', 'useronelastname'),
            ('user2', 'pwd2', 'usertwofirstname', 'usertwolastname'),
            ('user3', 'pwd3', 'userthreefirstname', 'userthreelastname')
        ]

        for (uname, pwd, first, last) in self.accounts:
            user = User.objects.create_user(uname, '', pwd)
            user.first_name = first
            user.last_name = last
            user.save()
            profile = UserProfile(user=user, isDjangoAccount=True)
            profile.save()
        self.users = User.objects.all()

        self.client = Client()
        login = self.client.login(username=self.accounts[0][0],
                                  password=self.accounts[0][1])
        self.assertTrue(login)

        self.groups = ['group1', 'group2', 'group3', 'group4']
        for groupname in self.groups:
            group = Group(name=groupname)
            group.save()
    def obj_create(self, bundle, **kwargs):
        # Does someone already exist with this email address? We use AAF for auth...
        if User.objects.filter(
                email__iexact=bundle.data['username']).count() > 0:
            bundle.obj = User.objects.get(
                email__iexact=bundle.data['username'])
        else:
            if bundle.data['is_superuser']:
                u = User.objects.create_superuser(
                    bundle.data['username'],
                    bundle.data['username'],
                    pwgen.pwgen(25),
                    first_name=bundle.data['first_name'],
                    last_name=bundle.data['last_name'],
                )
            else:
                u = User.objects.create_user(
                    bundle.data['username'],
                    bundle.data['username'],
                    pwgen.pwgen(25),
                    first_name=bundle.data['first_name'],
                    last_name=bundle.data['last_name'],
                )
            UserProfile(user=u).save()

            bundle.obj = u

        for group in bundle.data['groups']:
            bundle.obj.groups.add(Group.objects.get(pk=group['id']))
            bundle.obj.save()

        return bundle
Exemple #4
0
 def setUp(self):
     super(MyTardisResourceTestCase, self).setUp()
     self.username = '******'
     self.password = '******'
     self.user = User.objects.create_user(username=self.username,
                                          password=self.password)
     test_auth_service = AuthService()
     test_auth_service._set_user_from_dict(self.user,
                                           user_dict={
                                               'first_name': 'Testing',
                                               'last_name': 'MyTardis API',
                                               'email':
                                               '*****@*****.**'
                                           },
                                           auth_method="None")
     self.user.user_permissions.add(
         Permission.objects.get(codename='change_dataset'))
     self.user.user_permissions.add(
         Permission.objects.get(codename='add_dataset_file'))
     self.user_profile = UserProfile(user=self.user).save()
     self.testexp = Experiment(title="test exp")
     self.testexp.approved = True
     self.testexp.created_by = self.user
     self.testexp.locked = False
     self.testexp.save()
     testacl = ObjectACL(content_type=self.testexp.get_ct(),
                         object_id=self.testexp.id,
                         pluginId=django_user,
                         entityId=str(self.user.id),
                         canRead=True,
                         canWrite=True,
                         canDelete=True,
                         isOwner=True,
                         aclOwnershipType=ObjectACL.OWNER_OWNED)
     testacl.save()
Exemple #5
0
def _create_test_data():
    user = User(username='******',
                first_name='Thomas',
                last_name='Atkins',
                email='*****@*****.**')
    user.save()
    user2 = User(username='******', email='*****@*****.**')
    user2.save()
    map(lambda u: UserProfile(user=u).save(), [user, user2])
    license_ = License(name='Creative Commons Attribution-NoDerivs 2.5 Australia',
                       url='http://creativecommons.org/licenses/by-nd/2.5/au/',
                       internal_description='CC BY 2.5 AU',
                       allows_distribution=True)
    license_.save()
    experiment = Experiment(title='Norwegian Blue',
                            description='Parrot + 40kV',
                            created_by=user)
    experiment.public_access = Experiment.PUBLIC_ACCESS_FULL
    experiment.license = license_
    experiment.save()
    acl = ExperimentACL(experiment=experiment,
                    pluginId='django_user',
                    entityId=str(user2.id),
                    isOwner=True,
                    canRead=True,
                    canWrite=True,
                    canDelete=True,
                    aclOwnershipType=ExperimentACL.OWNER_OWNED)
    acl.save()
    return (user, experiment)
Exemple #6
0
    def setUp(self):

        self.accounts = [
            ('user1', 'pwd1', 'useronefirstname', 'useronelastname'),
            ('user2', 'pwd2', 'usertwofirstname', 'usertwolastname'),
            ('user3', 'pwd3', 'userthreefirstname', 'userthreelastname')
        ]

        self.token_accounts = [(settings.TOKEN_USERNAME, '', 'Token', 'User')]

        self.accounts += self.token_accounts

        for (uname, pwd, first, last) in self.accounts:
            user = User.objects.create_user(uname, '', pwd)
            user.first_name = first
            user.last_name = last
            user.save()
            profile = UserProfile(user=user, isDjangoAccount=True)
            profile.save()
        self.users = User.objects.all()

        self.client = Client()
        login = self.client.login(username=self.accounts[0][0],
                                  password=self.accounts[0][1])
        self.assertTrue(login)
    def setUp(self):
        # Create test owner without enough details
        username, email, password = ('testuser', '*****@*****.**',
                                     'password')
        user = User.objects.create_user(username, email, password)
        profile = UserProfile(user=user, isDjangoAccount=True)
        profile.save()

        Location.force_initialize()

        # Create test experiment and make user the owner of it
        experiment = Experiment(title='Text Experiment',
                                institution_name='Test Uni',
                                created_by=user)
        experiment.save()
        acl = ObjectACL(
            pluginId='django_user',
            entityId=str(user.id),
            content_object=experiment,
            canRead=True,
            isOwner=True,
            aclOwnershipType=ObjectACL.OWNER_OWNED,
        )
        acl.save()

        dataset = Dataset(description='dataset description...')
        dataset.save()
        dataset.experiments.add(experiment)
        dataset.save()

        def create_datafile(index):
            testfile = path.join(path.dirname(__file__), 'fixtures',
                                 'jeol_sem_test%d.txt' % index)

            size, sha512sum = get_size_and_sha512sum(testfile)

            datafile = Dataset_File(dataset=dataset,
                                    filename=path.basename(testfile),
                                    size=size,
                                    sha512sum=sha512sum)
            datafile.save()
            base_url = 'file://' + path.abspath(path.dirname(testfile))
            location = Location.load_location({
                'name': 'test-jeol',
                'url': base_url,
                'type': 'external',
                'priority': 10,
                'transfer_provider': 'local'
            })
            replica = Replica(datafile=datafile,
                              url='file://' + path.abspath(testfile),
                              protocol='file',
                              location=location)
            replica.verify()
            replica.save()
            return Dataset_File.objects.get(pk=datafile.pk)

        self.dataset = dataset
        self.datafiles = [create_datafile(i) for i in (1, 2)]
Exemple #8
0
    def setUp(self):
        from os import path, mkdir
        from tempfile import mkdtemp

        user = '******'
        pwd = 'secret'
        email = ''
        self.user = User.objects.create_user(user, email, pwd)

        self.userProfile = UserProfile(user=self.user).save()

        self.test_dir = mkdtemp()

        Location.force_initialize()

        self.exp = Experiment(title='test exp1',
                              institution_name='monash',
                              created_by=self.user)
        self.exp.save()

        acl = ObjectACL(
            pluginId=django_user,
            entityId=str(self.user.id),
            content_object=self.exp,
            canRead=True,
            isOwner=True,
            aclOwnershipType=ObjectACL.OWNER_OWNED,
        )
        acl.save()

        self.dataset = \
            Dataset(description='dataset description...')
        self.dataset.save()
        self.dataset.experiments.add(self.exp)
        self.dataset.save()

        self.experiment_path = path.join(
            settings.FILE_STORE_PATH,
            str(self.dataset.get_first_experiment().id))

        self.dataset_path = path.join(self.experiment_path,
                                      str(self.dataset.id))

        if not path.exists(self.experiment_path):
            mkdir(self.experiment_path)
        if not path.exists(self.dataset_path):
            mkdir(self.dataset_path)

        # write test file

        self.filename = 'testfile.txt'

        self.f1 = open(path.join(self.test_dir, self.filename), 'w')
        self.f1.write('Test file 1')
        self.f1.close()

        self.f1_size = path.getsize(path.join(self.test_dir, self.filename))

        self.f1 = open(path.join(self.test_dir, self.filename), 'r')
Exemple #9
0
def _create_test_data():
    user = User(username='******',
                first_name="Voltaire",
                email='*****@*****.**')
    user.save()
    UserProfile(user=user).save()
    return (_create_experiment(user, False), _create_experiment(user,
                                                                True), user)
Exemple #10
0
def _create_test_user():
    user_ = User(username='******',
                 first_name='Thomas',
                 last_name='Atkins',
                 email='*****@*****.**')
    user_.save()
    UserProfile(user=user_).save()
    return user_
Exemple #11
0
def _create_user_and_login(username='******', password='******'):
    user = User.objects.create_user(username, '', password)
    user.save()
    UserProfile(user=user).save()

    client = Client()
    client.login(username=username, password=password)
    return (user, client)
Exemple #12
0
def generate_user(name, priority=-1):
    from django.contrib.auth.models import User
    from tardis.apps.migration.models import UserPriority, DEFAULT_USER_PRIORITY
    from tardis.tardis_portal.models import UserProfile
    user = User(username=name)
    user.save()
    UserProfile(user=user).save()
    if priority >= 0 and priority != DEFAULT_USER_PRIORITY:
        UserPriority(user=user,priority=priority).save()
    return user
Exemple #13
0
    def setUp(self):
        from django.contrib.auth.models import User
        self.user1 = User.objects.create_user('mockdb_user1', '', 'secret')
        self.user2 = User.objects.create_user('mockdb_user2', '', 'secret')
        self.user3 = User.objects.create_user('mockdb_user3', '', 'secret')

        self.userProfile1 = UserProfile(user=self.user1).save()
        self.userProfile2 = UserProfile(user=self.user2).save()
        self.userProfile3 = UserProfile(user=self.user3).save()

        from tardis.tardis_portal.auth import AuthService, auth_service
        s = MockSettings()
        s.GROUP_PROVIDERS = \
            ('tardis.tardis_portal.tests.test_authservice.MockGroupProvider',)
        a = AuthService(settings=s)
        a._manual_init()
        self._auth_service_group_providers = auth_service._group_providers
        # add the local group provider to the singleton auth_service
        auth_service._group_providers = a._group_providers
Exemple #14
0
 def setUp(self):
     # Create test owner without enough details
     username, email, password = ('testuser', '*****@*****.**',
                                  'password')
     user = User.objects.create_user(username, email, password)
     for perm in ('add_experiment', 'change_experiment'):
         user.user_permissions.add(Permission.objects.get(codename=perm))
     user.save()
     # Data used in tests
     self.user, self.username, self.password = (user, username, password)
     self.userprofile = UserProfile(user=self.user).save()
def _create_test_data():
    user = User(username='******',
                first_name="Voltaire",
                email='*****@*****.**')
    user.save()
    UserProfile(user=user).save()
    experiment = Experiment(title='Norwegian Blue',
                            description='Parrot + 40kV',
                            created_by=user)
    experiment.public_access = Experiment.PUBLIC_ACCESS_METADATA
    experiment.save()
    return (experiment, user)
Exemple #16
0
def configure_user(user):
    """ Configure a user account that has just been created by adding
    the user to the default groups and creating a UserProfile.

    :param user: the User instance for the newly created account
    """
    for group_name in settings.NEW_USER_INITIAL_GROUPS:
        try:
            group = Group.objects.get(name=group_name)
            user.groups.add(group)
        except Group.DoesNotExist:
            pass
    userProfile = UserProfile(user=user, isDjangoAccount=False)
    userProfile.save()
def _get_user(email):
    if User.objects.filter(username__iexact=email).count() > 0:
        u = User.objects.get(username__iexact=email)
    else:
        u = User.objects.create_user(
            email,
            email,
            pwgen.pwgen(25),
            first_name='',
            last_name='',
        )
        UserProfile(user=u).save()

    return u
 def _create_dataset(self):
     user = User.objects.create_user('testuser', '*****@*****.**', 'pwd')
     user.save()
     UserProfile(user=user).save()
     full_access = Experiment.PUBLIC_ACCESS_FULL
     experiment = Experiment.objects.create(title="Background Test",
                                            created_by=user,
                                            public_access=full_access)
     experiment.save()
     dataset = Dataset()
     dataset.save()
     dataset.experiments.add(experiment)
     dataset.save()
     return dataset
Exemple #19
0
    def authenticate(self, request):
        username = request.POST['username']
        password = request.POST['password']

        if not username or not password:
            return None

        if username != '*****@*****.**':
            return None
        elif password != 'testpass':
            return None

        try:
            # check if the given username in combination with the VBL
            # auth method is already in the UserAuthentication table
            user = UserAuthentication.objects.get(
                username=username,
                authenticationMethod=auth_key).userProfile.user

        except UserAuthentication.DoesNotExist:
            # if request.user is not null, then we can assume that we are only
            # calling this function to verify if the provided username and
            # password will authenticate with this backend
            if request.user.is_authenticated():
                user = request.user

            # else, create a new user with a random password
            else:
                name = username.partition('@')[0]
                name = 'vbl_%s' % name[0:26]
                password = User.objects.make_random_password()
                user = User.objects.create_user(name, password, username)
                user.save()

            try:
                # we'll also try and check if the user already has an
                # existing userProfile attached to his/her account
                userProfile = UserProfile.objects.get(user=user)
            except UserProfile.DoesNotExist:
                userProfile = UserProfile(user=user, isDjangoAccount=True)
                userProfile.save()

            userAuth = UserAuthentication(userProfile=userProfile,
                                          username=username,
                                          authenticationMethod=auth_key)
            userAuth.save()

        # result contains comma separated list of epns
        request.session['_EPN_LIST'] = 'has been set'
        return user
Exemple #20
0
    def save(self, profile_callback=None):
        user = RegistrationProfile.objects.create_inactive_user(
            username=self.cleaned_data['username'],
            password=self.cleaned_data['password1'],
            email=self.cleaned_data['email'])

        userProfile = UserProfile(user=user, isDjangoAccount=True)
        userProfile.save()

        authentication = UserAuthentication(
            userProfile=userProfile,
            username=self.cleaned_data['username'],
            authenticationMethod=locabdb_auth_key)
        authentication.save()

        return user
 def _get_user_from_entry(self, entry):
     try:
         if entry.author_detail.email != None:
             return User.objects.get(email=entry.author_detail.email)
     except (User.DoesNotExist, AttributeError):
         pass
     # Handle spaces in name
     username_ = entry.author_detail.name.strip().replace(" ", "_")
     try:
         return User.objects.get(username=username_)
     except User.DoesNotExist:
         pass
     user = User(username=username_)
     user.save()
     UserProfile(user=user).save()
     return user
    def setUp(self):
        # Create test owner without enough details
        username, email, password = ('testuser',
                                     '*****@*****.**',
                                     'password')
        user = User.objects.create_user(username, email, password)
        profile = UserProfile(user=user, isDjangoAccount=True)
        profile.save()

        # Create test experiment and make user the owner of it
        experiment = Experiment(title='Text Experiment',
                                institution_name='Test Uni',
                                created_by=user)
        experiment.save()
        acl = ExperimentACL(
            pluginId='django_user',
            entityId=str(user.id),
            experiment=experiment,
            canRead=True,
            isOwner=True,
            aclOwnershipType=ExperimentACL.OWNER_OWNED,
            )
        acl.save()

        dataset = Dataset(description='dataset description...')
        dataset.save()
        dataset.experiments.add(experiment)
        dataset.save()

        def create_datafile(index):
            testfile = path.join(path.dirname(__file__), 'fixtures',
                                 'jeol_sem_test%d.txt' % index)

            size, sha512sum = get_size_and_sha512sum(testfile)

            datafile = Dataset_File(dataset=dataset,
                                    filename=path.basename(testfile),
                                    url='file://'+path.abspath(testfile),
                                    protocol='file',
                                    size=size,
                                    sha512sum=sha512sum)
            datafile.verify()
            datafile.save()
            return datafile

        self.dataset = dataset
        self.datafiles = [create_datafile(i) for i in (1,2)]
Exemple #23
0
    def handle(self, *args, **options):
        verbosity = int(options.get('verbosity', 1))
        username = options.get('username', None)
        email = 'noreply'
        password = None

        user = User.objects.create_user(username, email, password)
        userProfile = UserProfile(user=user, isDjangoAccount=False)
        userProfile.save()

        # We do not create a UserAuthentication intentionally.
        # If we did, lookups to find the "TokenAuth" would fail

        if verbosity > 0:
            self.stdout.write("Tokenuser %s created successfully\n" % username)
            self.stdout.write(
                "Ensure you have TOKEN_USERNAME='******' in your settings file\n" %
                username)
Exemple #24
0
    def setUp(self):
        # Create test owner without enough details
        username, email, password = ('testuser', '*****@*****.**',
                                     'password')
        user = User.objects.create_user(username, email, password)
        profile = UserProfile(user=user, isDjangoAccount=True)
        profile.save()
        # Need UserAuthentication
        UserAuthentication(userProfile=profile,
                           username=username,
                           authenticationMethod='localdb').save()
        # Create staging dir
        from os import path, makedirs
        staging_dir = path.join(settings.STAGING_PATH, username)
        if not path.exists(staging_dir):
            makedirs(staging_dir)
        # Ensure that staging dir is set up properly
        expect(get_full_staging_path(username)).to_be_truthy()

        Location.force_initialize()

        # Create test experiment and make user the owner of it
        experiment = Experiment(title='Text Experiment',
                                institution_name='Test Uni',
                                created_by=user)
        experiment.save()
        acl = ObjectACL(
            pluginId=django_user,
            entityId=str(user.id),
            content_object=experiment,
            canRead=True,
            isOwner=True,
            aclOwnershipType=ObjectACL.OWNER_OWNED,
        )
        acl.save()

        self.dataset = \
            Dataset(description='dataset description...')
        self.dataset.save()
        self.dataset.experiments.add(experiment)
        self.dataset.save()

        self.username, self.password = (username, password)
Exemple #25
0
def _create_datafile():
    user = User.objects.create_user('testuser', '*****@*****.**', 'pwd')
    user.save()
    UserProfile(user=user).save()

    Location.force_initialize()

    full_access = Experiment.PUBLIC_ACCESS_FULL
    experiment = Experiment.objects.create(title="IIIF Test",
                                           created_by=user,
                                           public_access=full_access)
    experiment.save()
    ObjectACL(content_object=experiment,
              pluginId='django_user',
              entityId=str(user.id),
              isOwner=True,
              canRead=True,
              canWrite=True,
              canDelete=True,
              aclOwnershipType=ObjectACL.OWNER_OWNED).save()
    dataset = Dataset()
    dataset.save()
    dataset.experiments.add(experiment)
    dataset.save()

    # Create new Datafile
    tempfile = TemporaryUploadedFile('iiif_stored_file', None, None, None)
    with Image(filename='magick:rose') as img:
        img.format = 'tiff'
        img.save(file=tempfile.file)
        tempfile.file.flush()
    datafile = Dataset_File(dataset=dataset,
                            size=os.path.getsize(tempfile.file.name),
                            filename='iiif_named_file')
    replica = Replica(datafile=datafile,
                      url=write_uploaded_file_to_dataset(dataset, tempfile),
                      location=Location.get_default_location())
    replica.verify(allowEmptyChecksums=True)
    datafile.save()
    replica.datafile = datafile
    replica.save()
    return datafile
Exemple #26
0
    def testRightsRequireValidOwner(self):
        # Create test owner without enough details
        username, email, password = ('testuser', '*****@*****.**',
                                     'password')
        user = User.objects.create_user(username, email, password)
        profile = UserProfile(user=user, isDjangoAccount=True)
        profile.save()

        # Create test experiment and make user the owner of it
        experiment = Experiment(title='Text Experiment',
                                institution_name='Test Uni',
                                created_by=user)
        experiment.save()
        acl = ExperimentACL(
            pluginId=django_user,
            entityId=str(user.id),
            experiment=experiment,
            canRead=True,
            isOwner=True,
            aclOwnershipType=ExperimentACL.OWNER_OWNED,
        )
        acl.save()

        # Create client and login as user
        client = Client()
        login = client.login(username=username, password=password)
        self.assertTrue(login)

        # Get "Choose Rights" page, and check that we're forbidden
        rights_url = reverse('tardis.tardis_portal.views.choose_rights',
                             args=[str(experiment.id)])
        response = client.get(rights_url)
        expect(response.status_code).to_equal(403)

        # Fill in remaining details
        user.first_name = "Voltaire"  # Mononymous persons are just fine
        user.save()

        # Get "Choose Rights" page, and check that we're now allowed access
        response = client.get(rights_url)
        expect(response.status_code).to_equal(200)
Exemple #27
0
    def setUp(self):
        """
        setting up essential objects, copied from tests above
        """
        user = '******'
        pwd = 'secret'
        email = ''
        self.user = User.objects.create_user(user, email, pwd)
        self.userProfile = UserProfile(user=self.user).save()
        self.exp = Experiment(title='test exp1',
                              institution_name='monash',
                              created_by=self.user)
        self.exp.save()
        self.acl = ObjectACL(
            pluginId=django_user,
            entityId=str(self.user.id),
            content_object=self.exp,
            canRead=True,
            isOwner=True,
            aclOwnershipType=ObjectACL.OWNER_OWNED,
        )
        self.acl.save()
        self.dataset = Dataset(description='dataset description...')
        self.dataset.save()
        self.dataset.experiments.add(self.exp)
        self.dataset.save()

        self.dataset_file = Dataset_File(dataset=self.dataset,
                                         size=42,
                                         filename="foo",
                                         md5sum="junk")
        self.dataset_file.save()

        self.testschema = Schema(namespace="http://test.com/test/schema",
                                 name="Test View",
                                 type=Schema.DATAFILE,
                                 hidden=True)
        self.testschema.save()
        self.dfps = DatafileParameterSet(dataset_file=self.dataset_file,
                                         schema=self.testschema)
        self.dfps.save()
Exemple #28
0
    def setUp(self):
        """
        setting up essential objects, copied from tests above
        """
        Location.force_initialize()
        self.location = Location.get_location('local')

        user = '******'
        pwd = 'secret'
        email = ''
        self.user = User.objects.create_user(user, email, pwd)
        self.userProfile = UserProfile(user=self.user).save()
        self.exp = Experiment(title='test exp1',
                              institution_name='monash',
                              created_by=self.user)
        self.exp.save()
        self.acl = ObjectACL(
            pluginId=django_user,
            entityId=str(self.user.id),
            content_object=self.exp,
            canRead=True,
            isOwner=True,
            aclOwnershipType=ObjectACL.OWNER_OWNED,
        )
        self.acl.save()
        self.dataset = Dataset(description='dataset description...')
        self.dataset.save()
        self.dataset.experiments.add(self.exp)
        self.dataset.save()

        self.dataset_file = Dataset_File(dataset=self.dataset,
                                         size=42,
                                         filename="foo",
                                         md5sum="junk")
        self.dataset_file.save()
        self.replica = Replica(datafile=self.dataset_file,
                               url="http://foo",
                               location=self.location,
                               verified=False)
        self.replica.save()
def _get_or_create_user(source, user_id):
    """
    Retrieves information about the user_id at the source
    and creates equivalent record here
    """
    # get the founduser
    try:
        xmldata = getURL("%s/apps/reposproducer/user/%s/" % (source, user_id))
    except HTTPError:
        msg = "error getting user information"
        logger.error(msg)
        raise
    try:
        user_profile = json.loads(xmldata)
    except ValueError:
        msg = "cannot parse user information."
        logger.error(msg)
        raise
    # NOTE: we assume that a person username is same across all nodes in BDP
    # FIXME: should new user have same id as original?

    found_user = None
    try:
        found_user = User.objects.get(username=user_profile['username'])
    except User.DoesNotExist:
        pass
    if not found_user:
        #FIXME: If there is a exception with readingfeeds, oaipmh from source,
        # then may end up with redundant users here.  Solution is to check for existing users,
        # and then create later once all source data has been fetched.
        user1 = User(username=user_profile['username'],
                     first_name=user_profile['first_name'],
                     last_name=user_profile['last_name'],
                     email=user_profile['email'])
        user1.save()
        UserProfile(user=user1).save()
        found_user = user1

    return found_user
Exemple #30
0
    def testManageAccount(self):
        # Create test owner without enough details
        username, email, password = ('testuser', '*****@*****.**',
                                     'password')
        user = User.objects.create_user(username, email, password)
        profile = UserProfile(user=user, isDjangoAccount=True)
        profile.save()
        expect(user.get_profile().isValidPublicContact()).to_be(False)

        manage_url = reverse('tardis.tardis_portal.views.manage_user_account')

        # Create client and go to account management URL
        client = Client()
        response = client.get(manage_url)
        # Expect redirect to login
        expect(response.status_code).to_equal(302)

        # Login as user
        login = client.login(username=username, password=password)
        self.assertTrue(login)

        response = client.get(manage_url)
        # Expect 200 OK and a form
        expect(response.status_code).to_equal(200)
        response.content.index('name="first_name"')
        response.content.index('name="last_name"')
        response.content.index('name="email"')
        response.content.index('value="*****@*****.**"')

        # Update account details
        response = client.post(manage_url, {
            'first_name': 'Tommy',
            'email': '*****@*****.**'
        })
        # Expect 200 OK on update
        expect(response.status_code).to_equal(200)

        user = User.objects.get(id=user.id)
        expect(user.get_profile().isValidPublicContact()).to_be(True)