Example #1
0
    def hydrate(self, bundle):
        ## get all data from bundle.data
        user = bundle.request.user.get_profile()

        category = ProgramAnnotation.CATEGORY
        data = bundle.data['data']
        environment = None
        area = None

        try:
            environment = EnvironmentResource().get_via_uri(
                bundle.data['environment'], request=bundle.request)
        except:
            environment = None

        try:
            area = AreaResource().get_via_uri(bundle.data['area'],
                                              request=bundle.request)
        except:
            area = None

        try:
            bundle.obj = ProgramAnnotation(user=user,
                                           environment=environment,
                                           area=area,
                                           category=category,
                                           data=data)
        except DuplicateAnnotationException, e:
            raise ImmediateHttpResponse(response=http.HttpForbidden(
                content=e.get_message()))
Example #2
0
    def is_valid(self, bundle, request=None):
        from client.api import EnvironmentResource, AreaResource

        ## check that we have a user
        if not bundle.request.user or bundle.request.user.is_anonymous():
            return {'__all__': 'No user found in request.'}

        if not bundle.data:
            return {'__all__': 'No data submitted.'}

        errors = {}

        if bundle.request.method.upper() == "POST":
            env_obj = None
            area_obj = None

            if 'environment' in bundle.data:
                try:
                    env_obj = EnvironmentResource().get_via_uri(
                        bundle.data['environment'])
                except:
                    env_obj = None

            if 'area' in bundle.data:
                try:
                    area_obj = AreaResource().get_via_uri(bundle.data['area'])
                except:
                    area_obj = None

            if env_obj is None and area_obj is None:
                errors['environment'] = ['No or wrong environment uri']
                errors['area'] = ['No or wrong area uri']

            if not env_obj is None and not area_obj is None and area_obj.env != env_obj:
                errors['environment'] = [
                    "Environment resource mismatches parent environment of area resource."
                ]

        if not 'data' in bundle.data or not bundle.data['data']:
            errors['data'] = ["No or empty data field."]

        ## some additional validation of the data field might also be possible if no errors up to now
        if not errors:
            ann_cls = bundle.obj.__class__
            data = bundle.data['data']
            category = bundle.obj.__class__.CATEGORY

            data_errors = ann_cls.validate_data(category, data)
            if data_errors:
                errors['data'] = data_errors

                import sys
                print >> sys.stderr, data_errors

        return errors
Example #3
0
from django.conf.urls.defaults import patterns, include, url
#from tastypie.api import Api
from client.api import ClientApi
from client.api import EnvironmentResource, AreaResource, FeatureResource, AnnotationResource,\
                        AnnouncementResource, HistoryResource, UserResource, EnvrionmentContextResource
#from client.views import checkin, checkout

v1_api = ClientApi(api_name='v1')
v1_api.register(EnvironmentResource())
v1_api.register(AreaResource())
v1_api.register(FeatureResource())
v1_api.register(AnnotationResource())
v1_api.register(AnnouncementResource())
v1_api.register(HistoryResource())
v1_api.register(UserResource())
v1_api.register(EnvrionmentContextResource())

