def Image(self, operation, payload): """ Performs operations on Image objects. Only supports GET operations. :param operation: The operation to perform (GET) :type operation: str :param payload: Provide a Person object, to return that user's profile image :type payload: SocialObject :returns Image -- image of requested object """ if (operation == "GET"): try: user = self.network.get_user(payload.id) user_image = user.get_image() img_object = SocialObjects.Image() img_object.fullImage = user_image author_obj = SocialObjects.Person() author_obj.id = user.name author_obj.displayName = user.name img_object.author = author_obj return img_object except: return SocialObjects.Image() else: raise NotImplementedException("Operation not supported")
def setUp(self): self.gateway = LastfmServiceGateway() person = SocialObjects.Person() person.id = "lukeweb" self.good_person = person person = SocialObjects.Person() person.id = "fegrhgtjtrshrh" self.bad_person = person
def test_good_nested_obj(self): policy_proc = self.get_good_processor() test_obj = SocialObjects.Person() test_obj.updated = datetime.datetime.fromtimestamp(0) obj = policy_proc._infer_attributes("updated.year", test_obj) self.assertEqual(obj, 1970)
def test_bad_attribute(self): policy_proc = self.get_good_processor() person = SocialObjects.Person() person.id = "me" with self.assertRaises(AttributeError): obj = policy_proc._infer_attributes("blah", person)
def test_bad_obj(self): policy_proc = self.get_good_processor() person = SocialObjects.Person() #with self.assertRaises(AttributeError): obj = policy_proc._infer_attributes("id", person) self.assertEqual(obj, None)
class GetObjectJSONTestCase(BaseSocialObjectGatewayTestCase): def test_good_get(self): self.sog.provide_privacy_policy(self.good_policy) with patch.object(self.sog, 'GetObject', return_value=self.test_object) as mock_json: obj = self.sog.GetObjectJSON("Facebook", "User", "session:Facebook.id", "") obj_json = jsonpickle.decode(obj) assert obj_json.displayName == "Test Object" @patch.object(PolicyProcessor, "_infer_object", return_value=SocialObjects.Person()) def test_bad_get(self, object_name): self.sog.provide_privacy_policy(self.good_policy) with patch.object(SocialObjectGateway.SocialObjectsGateway, 'GetObject', return_value=None) as mock_json: obj = self.sog.GetObjectJSON("Facebook", "User", "session:Facebook.id", "") obj_json = None try: obj_json = jsonpickle.decode(obj) except: pass assert obj_json == None
def test_bad_nested_obj(self): policy_proc = self.get_good_processor() test_obj = SocialObjects.Person() test_obj.updated = datetime.datetime.fromtimestamp(0) with self.assertRaises(AttributeError): obj = policy_proc._infer_attributes("updated.blah", test_obj)
def test_good_obj(self): policy_proc = self.get_good_processor() person = SocialObjects.Person() person.id = "me" obj = policy_proc._infer_attributes("id", person) self.assertEqual(obj, "me")
def test_fail_validation(self): policy_proc = self.get_disallow_processor() test_person = SocialObjects.Person() test_person.id = "lukeweb" with self.assertRaises(DisallowedByPrivacyPolicyError) as exp: request = policy_proc._validate_object_request( "GET", "Lastfm", "Image", test_person)
def test_bad_request_badOperation(self): policy_proc = self.get_good_processor() test_person = SocialObjects.Person() test_person.id = "lukeweb" with self.assertRaises(OperationNotImplementedError) as exp: request = policy_proc._validate_object_request( "BLAH", "Lastfm", "Image", test_person)
def test_bad_request_badObject(self): policy_proc = self.get_good_processor() test_person = SocialObjects.Person() test_person.id = "lukeweb" with self.assertRaises(SocialObjectNotSupportedError) as exp: request = policy_proc._validate_object_request( "GET", "Lastfm", "NotAObject", test_person)
def test_good_validation(self): policy_proc = self.get_good_processor() test_person = SocialObjects.Person() test_person.id = "lukeweb" request = policy_proc._validate_object_request("GET", "Lastfm", "Image", test_person) self.assertTrue(request)
def __get_author_from_username(self, username): """ Returns a simple Person object whose ID is the given username :param username: username to return a Person object for :type username: str :returns: Person - id is given username """ auth = SocialObjects.Person() auth.id = username return auth
def setUp(self): dir = os.path.dirname(__file__) self.good_policy = os.path.join(dir, "good-policy.xml") self.bad_policy = os.path.join(dir, "bad-policy.xml") self.disallow_policy = os.path.join(dir, "disallow-policy.xml") self.good_design = os.path.join(dir, "good-design.xml") self.test_object = SocialObjects.Person() self.test_object.displayName = "Test Object" self.sog = SocialObjectGateway.SocialObjectsGateway(server_url="")
def PostObjectJSON(self, provider, object_type, payload): """ Used by web services interface for pushing objects to a service gateway. Expects a payload as a JSON dictionary, where the keys are the appropriate fields of <object_type> This method converts the dictionary to a native object and pushes it through the PRISONER pipe for sanitisation and publication """ dumb_social = SocialObjects.SocialObject() payload = json.loads(payload) for key, value in payload.items(): setattr(dumb_social, key, value) self.PostObject(provider, object_type, dumb_social)
def GetObjectJSON(self, provider, object_type, payload, criteria, extra_args=None): """ Interface for retrieving objects from a service gateway, for consumption by web services. This differs from GetObject in some fundamental ways. GetObject is more pythonic - you request objects by supplying relevant SocialObjects, and you get SocialObject instances in return. This method however, receives plain-text responses, and returns JSON objects. Whereas GetObject expects a semantically-appropriate SocialObject as the payload (eg. supply an instance of Person to receive objects of a given type owned by that Person), this method expects a payload expressed as a query string, using the namespaced syntax found in the privacy policy spec. For example, a payload of "session:Lastfm.id" will be evaluated as "get objects authored by the user ID in the Last.fm session. "literal:lukeweb", similarly, returns objects owned by that literal user. JSON objects are returned, with the same fields as the Pythonic counterparts. A key difference is that the returned object has an additional attribute injected - prisoner_id. This is a unique identifier for the returned object *that is valid for the duration of this session*. Rather than passing around full instances of objects, subsequent queries, or publication of experimental responses, need only refer to this ID to ensure PRISONER is able to relate your requests back to the full representation of the data. Note that subsequent attempts to retrieve the cached object are subject to the privacy policy sanitisation process of the *original* request. """ # evaluate payload eval_payload = self.policy_processor._infer_object(payload) eval_payload_obj = SocialObjects.SocialObject() eval_payload_obj.id = eval_payload # use this to passthrough original object, not wrapped # as a dumb SocialObject eval_payload_obj = eval_payload # call getobject with cleaned object ret_object = self.GetObject(provider, object_type, eval_payload_obj, True, criteria, extra_args) # cache the object under a unique id, JSONify, return if ret_object != None: ident = self.cache_object(ret_object) try: return jsonpickle.encode(self.cached_objects[ident]) except: return None else: return None
def Note(self, operation, payload): """ Requests all tweets by a given user. :param operation: (GET) tweets :type operation: str :param payload: A Person whose ID is a Twitter ID :type payload: Person :returns: A list of Tweet objects """ self.timeline_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?' self.timeline_params = {"user_id": payload, "count": 50} #"include_rts": 1, #"exclude_replies":1} self.timeline_request = self.timeline_url + urllib.urlencode( self.timeline_params) self.resp, self.content = self.client.request(self.timeline_request, "GET") timeline = Timeline() tweet_list = [] author = SocialObjects.Person() author.id = payload tweets = json.loads(self.content) for tweet in tweets: this_tweet = Note() this_tweet.author = author this_tweet.published = tweet['created_at'] this_tweet.content = tweet['text'] this_tweet.favorites = tweet['favorite_count'] this_tweet.retweets = tweet['retweet_count'] tweet_list.append(this_tweet) timeline.objects = tweet_list print "returning timeline!" return timeline
def restore_authentication(self, access_token): """ Restores previously authenticated session. Last.fm session keys last indefinitely so this just provides pylast with the old session key and hope it works :param access_token: Last.fm session key received from previous auth attempt :type access_token: str :returns: boolean - was auth successful? """ self.session_key = access_token self.network.session_key = access_token # place username in session user = self.network.get_authenticated_user() user_person = SocialObjects.Person() user_person.id = user.get_name() self.session = user_person return True
def complete_authentication(self, request): """ Completes authentication. Request passed via authentication flow must contain a token argument as returned by Last.fm. We pass this to Last.fm to return a session key (lasts indefinitely) for making authenticated calls on this user. :param request: Request from first stage of authentication :type request: HTTPRequest :returns: Session key to persist for this user """ access_token = request.args['token'] # print "Last.fm access token: %s" % access_token session_key = self.session_manager.get_web_auth_session_key_verbose( access_token) self.session_key = session_key self.network.session_key = session_key # place username in session user = self.network.get_authenticated_user() user_person = SocialObjects.Person() user_person.id = user.get_name() self.session = user_person return session_key
def GetObject_returns_object(*args, **kwargs): test_object = SocialObjects.Person() test_object.displayName = "Test Object" return test_object
def ProcessorInferObject_returns_Person(*args, **kwargs): test_object = SocialObjects.Person() return test_object