Ejemplo n.º 1
0
    def get_profile(self, profileId, activityId):
        #Make sure activityId exists
        try:
            activity = models.activity.objects.get(activity_id=activityId)
        except models.activity.DoesNotExist:
            raise IDNotFoundError(
                'There is no activity associated with the id: %s' % activityId)

        #Retrieve the profile with the given profileId and activity
        try:
            return models.activity_profile.objects.get(profileId=profileId,
                                                       activity=activity)
        except models.activity_profile.DoesNotExist:
            raise IDNotFoundError(
                'There is no profile associated with the id: %s' % profileId)
Ejemplo n.º 2
0
    def __init__(self, initial=None, create=False):
        self.initial = initial
        params = self.initial
        if isinstance(params, dict):
            self.initial = json.dumps(self.initial)
        else:
            try:
                params = ast.literal_eval(params)
            except:
                params = json.loads(params)

        if 'objectType' in params and params['objectType'] == 'Group':
            obj = group
        else:
            obj = agent
        if create:
            self.agent, created = obj.objects.gen(**params)
        else:
            try:
                if 'member' in params:
                    params.pop('member', None)
                self.agent = obj.objects.get(**params)
            except:
                raise IDNotFoundError(
                    "Error with Agent. The agent partial (%s) did not match any agents on record"
                    % self.initial)
Ejemplo n.º 3
0
class AgentManager():
    def __init__(self, params=None, create=False, define=True):
        self.define = define
        self.initial = copy.deepcopy(params)
        if not isinstance(params, dict):
            try:
                params = json.loads(params)
            except Exception, e:
                err_msg = "Error parsing the Agent object. Expecting json. Received: %s which is %s" % (
                    params, type(params))
                raise ParamError(err_msg)

        if create:
            params['define'] = self.define
            self.Agent, created = ag.objects.gen(**params)
        else:
            try:
                if 'member' in params:
                    params.pop('member', None)
                # If retreiving agents always get global version
                params['global_representation'] = True
                # gotta get account info right for this..
                if 'account' in params:
                    acc = params.pop('account')
                    if 'homePage' in acc:
                        params['account_homePage'] = acc['homePage']
                    if 'name' in acc:
                        params['account_name'] = acc['name']
                self.Agent = ag.objects.get(**params)
            except:
                err_msg = "Error with Agent. The agent partial (%s) did not match any agents on record" % self.initial
                raise IDNotFoundError(err_msg)
Ejemplo n.º 4
0
    def get_profile_ids(self, profileId, activityId, since=None):
        ids = []

        #make sure activityId exists
        try:
            activity = models.activity.objects.get(activity_id=activityId)
        except models.activity.DoesNotExist:
            raise IDNotFoundError(
                'There is no activity associated with the id: %s' % activityId)

        #If there is a since param return all profileIds since then
        if since:
            try:
                profs = models.activity_profile.objects.filter(
                    updated__gte=since, profileId=profileId, activity=activity)
            except ValidationError:
                since_i = int(float(since))
                since_dt = datetime.datetime.fromtimestamp(since_i)
                profs = models.activity_profile_set.filter(
                    update__gte=since_dt,
                    profileId=profileId,
                    activity=activity)
            ids = [p.profileId for p in profs]
        else:
            #Return all IDs of profiles associated with this activity b/c there is no since param
            ids = models.activity_profile.objects.filter(
                activity=activity).values_list('profileId', flat=True)
        return ids
Ejemplo n.º 5
0
def server_validate_statement_object(stmt_object, auth):
    if stmt_object['objectType'] == 'StatementRef' and not check_for_existing_statementId(stmt_object['id']):
            err_msg = "No statement with ID %s was found" % stmt_object['id']
            raise IDNotFoundError(err_msg)
    elif stmt_object['objectType'] == 'Activity' or 'objectType' not in stmt_object:
        # Check if object has definition first
        # If it doesn't have definition, it doesn't matter if the user is owner or not because can't remove definition if exists
        if 'definition' in stmt_object:
            try:
                activity = models.Activity.objects.get(activity_id=stmt_object['id'], canonical_version=True)
            except models.Activity.DoesNotExist:
                pass
            else:
                # Get authority from request
                if auth:
                    if auth['id'].__class__.__name__ == 'Agent':
                        auth_name = auth['id'].name
                    else:
                        auth_name = auth['id'].username
                else:
                    auth_name = None

                # Get definition for canonical activity (if exists)
                try:
                    activity_def = activity.object_return()['definition']
                except KeyError, e:
                    activity_def = {}

                # If definitions are different and the auths are different
                if (stmt_object['definition'] != activity_def) and (activity.authoritative != '' and activity.authoritative != auth_name):
                    err_msg = "This ActivityID already exists, and you do not have the correct authority to create or update it."
                    raise Forbidden(err_msg)
