Example #1
0
    def obj_create(self, bundle, request=None, **kwargs):
        prov_bundle = ProvBundle()
        prov_bundle._decode_JSON_container(bundle.data['content'])
        
        account = PDBundle.create(bundle.data['rec_id'], bundle.data['asserter'], request.user)
        account.save_bundle(prov_bundle)

        bundle.obj = account
        return bundle
Example #2
0
class BundleForm(Form):
    ''' Form for creating a Bundle '''
    
    rec_id = forms.CharField(label=('Bundle ID'))
    public = forms.BooleanField(label=('Public'), required = False)
    submission = forms.FileField(label=('Original File'), required = False)
    license = LicenseMultipleChoiceField(License.objects, widget=CheckboxSelectMultiple, required=False)
    url = forms.URLField(label='URL to the bundle file:', required=False)
    content = forms.CharField(label=('Content (in JSON format)'), widget=Textarea(attrs={'class': 'span7'}), required=False)
    
    def clean(self):
        self.bundle = ProvBundle()
        ''' Try to parse content or download and parse URL - one at least needed'''
        if self.cleaned_data['content']:
            try:
                self.bundle._decode_JSON_container(loads(self.cleaned_data['content']))
            except ValueError:
                raise forms.ValidationError(u'Wrong syntax in the JSON content.')
        elif self.cleaned_data['url']:
            try:
                source = urlopen(self.cleaned_data['url'], timeout=5)
                url_content = source.read()
                source.close()
            except URLError:
                raise forms.ValidationError(u'There was a problem accessing the URL.')
            try:
                self.bundle._decode_JSON_container(loads(url_content))
            except ValueError:
                raise forms.ValidationError(u'Wrong syntax in the JSON content at the URL.')
        else:
            raise forms.ValidationError(u'No content or URL provided.')
        return self.cleaned_data
    
    def save(self, owner, commit=True):
        if self.errors:
            raise ValueError("The %s could not be %s because the data didn't"
                         " validate." % ('Container', 'created'))
            
        container = Container.create(self.cleaned_data['rec_id'], self.bundle, owner, self.cleaned_data['public'])
        save = False
        
        if 'submission' in self.files:
            file_sub = self.files['submission']
            sub = Submission.objects.create()
            sub.content.save(sub.timestamp.strftime('%Y-%m-%d%H-%M-%S')+file_sub._name, file_sub)
            container.submission = sub
            save = True
            
        for l in self.cleaned_data['license']:
            container.license.add(l)
            save = True
            
        if save:
            container.save()
        return container
Example #3
0
    def get_document(self, doc_id, format=None, flattened=False, view=None):
        """Returns a ProvBundle object of the document with the ID provided or raises ApiNotFoundError"""

        extension = format if format is not None else 'json'
        view = "/views/%s" % view if view in ['data', 'process', 'responsibility'] else ""
        url = "documents/%d%s%s.%s" % (doc_id, "/flattened" if flattened else "", view, extension)
        response = self.request(url, raw=True)

        if format is None:
            # Try to decode it as a ProvBundle
            prov_document = ProvBundle()
            prov_document._decode_JSON_container(json.loads(response))
            return prov_document
        else:
            # return the raw response
            return response
Example #4
0
 def setUp(self):
     logging.debug('Setting up user and checking the URL file...')
     self.check_u = User.objects.get_or_create(username='******')
     self.user = self.check_u[0]
     self.check_k = ApiKey.objects.get_or_create(user=self.user)
     self.key = self.check_k[0]
     self.auth = 'ApiKey' + self.user.username + ':' + self.key.key
     self.check_u = self.check_u[1]
     self.check_k = self.check_k[1]
     self.url = 'http://users.ecs.soton.ac.uk/ab9g10/test.json'
     source = urlopen(self.url)
     url_content = ProvBundle()
     url_content._decode_JSON_container(json.loads(source.read()))
     source.close()
     self.content = PDBundle.create('url_test')
     self.content.save_bundle(url_content)
     self.content = self.content.get_prov_bundle()