urlpatterns = patterns(
    '',
    #url(r'^checkin/$', checkin, name="checkin"),
    #url(r'^checkout/$', checkout, name="checkout"),
    (r'', include(v1_api.urls)),
)
Example #4
0
        ## return data about the area resource
        ar = AreaResource()
        ar_bundle = ar.build_bundle()
        ar_item = ar.obj_get(ar_bundle, pk=area.id)
        ar_bundle.obj = ar_item
        ar_bundle.request = request

        try:
            area_data = ar.full_dehydrate(ar_bundle).data
            response['data'].update(area_data)
        except ImmediateHttpResponse, error:
            return error.response

    elif env:
        ## return data about the environment resource
        envr = EnvironmentResource()
        envr_bundle = envr.build_bundle()
        envr_item = envr.obj_get(envr_bundle, pk=env.id)
        envr_bundle.obj = envr_item
        envr_bundle.request = request

        try:
            env_data = envr.full_dehydrate(envr_bundle).data
            response['data'].update(env_data)
        except ImmediateHttpResponse, error:
            return error.response

        ## include the list of all areas that belong to this environment
        area_list = []
        for ar in env.areas.all():
            area_dict = {
Example #5
0
def send_feature_update_message(environment=None,
                                area=None,
                                feature=None,
                                receivers='all'):
    """
    The function sends a feature update message for the feature `feature'.
    This `receivers' are either a list of User IDs, or the keyword `all' (by default).
    For the `all' case, we consider all users checked in at the given `area' (if not None), otherwise
    at the given `environment'.
    """
    import redis
    from django.conf import settings
    from datetime import datetime
    from pytz import timezone
    from coresql.models import UserContext
    from client.api import EnvironmentResource, AreaResource, FeatureResource

    redis_server = redis.Redis(host=settings.REDIS_HOST,
                               port=settings.REDIS_PORT,
                               db=settings.REDIS_DB)

    if feature is None:
        return

    if environment is None and area is None and receivers == 'all':
        return

    if receivers == 'all':
        utc_tz = timezone("UTC")
        timestamp = datetime.now(utc_tz)
        timestamp_str = timestamp.strftime("%Y-%m-%dT%H:%M:%S")
        '''build update message content'''
        feature_categ = feature.category
        update_type = FEATURE_RETRIEVE_CONTENT_LABEL

        ## get the feature resource URI
        feature_resource_class = feature.__class__.get_resource_class()
        feature_resource_uri = feature_resource_class().get_resource_uri(
            feature)

        ## get the location URI
        location_uri = None
        if area is not None:
            location_uri = AreaResource().get_resource_uri(area)
        elif environment is not None:
            location_uri = EnvironmentResource().get_resource_uri(environment)

        update_message = {
            'type': FEATURE_UPDATE_TYPE,
            'timestamp': timestamp_str,
            'content': {
                'feature': feature_categ.encode("utf8"),
                'location_uri': location_uri,
                'resource_uri': feature_resource_uri,
                'params': [{
                    'name': 'type',
                    'value': update_type
                }]
            }
        }
        '''send it to required uses'''
        if isinstance(receivers, basestring) and receivers == 'all':
            user_contexts = None

            if area is not None:
                user_contexts = UserContext.objects.filter(
                    currentArea=area).order_by('user').distinct()

            elif environment is not None:
                user_contexts = UserContext.objects.filter(
                    currentEnvironment=environment).order_by(
                        'user').distinct()

            for uc in user_contexts:
                user_id = uc.user.user.id

                ## send message on the user channel
                channel_name = str(user_id)
                redis_server.publish(channel_name, update_message)

    elif isinstance(receivers, list):
        '''receivers is already a list of user IDs for which to send the feature update notification'''
        for user_id in receivers:
            ## send message on the user channel
            channel_name = str(user_id)
            redis_server.publish(channel_name, update_message)
Example #6
0
    if area:
        ## return data about the area resource
        ar = AreaResource()
        ar_item = ar.obj_get(pk=area.id)
        ar_bundle = ar.build_bundle(obj=ar_item, request=request)

        try:
            area_data = ar.full_dehydrate(ar_bundle).data
            response["data"].update(area_data)
        except ImmediateHttpResponse, error:
            return error.response

    elif env:
        ## return data about the environment resource
        envr = EnvironmentResource()
        envr_item = envr.obj_get(pk=env.id)
        envr_bundle = envr.build_bundle(obj=envr_item, request=request)

        try:
            env_data = envr.full_dehydrate(envr_bundle).data
            response["data"].update(env_data)
        except ImmediateHttpResponse, error:
            return error.response

        ## include the list of all areas that belong to this environment
        area_list = []
        for ar in env.areas.all():
            area_dict = {"name": ar.name, "resource_uri": AreaResource().get_resource_uri(ar)}

            ## check if there are tags for this area
Example #7
0
    def is_authorized(self, request, object=None):
        from client.api import EnvironmentResource, AreaResource, AnnotationResource
        from coresql.models import Environment, Area
        from coresql.utils import str2bool

        if hasattr(request, 'user') and not request.user.is_anonymous():
            env_obj = None
            area_obj = None

            if request.method.upper() == "GET":
                if 'environment' in request.GET:
                    try:
                        env_obj = Environment.objects.get(
                            pk=request.GET['environment'])
                    except:
                        env_obj = None

                if 'area' in request.GET:
                    try:
                        area_obj = Area.objects.get(pk=request.GET['area'])
                    except:
                        area_obj = None
                ''' For GET requests we check if there is a virtual access flag set in the request.
                    If the flag is not set, the default behavior is to assume physical check-in '''
                if 'virtual' in request.GET:
                    try:
                        virtual = str2bool(request.GET['virtual'])
                        if virtual and (area_obj or env_obj):
                            ''' if the virtual flag is set to TRUE, then allow access, otherwise, check that 
                            the user is actually checked-in where he says he is '''
                            return True
                    except ValueError:
                        return False

            elif request.method.upper() == "POST":
                ''' for the rest of the methods check that the requesting user is actually checked in '''
                serdes = Serializer()
                deserialized = None
                try:
                    deserialized = serdes.deserialize(request.raw_post_data,
                                                      format=request.META.get(
                                                          'CONTENT_TYPE',
                                                          'application/json'))
                except Exception:
                    return False

                if deserialized is None:
                    return False

                if 'environment' in deserialized:
                    try:
                        #env_pk = int(deserialized['env'])
                        env_obj = EnvironmentResource().get_via_uri(
                            deserialized['environment'], request=request)
                    except:
                        env_obj = None

                if 'area' in deserialized:
                    try:
                        #area_pk = int(deserialized['area'])
                        area_obj = AreaResource().get_via_uri(
                            deserialized['area'], request=request)
                    except:
                        area_obj = None

            elif request.method.upper() in ["DELETE", "PUT"]:
                ann_res_uri = request.path
                try:
                    ann_obj = AnnotationResource().get_via_uri(ann_res_uri,
                                                               request=request)
                    env_obj = ann_obj.environment
                    area_obj = ann_obj.area

                    #print "[authorization] env_obj: ", env_obj
                    #print "[authorization] area_obj: ", area_obj
                except Exception:
                    #print "[authorization] exception in getting annotation resource for deletion: ", ex
                    env_obj = None
                    area_obj = None

            user_profile = request.user.get_profile(
            )  ## will be an instance of UserProfile => available context
            return is_checked_in(user_profile, env_obj, area_obj)

        return False
Example #8
0
    def is_valid(self, bundle, request=None):
        from client.api import EnvironmentResource, AreaResource
        from coresql.models import CATEGORY_CHOICES, Annotation

        ## check that we have a user
        if not bundle.request.user or bundle.request.user.is_anonymous():
            return {'__all__': 'No user found in request.'}

        if not bundle.data:
            return {'__all__': 'No data submitted.'}

        errors = {}

        if bundle.request.method.upper() == "POST":
            env_obj = None
            area_obj = None

            if 'environment' in bundle.data:
                try:
                    env_obj = EnvironmentResource().get_via_uri(
                        bundle.data['environment'])
                except:
                    env_obj = None

            if 'area' in bundle.data:
                try:
                    area_obj = AreaResource().get_via_uri(bundle.data['area'])
                except:
                    area_obj = None

            if env_obj is None and area_obj is None:
                errors['environment'] = ['No or wrong environment uri']
                errors['area'] = ['No or wrong area uri']

            if not env_obj is None and not area_obj is None and area_obj.env != env_obj:
                errors['environment'] = [
                    "Environment resource mismatches parent environment of area resource."
                ]

        if not 'data' in bundle.data or not bundle.data['data']:
            errors['data'] = ["No or empty data field."]

        if not 'category' in bundle.data or not (
                bundle.data['category'],
                bundle.data['category']) in CATEGORY_CHOICES:
            errors['category'] = ["No category specified or wrong category."]

        ## some additional validation of the data field might also be possible if no errors up to now
        if not errors:
            for _, cls in Annotation.get_subclasses():
                category = bundle.data['category']
                data = bundle.data['data']

                if cls.is_annotation_for(category, data):
                    data_errors = cls.validate_data(category, data)
                    if data_errors:
                        errors['data'] = data_errors

                        import sys
                        print >> sys.stderr, data_errors

                    break

        return errors