Ejemplo n.º 6
0
 def get_profile(self, profileId, activityId):
     #Retrieve the profile with the given profileId and activity
     try:
         return models.ActivityProfile.objects.get(profileId=profileId,
                                                   activityId=activityId)
     except models.ActivityProfile.DoesNotExist:
         err_msg = 'There is no profile associated with the id: %s' % profileId
         raise IDNotFoundError(err_msg)
Ejemplo n.º 7
0
 def get_ids(self, auth):
     try:
         state_set = self.get_set(auth)
     except models.activity_state.DoesNotExist:
         raise IDNotFoundError(
             'There is no activity state associated with the ID: %s' %
             self.stateId)
     if self.since:
         state_set = state_set.filter(updated__gte=self.since)
     return state_set.values_list('state_id', flat=True)
Ejemplo n.º 8
0
def validate_statementId(req_dict):
    if 'statementId' in req_dict['params'] and 'voidedStatementId' in req_dict['params']:
        err_msg = "Cannot have both statementId and voidedStatementId in a GET request"
        raise ParamError(err_msg)
    elif 'statementId' in req_dict['params']:
        statementId = req_dict['params']['statementId']
        voided = False
    else:
        statementId = req_dict['params']['voidedStatementId']
        voided = True

    not_allowed = ["agent", "verb", "activity", "registration", 
                   "related_activities", "related_agents", "since",
                   "until", "limit", "ascending"]
    bad_keys = set(not_allowed) & set(req_dict['params'].keys())
    if bad_keys:
        err_msg = "Cannot have %s in a GET request only 'format' and/or 'attachments' are allowed with 'statementId' and 'voidedStatementId'" % ', '.join(bad_keys)
        raise ParamError(err_msg)

    # Try to retrieve stmt, if DNE then return empty else return stmt info                
    try:
        st = models.Statement.objects.get(statement_id=statementId)
    except models.Statement.DoesNotExist:
        err_msg = 'There is no statement associated with the id: %s' % statementId
        raise IDNotFoundError(err_msg)

    auth = req_dict.get('auth', None)
    mine_only = auth and 'statements_mine_only' in auth

    if auth:
        if mine_only and st.authority.id != auth['id'].id:
            err_msg = "Incorrect permissions to view statements that do not have auth %s" % str(auth['id'])
            raise Forbidden(err_msg)
    
    if st.voided != voided:
        if st.voided:
            err_msg = 'The requested statement (%s) is voided. Use the "voidedStatementId" parameter to retrieve your statement.' % statementId
        else:
            err_msg = 'The requested statement (%s) is not voided. Use the "statementId" parameter to retrieve your statement.' % statementId
        raise IDNotFoundError(err_msg)

    return statementId
Ejemplo n.º 9
0
def validate_void_statement(void_id):
    # Retrieve statement, check if the verb is 'voided' - if not then set the voided flag to true else return error 
    # since you cannot unvoid a statement and should just reissue the statement under a new ID.
    try:
        stmt = models.Statement.objects.get(statement_id=void_id)
    except models.Statement.DoesNotExist:
        err_msg = "Statement with ID %s does not exist" % void_id
        raise IDNotFoundError(err_msg)
        
    if stmt.voided:
        err_msg = "Statement with ID: %s is already voided, cannot unvoid. Please re-issue the statement under a new ID." % void_id
        raise Forbidden(err_msg)
Ejemplo n.º 10
0
 def get_ids(self):
     try:
         state_set = self.get_set()
     except models.ActivityState.DoesNotExist:
         err_msg = 'There is no activity state associated with the ID: %s' % self.stateId
         raise IDNotFoundError(err_msg)
     if self.since:
         try:
             # this expects iso6801 date/time format "2013-02-15T12:00:00+00:00"
             state_set = state_set.filter(updated__gte=self.since)
         except ValidationError:
             err_msg = 'Since field is not in correct format for retrieval of state IDs'
             raise ParamError(err_msg)
     return state_set.values_list('state_id', flat=True)