Example #5
0
    def testOAuthAccess(self):
        self.user = User.objects.create_user('jane', '*****@*****.**', 'toto')
        self.resource = Resource.objects.get_or_create(name='api', url='/api/')
        self.CONSUMER_KEY = 'dpf43f3p2l4k3l03'
        self.CONSUMER_SECRET = 'kd94hf93k423kf44'
        self.consumer, _ = Consumer.objects.get_or_create(
            key=self.CONSUMER_KEY, secret=self.CONSUMER_SECRET,
            defaults={
                'name': 'Test',
                'description': 'Testing...'
        })
        pb = ProvBundle()
        pb._decode_JSON_container('')
        self.bundle = Container.create('test_bundle', pb, self.user)
        
        c = Client()
        response = c.get("/oauth/request_token/")
        self.assertEqual(response.status_code, 401)
        import time
        parameters = {
            'oauth_consumer_key': self.CONSUMER_KEY,
            'oauth_signature_method': 'PLAINTEXT',
            'oauth_signature': '%s&' % self.CONSUMER_SECRET,
            'oauth_timestamp': str(int(time.time())),
            'oauth_nonce': 'requestnonce',
            'oauth_version': '1.0',
            'oauth_callback': 'http://test/request_token_ready',
            'scope': 'api',
            }
        response = c.get("/oauth/request_token/", parameters)
        self.assertEqual(response.status_code, 200)
        token = list(Token.objects.all())[-1]
        self.assertIn(token.key, response.content)
        self.assertIn(token.secret, response.content)
        self.assertTrue(token.callback_confirmed)

        parameters = {'oauth_token': token.key,}
        response = c.get("/oauth/authorize/", parameters)
        self.assertEqual(response.status_code, 302)
        self.assertIn(token.key, response['Location'])
        c.login(username='******', password='******')
        self.assertFalse(token.is_approved)
        response = c.get("/oauth/authorize/", parameters)
        self.assertEqual(response.status_code, 200)
        
        # fake authorization by the user
        parameters['authorize_access'] = 1
        response = c.post("/oauth/authorize/", parameters)
        self.assertEqual(response.status_code, 302)
        token = Token.objects.get(key=token.key)
        self.assertIn(token.key, response['Location'])
        self.assertTrue(token.is_approved)
        c.logout()
        
        # Exchange the Request token for an Access token
        parameters = {
            'oauth_consumer_key': self.CONSUMER_KEY,
            'oauth_token': token.key,
            'oauth_signature_method': 'PLAINTEXT',
            'oauth_signature': '%s&%s' % (self.CONSUMER_SECRET, token.secret),
            'oauth_timestamp': str(int(time.time())),
            'oauth_nonce': 'accessnonce',
            'oauth_version': '1.0',
            'oauth_verifier': token.verifier,
            'scope': 'api',
            }
        response = c.get("/oauth/access_token/", parameters)
        self.assertEqual(response.status_code, 200)
        access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1]
        self.assertIn(access_token.key, response.content)
        self.assertIn(access_token.secret, response.content)
        self.assertEqual(access_token.user.username, self.user.username)
        
        # Generating signature base string
        parameters = {
            'oauth_consumer_key': self.CONSUMER_KEY,
            'oauth_token': access_token.key,
            'oauth_signature_method': 'HMAC-SHA1',
            'oauth_timestamp': str(int(time.time())),
            'oauth_nonce': 'accessresourcenonce',
            'oauth_version': '1.0',
        }
        url_path = "/api/v0/bundle/%d/" % self.bundle.id
        oauth_request = oauth.Request.from_token_and_callback(access_token, http_url='http://testserver' + url_path, parameters=parameters)
        signature_method = oauth.SignatureMethod_HMAC_SHA1()
        signature = signature_method.sign(oauth_request, self.consumer, access_token)
        parameters['oauth_signature'] = signature
        response = c.get(url_path + '?format=json', parameters)
        self.assertEqual(response.status_code, 200)
Example #6
0
    def obj_create(self, bundle, request=None, **kwargs):
        '''
        Function to create a bundle via the API.
        Arguments (in JSON) are as follows:
            rec_id - the name for the Bundle (REQUIRED)
            content - the content in JSON format (or URL REQUIRDE)
            URL - a URL reference to the JSON content of the bundle * (OR content REQUIRED)
            public - indicator whether the Bundle to be made public, False if not provided
            licenses - a list of names corresponding to License objects in the DB
            submission - a file submitted which represents the Bundle **
        
        * - The URL is only opened and it's content parsed if and only if 'content' is empty
        ** - The file content is not parsed at all, it is just saved for later usage and
             if file is submitted the HTTP call should be in 'multipart' encoding format.
        '''
        
        try:
            '''Try to read the content else download and parse the URL file '''
            prov_bundle = ProvBundle()
            if bundle.data['content']:
                prov_bundle._decode_JSON_container(bundle.data['content'])
            else:
                source = urlopen(bundle.data['url'], timeout=5)
                content = source.read()
                source.close()
                prov_bundle._decode_JSON_container(loads(content))
            container = Container.create(bundle.data['rec_id'], prov_bundle, request.user)
        except: 
            raise ImmediateHttpResponse(HttpBadRequest())

        save = False
        if 'public' in bundle.data: 
            container.public = bundle.data['public']
            save = True
            if bundle.data['public']:
                assign('view_container', Group.objects.get(id=PUBLIC_GROUP_ID), container) 
                           
        if 'licenses' in bundle.data:
            for title in bundle.data['licenses']:
                try:
                    lic = License.objects.get(title=title)
                    container.license.add(lic)
                    save = True
                except License.DoesNotExist:
                    pass
        
        if 'submission' in request.FILES:
            file_sub = request.FILES['submission']
            sub = Submission.objects.create()
            sub.content.save(sub.timestamp.strftime('%Y-%m-%d%H-%M-%S')+file_sub._name, file_sub)
            container.submission = sub
            save = True
            
        if 'url' in bundle.data:
            container.url = bundle.data['url']
            save = True
            
        if save:
            container.save()
        bundle.obj = container
        return bundle