Ejemplo n.º 11
0
 def get(self):
     agent = self.__get_agent()
     try:
         if self.registrationId:
             return models.ActivityState.objects.get(
                 state_id=self.stateId,
                 agent=agent,
                 activity_id=self.activity_id,
                 registration_id=self.registrationId)
         return models.ActivityState.objects.get(
             state_id=self.stateId,
             agent=agent,
             activity_id=self.activity_id)
     except models.ActivityState.DoesNotExist:
         err_msg = 'There is no activity state associated with the id: %s' % self.stateId
         raise IDNotFoundError(err_msg)
Ejemplo n.º 12
0
 def __init__(self, request_dict):
     self.req_dict = request_dict
     self.agent = request_dict['agent']
     try:
         self.activity = models.activity.objects.get(
             activity_id=request_dict['activityId'])
     except models.activity.DoesNotExist:
         raise IDNotFoundError(
             "Error with Activity State. The activity id (%s) did not match any activities on record"
             % (request_dict['activityId']))
     self.registrationId = request_dict.get('registrationId', None)
     self.stateId = request_dict.get('stateId', None)
     self.updated = request_dict.get('updated', None)
     self.content_type = request_dict.get('CONTENT_TYPE', None)
     self.state = request_dict.get('state', None)
     self.etag = request_dict.get('ETAG', None)
     self.since = request_dict.get('since', None)
Ejemplo n.º 13
0
    def put_profile(self, request_dict):
        #Parse out profile from request_dict
        try:
            profile = ContentFile(request_dict['profile'].read())
        except:
            try:
                profile = ContentFile(request_dict['profile'])
            except:
                profile = ContentFile(str(request_dict['profile']))

        #Check if activity exists
        try:
            activity = models.activity.objects.get(
                activity_id=request_dict['activityId'])
        except models.activity.DoesNotExist:
            raise IDNotFoundError(
                'There is no activity associated with the id: %s' %
                request_dict['activityId'])

        #Get the profile, or if not already created, create one
        p, created = models.activity_profile.objects.get_or_create(
            profileId=request_dict['profileId'], activity=activity)

        #If it already exists delete it
        if not created:
            etag.check_preconditions(request_dict, p, required=True)
            p.profile.delete()

        #Save profile content type based on incoming content type header and create etag
        p.content_type = request_dict['CONTENT_TYPE']
        p.etag = etag.create_tag(profile.read())

        #Set updated
        if request_dict['updated']:
            p.updated = request_dict['updated']

        #Go to beginning of file
        profile.seek(0)

        #If it didn't exist, save it
        if created:
            p.save()

        #Set filename with the activityID and profileID and save
        fn = "%s_%s" % (p.activity_id, request_dict.get('filename', p.id))
        p.profile.save(fn, profile)
Ejemplo n.º 14
0
    def get_profile_ids(self, since=None):
        ids = []
        if since:
            try:
                # this expects iso6801 date/time format "2013-02-15T12:00:00+00:00"
                profs = self.Agent.agentprofile_set.filter(updated__gte=since)
            except ValidationError:
                err_msg = 'Since field is not in correct format for retrieval of agent profiles'
                raise ParamError(err_msg)
            except:
                err_msg = 'There are no profiles associated with the id: %s' % profileId
                raise IDNotFoundError(err_msg)

            ids = [p.profileId for p in profs]
        else:
            ids = self.Agent.agentprofile_set.values_list('profileId',
                                                          flat=True)
        return ids
Ejemplo n.º 15
0
    def get(self):
        ifp = get_agent_ifp(json.loads(self.agent))
        agent = models.Agent.objects.get(**ifp)

        try:
            if self.registration:
                return models.ActivityState.objects.get(
                    state_id=self.stateId,
                    agent=agent,
                    activity_id=self.activity_id,
                    registration_id=self.registration)
            return models.ActivityState.objects.get(
                state_id=self.stateId,
                agent=agent,
                activity_id=self.activity_id)
        except models.ActivityState.DoesNotExist:
            err_msg = 'There is no activity state associated with the id: %s' % self.stateId
            raise IDNotFoundError(err_msg)
Ejemplo n.º 16
0
def agents_get(req_dict):
    rogueparams = set(req_dict['params']) - set(["agent"])
    if rogueparams:
        raise ParamError("The get agent request contained unexpected parameters: %s" % ", ".join(rogueparams))

    try: 
        req_dict['params']['agent']
    except KeyError:
        err_msg = "Error -- agents url, but no agent parameter.. the agent parameter is required"
        raise ParamError(err_msg)

    agent = json.loads(req_dict['params']['agent'])
    params = get_agent_ifp(agent)

    if not models.Agent.objects.filter(**params).exists():
        raise IDNotFoundError("Error with Agent. The agent partial did not match any agents on record")

    req_dict['agent_ifp'] = params
    return req_dict
Ejemplo n.º 17
0
def activities_get(req_dict):
    rogueparams = set(req_dict['params']) - set(["activityId"])
    if rogueparams:
        raise ParamError("The get activities request contained unexpected parameters: %s" % ", ".join(rogueparams))

    try:
        activityId = req_dict['params']['activityId']
    except KeyError:
        err_msg = "Error -- activities - method = %s, but activityId parameter is missing" % req_dict['method']
        raise ParamError(err_msg)

    # Try to retrieve activity, if DNE then return empty else return activity info
    try:
        act = models.Activity.objects.get(activity_id=activityId)
    except models.Activity.DoesNotExist:    
        err_msg = "No activity found with ID %s" % activityId
        raise IDNotFoundError(err_msg)

    return req_dict
Ejemplo n.º 18
0
    def get_profile_ids(self, since=None):
        ids = []
        if since:
            try:
                profs = self.agent.agent_profile_set.filter(updated__gte=since)
            except ValidationError:
                since_i = int(float(since))
                since_dt = datetime.datetime.fromtimestamp(since_i)
                profs = self.agent.agent_profile_set.filter(
                    update__gte=since_dt)
            except:
                raise IDNotFoundError(
                    'There are no profiles associated with the id: %s' %
                    profileId)

            ids = [p.profileId for p in profs]
        else:
            ids = self.agent.agent_profile_set.values_list('profileId',
                                                           flat=True)
        return ids
Ejemplo n.º 19
0
    def get(self, auth):
        agent = self.__get_agent()
        # pdb.set_trace()
        # if not agent.mbox is None:
        #     if agent.mbox != auth.email:
        #         raise Forbidden("Unauthorized to retrieve activity state with ID %s" % self.stateId)

        try:
            if self.registrationId:
                return models.activity_state.objects.get(
                    state_id=self.stateId,
                    agent=agent,
                    activity=self.activity,
                    registration_id=self.registrationId)
            return models.activity_state.objects.get(state_id=self.stateId,
                                                     agent=agent,
                                                     activity=self.activity)
        except models.activity_state.DoesNotExist:
            raise IDNotFoundError(
                'There is no activity state associated with the id: %s' %
                self.stateId)
Ejemplo n.º 20
0
def server_validate_statement_object(stmt_object, auth):
    if stmt_object['objectType'] == 'StatementRef' and not check_for_existing_statementId(stmt_object['id']):
            err_msg = "No statement with ID %s was found" % stmt_object['id']
            raise IDNotFoundError(err_msg)
    elif stmt_object['objectType'] == 'Activity' or 'objectType' not in stmt_object:
        if 'definition' in stmt_object:
            try:
                activity = models.Activity.objects.get(activity_id=stmt_object['id'], canonical_version=True)
            except models.Activity.DoesNotExist:
                pass
            else:
                if auth:
                    if auth['id'].__class__.__name__ == 'Agent':
                        auth_name = auth['id'].name
                    else:
                        auth_name = auth['id'].username
                else:
                    auth_name = None
                if activity.authoritative != '' and activity.authoritative != auth_name:
                    err_msg = "This ActivityID already exists, and you do not have the correct authority to create or update it."
                    raise Forbidden(err_msg)
Ejemplo n.º 21
0
 def get_profile(self, profileId):
     try:
         return self.agent.agent_profile_set.get(profileId=profileId)
     except:
         raise IDNotFoundError(
             'There is no profile associated with the id: %s' % profileId)