示例#1
0
文件: views.py 项目: DHLabs/keep_isn
def xml_submission( request, username ):
    '''
        See: https://bitbucket.org/javarosa/javarosa/wiki/FormSubmissionAPI

        Parse an xml_submission_file and add the data into the specified repo.
    '''
    success_response = '''
        <OpenRosaResponse xmlns="http://openrosa.org/http/response">
            <message>Form Received!</message>
        </OpenRosaResponse>'''

    root = etree.fromstring(request.FILES[ 'xml_submission_file' ].read())

    # Find the user object associated with this username
    account = user_or_organization( username )

    # The find the repo object associated with this form name & user
    repo_name = root.tag
    repo = Repository.objects.get_by_username( repo_name, username )

    # Parse the xml data
    xml_data = {}
    _parse_xml_submission( xml_data, root, request.FILES )

    # Do basic validation of the data
    repo.add_data( xml_data, request.FILES )

    response = HttpResponse( success_response, mimetype='application/json' )
    response[ 'X-OpenRosa-Version' ] = '1.0'

    return response
示例#2
0
def xml_submission(request, username):
    '''
        See: https://bitbucket.org/javarosa/javarosa/wiki/FormSubmissionAPI

        Parse an xml_submission_file and add the data into the specified repo.
    '''
    success_response = '''
        <OpenRosaResponse xmlns="http://openrosa.org/http/response">
            <message>Form Received!</message>
        </OpenRosaResponse>'''

    root = etree.fromstring(request.FILES['xml_submission_file'].read())

    # Find the user object associated with this username
    account = user_or_organization(username)

    # The find the repo object associated with this form name & user
    repo_name = root.tag
    repo = Repository.objects.get_by_username(repo_name, username)

    # Parse the xml data
    xml_data = {}
    _parse_xml_submission(xml_data, root, request.FILES)

    # Do basic validation of the data
    repo.add_data(xml_data, request.FILES)

    response = HttpResponse(success_response, mimetype='application/json')
    response['X-OpenRosa-Version'] = '1.0'

    return response
示例#3
0
文件: views.py 项目: EdbertChan/keep
def repo_viz( request, username, repo_name ):
    '''
        View repo <repo_name> under user <username>.

        Does the checks necessary to determine whether the current user has the
        authority to view the current repository.
    '''

    # Grab the user/organization based on the username
    account = user_or_organization( username )
    if account is None:
        return HttpResponse( status=404 )

    # Grab the repository
    repo = Repository.objects.get_by_username( repo_name, username )
    if repo is None:
        return HttpResponse( status=404 )

    # Grab all the permissions!
    permissions = []
    if request.user.is_authenticated():
        permissions = get_perms( request.user, repo )
        for org in request.user.organization_users.all():
            permissions.extend( get_perms( org, repo ) )

    # Check to see if the user has access to view this survey
    if not repo.is_public and 'view_repository' not in permissions:
        return HttpResponse( 'Unauthorized', status=401 )

    # Grab the data for this repository
    data = db.data.find( { 'repo': ObjectId( repo.mongo_id ) },
                         { 'survey_label': False,
                           'user': False } )\
                  .sort( [ ('timestamp', pymongo.DESCENDING ) ] )

    data = dehydrate_survey( data )

    # Is some unknown user looking at this data?
    # TODO: Make the privatizer take into account
    # geospatial location
    # if 'view_raw' not in permissions:
    #     data = privatize_geo( repo, data )

    usePerms = get_users_with_perms( repo, attach_perms=True )
    usePerms.pop( account, None )

    if isinstance( account, User ):
        account_name = account.username
    else:
        account_name = account.name

    return render_to_response( 'visualize.html',
                               { 'repo': repo,
                                 'sid': repo.mongo_id,
                                 'data': json.dumps( data ),
                                 'permissions': permissions,
                                 'account': account,
                                 'account_name': account_name,
                                 'users_perms': usePerms },
                               context_instance=RequestContext(request) )
示例#4
0
文件: views.py 项目: EdbertChan/keep
def share_repo( request, repo_id ):
    '''
        Modifies sharing permissions for specific users
    '''

    repo = get_object_or_404( Repository, mongo_id=repo_id )

    if not request.user.has_perm( 'share_repository', repo ):
        return HttpResponse( 'Unauthorized', status=401 )

    if request.method == 'POST':
        username = request.POST.get( 'username', None )
    else:
        username = request.GET.get( 'username', None )

    # Grab the user/organization based on the username
    account = user_or_organization( username )
    if account is None:
        return HttpResponse( status=404 )

    if account == request.user:
        return HttpResponse( status=401 )

    if request.method == 'DELETE':
        old_permissions = get_perms( account, repo )
        for old_permission in old_permissions:
            remove_perm( old_permission, account, repo )
        return HttpResponse( 'success', status=204 )
    else:
        new_permissions = request.POST.get( 'permissions', '' ).split(',')
        for new_permission in new_permissions:
            assign_perm( new_permission, account, repo )
        return HttpResponse( 'success', status=200 )
示例#5
0
文件: repo.py 项目: EdbertChan/keep
    def post_detail( self, request, **kwargs ):

        #basic_bundle = self.build_bundle( request=request )

        user_accessing = request.GET.get( 'user', None )
        user = user_or_organization( user_accessing )
        if user is None:
            return HttpUnauthorized()

        repo = Repository.objects.get( mongo_id=kwargs.get( 'mongo_id' ) )
        if repo is None:
            return HttpNotFound()

        if not user.has_perm( 'add_data', repo ):
            return HttpUnauthorized()

        new_id = repo.add_data( request.POST, request.FILES )

        response_data = { 'success': True, 'id': str( new_id ) }
        return self.create_response( request, response_data )
示例#6
0
    def create_detail( self, object_detail, bundle ):

        logged_in_user = bundle.request.user
        user = bundle.request.POST.get( 'user', None ) or bundle.request.GET.get( 'user', None )
        key  = bundle.request.POST.get( 'key', None ) or bundle.request.GET.get( 'key', None )

        # Case 1: No user query & the user is not logged in?
        if user is None and logged_in_user.is_anonymous():
            return False

        # Case 2: Session call. Check if the specified user has permission to
        # add data to this repo.
        if user is None and logged_in_user.is_authenticated():
            return logged_in_user.has_perm( 'add_data', object_detail )

        # Case 3: API call. Check if the specified user has permission to add
        # data to this repo
        if user is not None and key is not None:
            user = user_or_organization( user )
            return user.has_perm( 'add_data', object_detail )

        return False
示例#7
0
    def create_detail( self, object_detail, bundle ):

        logged_in_user = bundle.request.user
        user = bundle.request.POST.get( 'user', None )
        key  = bundle.request.POST.get( 'key', None )

        # Case 1: No user query & the user is not logged in?
        if user is None and logged_in_user.is_anonymous():
            return False

        # Case 2: Session call. Check if the specified user has permission to
        # add data to this repo.
        if user is None and logged_in_user.is_authenticated():
            return logged_in_user.has_perm( 'add_data', object_detail )

        # Case 3: API call. Check if the specified user has permission to add
        # data to this repo
        if user is not None and key is not None:
            user = user_or_organization( user )
            return user.has_perm( 'add_data', object_detail )

        return False
示例#8
0
文件: views.py 项目: EdbertChan/keep
def webform( request, username, repo_name ):
    '''
        Simply grab the survey data and send it on the webform. The webform
        will handle rendering and submission of the final data to the server.
    '''

    account = user_or_organization( username )
    if account is None:
        return HttpResponse( status=404 )

    # Grab the repository
    repo = Repository.objects.get_by_username( repo_name, username )
    if repo is None:
        return HttpResponse( status=404 )

    if request.method == 'POST':

        # Do validation of the data and add to repo!
        repo.add_data( request.POST, request.FILES )

        # Return to organization/user dashboard based on where the "New Repo"
        # button was clicked.  Send Non-users to thank-you page
        if not request.user.is_authenticated():
            return render_to_response( 'finish_survey.html' )

        elif isinstance( account, User ):
            return HttpResponseRedirect(
                        reverse( 'user_dashboard',
                                 kwargs={ 'username': account.username } ) )
        else:
            return HttpResponseRedirect(
                        reverse( 'organization_dashboard',
                                 kwargs={ 'org': account.name } ) )

    return render_to_response( 'webform.html',
                               { 'repo': repo,
                                 'repo_id': repo.mongo_id,
                                 'account': account },
                               context_instance=RequestContext( request ))
示例#9
0
文件: views.py 项目: ajermaky/keep
def share_repo(request, repo_id):
    """
        Modifies sharing permissions for specific users
    """

    repo = get_object_or_404(Repository, mongo_id=repo_id)

    if not request.user.has_perm('share_repository', repo):
        return HttpResponse('Unauthorized', status=401)

    if request.method == 'POST':
        username = request.POST.get('username', None)
    elif request.method == 'DELETE':
        username = request.GET.get('username', None)
    else:
        username = request.GET.get('username', None)

    # Grab the user/organization based on the username
    account = user_or_organization(username)
    if account is None:
        return HttpResponse(status=404)

    if account == request.user:
        return HttpResponse(status=401)

    # Remove permissions from user
    if request.method == 'DELETE':
        old_permissions = get_perms(account, repo)
        for old_permission in old_permissions:
            remove_perm(old_permission, account, repo)
        return HttpResponse('success', status=204)
    # Add certain permissions for a specific user
    else:
        new_permissions = request.POST.get('permissions', '').split(',')
        for new_permission in new_permissions:
            assign_perm(new_permission, account, repo)
        return HttpResponse('success', status=200)
示例#10
0
文件: views.py 项目: DHLabs/keep_isn
def repo_viz( request, username, repo_name, filter_param=None ):
    """
        View repo <repo_name> under user <username>.

        Does the checks necessary to determine whether the current user has the
        authority to view the current repository.
    """

    # Grab the user/organization based on the username
    account = user_or_organization( username )
    if account is None:
        return HttpResponse( status=404 )

    # Grab the repository
    repo = Repository.objects.get_by_username( repo_name, username )
    if repo is None:
        return HttpResponse( status=404 )

    # Grab all the permissions!
    permissions = []
    if request.user.is_authenticated():
        permissions = get_perms( request.user, repo )
        for org in request.user.organization_users.all():
            permissions.extend( get_perms( org, repo ) )

    apiauth = ApiTokenAuthentication()

    #if (not request.user.is_authenticated()) and (not apiauth.is_authenticated( request )):
    #    return HttpResponse( 'Unauthorized', status=401 )

    # Check to see if the user has access to view this survey
    # if not repo.is_public and 'view_repository' not in permissions:
    #     print request.user
    #     print permissions
    #     return HttpResponse( 'Unauthorized', status=401 )

    #----------------------------------------------------------------------
    #
    # Query and serialize data from this repository
    #
    #----------------------------------------------------------------------
    data_query = { 'repo': ObjectId( repo.mongo_id ) }

    if 'doctor_id' in request.GET:
        data_query['data.doctor_id'] = request.GET['doctor_id']
    #elif (not request.user.is_authenticated()):
    #    return HttpResponse( 'Unauthorized', status=401 )

    if repo.study and filter_param:
        data_query[ 'data.%s' % repo.study.tracker ] = filter_param

    # Grab the data for this repository


    if 'doctor_id' in request.GET:
        data = db.data.find( data_query,
                         { 'survey_label': False,
                           'user': False } )\
                  .sort( [ ('timestamp', pymongo.DESCENDING ) ] )
    else:
        data = db.data.find( data_query,
                         { 'survey_label': False,
                           'user': False } )\
                  .sort( [ ('timestamp', pymongo.DESCENDING ) ] )\
                  .limit( 25 )

    data_serializer = DataSerializer()
    if repo.is_tracker and repo.study:
        linked = Repository.objects.filter( study=repo.study ).exclude( id=repo.id )
        data = data_serializer.dehydrate( data, repo,linked )
    else:
        data = data_serializer.dehydrate( data, repo )

    # Is some unknown user looking at this data?
    # TODO: Make the privatizer take into account
    # geospatial location
    # if 'view_raw' not in permissions:
    #     data = privatize_geo( repo, data )

    usePerms = get_users_with_perms( repo, attach_perms=True )
    usePerms.pop( account, None )

    serializer = RepoSerializer()
    repo_json = json.dumps( serializer.serialize( [repo] )[0] )

    flat_fields = json.dumps(repo.flatten_fields())

    # Grab linked repos if this repo is a "tracker" and part of study
    linked_json = '[]'
    if repo.study and repo.is_tracker:
        # If this repo is a tracker and part of a study, grab all repos that
        # are part of the study so that we can display data links.
        linked = Repository.objects.filter( study=repo.study ).exclude( id=repo.id )
        linked_list = list(linked)
        linkone = linked_list[0]
        linked_list[0] = linked_list[1]
        linked_list[1] = linkone
        linked_json = json.dumps( serializer.serialize( linked_list ) )

    # Grab the list of visualizations for this repo
    viz_serializer = VisualizationSerializer()
    viz_json = json.dumps( viz_serializer.serialize( repo.visualizations.all() ) )

    patient_id = None
    if 'patient_id' in request.GET:
        patient_id = request.GET['patient_id']

    return render_to_response( 'visualize.html',
                               { 'repo': repo,

                                 'flat_fields': flat_fields,
                                 'repo_json': repo_json,
                                 'linked_json': linked_json,
                                 'viz_json': viz_json,

                                 'data': json.dumps( data ),

                                 'permissions': permissions,
                                 'account': account,
                                 'users_perms': usePerms,
                                 'patient_id': patient_id
                               },
                               context_instance=RequestContext(request) )
示例#11
0
文件: views.py 项目: DHLabs/keep_isn
def webform( request, username, repo_name ):
    """
        Simply grab the survey data and send it on the webform. The webform
        will handle rendering and submission of the final data to the server.
    """

    account = user_or_organization( username )
    if account is None:
        return HttpResponse( status=404 )

    # Grab the repository
    repo = Repository.objects.get_by_username( repo_name, username )
    if repo is None:
        return HttpResponse( status=404 )

    if request.method == 'POST':

        if 'detail_data_id' in request.POST:
            
            repo.update_data( request.POST, request.FILES )

            if 'async' in request.POST:
                return HttpResponse( 'success', status=200 )

            if 'doctor_id' in request.POST:
                url_send = '/' + account.username + '/patient_list/'

                 #get patient id
                patient_id = db.data.find( {"label": repo_name, "_id":ObjectId(request.POST['detail_data_id'])} )[0]['data']['patient_id']


                if not request.user.is_authenticated():
                    token = UserAPIToken.objects.filter( user=account )[0]

                    url_send = url_send + '?key=' + token.key + '&user='******'&doctor_id=' + request.POST['doctor_id']
                    url_send = url_send + "&patient_id=" + patient_id
                else:
                    url_send = url_send + "?patient_id=" + patient_id
               
                return HttpResponseRedirect( url_send )

            return HttpResponseRedirect(
                        reverse( 'repo_visualize',
                                  kwargs={ 'username': account.username,
                                           'repo_name': repo_name } ) )
        else:

            # Do validation of the data and add to repo!
            new_data_id = repo.add_data( request.POST, request.FILES )

            if 'async' in request.POST:
                return HttpResponse( new_data_id, status=200 )

            # Return to organization/user dashboard based on where the "New Repo"
            # button was clicked.  Send Non-users to thank-you page
            if not request.user.is_authenticated():
                return render_to_response( 'finish_survey.html' )

            elif isinstance( account, User ):
                return HttpResponseRedirect(
                            reverse( 'user_dashboard',
                                     kwargs={ 'username': account.username } ) )
            else:
                return HttpResponseRedirect(
                            reverse( 'organization_dashboard',
                                     kwargs={ 'org': account.name } ) )

    serializer = RepoSerializer()
    repo_json = json.dumps( serializer.serialize( [repo] )[0] )

    flat_fields = repo.flatten_fields_with_group()
    
    if 'label' not in flat_fields[0] or isinstance( flat_fields[0]["label"] , basestring):
        has_translations = False
    else:
        has_translations = True

    flat_field_json = json.dumps(flat_fields)

    data_id = None
    is_finished = False

    request.GET = request.GET.copy()

    orig_data = None
    if 'patient_id' in request.GET and not 'data_id' in request.GET:
        #check if there's data for this patient
        patient_datas = db.data.find( { "label":repo.name, "data.patient_id":request.GET['patient_id'] } )
        if patient_datas.count() > 0:
            orig_data = patient_datas[0]
            #add all data to query string
            url_to_send = request.get_full_path()

            if url_to_send[ len(url_to_send) - 1 ] == "&":
                url_to_send = url_to_send[:(len(url_to_send)-2)]

            url_to_send = url_to_send + "&data_id=" + str(orig_data['_id'])

            #do a redirect to new get url
            for key in orig_data['data']:
                if key == 'patient_id' and "patient_id" in url_to_send:
                    continue
                url_to_send = url_to_send + '&' + key + "="

                value = orig_data['data'][key]
                if isinstance( value, list ):
                    #put values together
                    new_val = ",".join( value )
                    url_to_send = url_to_send + str(new_val).encode('utf-8')
                else:
                    url_to_send = url_to_send + str(value).encode('utf-8')

            return HttpResponseRedirect( url_to_send )

    if not orig_data:
        if 'data_id' in request.GET:
            data_id = request.GET['data_id']
            orig_data = db.data.find(  {"_id":ObjectId( data_id )} )[0]

    if orig_data and 'is_finished' in orig_data:
        is_finished = orig_data['is_finished']

    return render_to_response( 'webform.html',
                               { 'repo': repo,
                                 'repo_json': repo_json,
                                 'flat_fields': flat_fields,
                                 'flat_field_json':flat_field_json,
                                 'has_translations': has_translations,
                                 'repo_id': repo.mongo_id,
                                 'account': account,
                                 'data_id': data_id,
                                 'is_finished': is_finished                                  
                                },
                               context_instance=RequestContext( request ))
示例#12
0
文件: views.py 项目: DHLabs/keep
def repo_viz( request, username, repo_name, filter_param=None ):
    """
        View repo <repo_name> under user <username>.

        Does the checks necessary to determine whether the current user has the
        authority to view the current repository.
    """

    # Grab the user/organization based on the username
    account = user_or_organization( username )
    if account is None:
        return HttpResponse( status=404 )

    # Grab the repository
    repo = Repository.objects.get_by_username( repo_name, username )
    if repo is None:
        return HttpResponse( status=404 )

    # If the repo is part of a study, grab the tracker repo
    tracker_repo = repo.registry()

    # Grab all the permissions!
    permissions = []
    if request.user.is_authenticated():
        permissions = get_perms( request.user, repo )
        for org in request.user.organization_users.all():
            permissions.extend( get_perms( org, repo ) )

    # Check to see if the user has access to view this survey
    if not repo.is_public and 'view_repository' not in permissions:
        return HttpResponse( 'Unauthorized', status=401 )

    #----------------------------------------------------------------------
    #
    # Query and serialize data from this repository
    #
    #----------------------------------------------------------------------
    data_query = { 'repo': ObjectId( repo.mongo_id ) }

    if repo.study and filter_param:
        data_query[ 'data.%s' % repo.study.tracker ] = filter_param

    # Grab the data for this repository
    data = db.data.find( data_query,
                         { 'survey_label': False,
                           'user': False } )\
                  .sort( [ ('timestamp', pymongo.DESCENDING ) ] )\
                  .limit( 50 )

    data_serializer = DataSerializer()
    if repo.is_tracker and repo.study:
        linked = Repository.objects.filter( study=repo.study ).exclude( id=repo.id )
        data = data_serializer.dehydrate( data, repo,linked )
    else:
        data = data_serializer.dehydrate( data, repo )

    # Is some unknown user looking at this data?
    # TODO: Make the privatizer take into account
    # geospatial location
    # if 'view_raw' not in permissions:
    #     data = privatize_geo( repo, data )

    # Get all accounts (users and orgs) with permissions to this repo.
    users_with_perms = get_users_with_perms( repo, attach_perms=True )
    # Don't want to show your own account
    users_with_perms.pop( account, None )
    orgs_with_perms = get_groups_with_perms( repo, attach_perms=True )
    account_perms = users_with_perms.copy()
    account_perms.update(orgs_with_perms)

    serializer = RepoSerializer()
    repo_json = json.dumps( serializer.serialize( [repo] )[0] )

    # Grab linked repos if this repo is a "tracker" and part of study
    linked_json = '[]'
    if repo.study and repo.is_tracker:
        # If this repo is a tracker and part of a study, grab all repos that
        # are part of the study so that we can display data links.
        linked = []
        study_repos = Repository.objects.filter( study=repo.study ).exclude( id=repo.id )
        orgs = request.user.organization_users.all()
        for r in study_repos:
            if repo.is_public or repo.is_form_public or request.user.has_perm( 'view_repository', repo ):
                linked.append(r)
            else:
                for org in orgs:
                    if 'view_repository' in get_perms(org, r):
                        linked.append(r)

        linked_json = json.dumps( serializer.serialize( linked ) )

    # Grab the list of visualizations for this repo
    viz_serializer = VisualizationSerializer()
    viz_json = json.dumps( viz_serializer.serialize( repo.visualizations.all() ) )

    # Get JSON for filters using TastyPie serializers
    fsr = FilterSetResource()
    filters = FilterSet.objects.filter(repo=repo.id)
    bundles = [fsr.build_bundle(obj=f, request=request) for f in filters]
    filter_data = [fsr.full_dehydrate(bundle) for bundle in bundles]
    filter_json = fsr.serialize(request, filter_data, 'application/json')
    resource_ids = {'user_id': request.user.id, 'repo_id': repo.id }

    return render_to_response( 'visualize.html',
                               { 'repo': repo,
                                 'registry': tracker_repo,

                                 'repo_json': repo_json,
                                 'linked_json': linked_json,
                                 'viz_json': viz_json,
                                 'filter_json': filter_json,
                                 'resource_ids': resource_ids,

                                 'data': json.dumps( data ),

                                 'permissions': permissions,
                                 'account': account,
                                 'account_perms': account_perms },
                               context_instance=RequestContext(request) )
示例#13
0
文件: views.py 项目: DHLabs/keep
def webform( request, username, repo_name ):
    """
        Simply grab the survey data and send it on the webform. The webform
        will handle rendering and submission of the final data to the server.
    """

    account = user_or_organization( username )
    if account is None:
        return HttpResponse( status=404 )

    # Grab the repository
    repo = Repository.objects.get_by_username( repo_name, username )
    if repo is None:
        return HttpResponse( status=404 )

    # If the repo is part of a study, grab the tracker repo
    tracker_repo = repo.registry()

    if request.method == 'POST':

        if 'detail_data_id' in request.POST:

            repo.update_data( request.POST, request.FILES )

            # If part of a study, return to registry
            if tracker_repo:
                destination = { 'repo_name': tracker_repo.name,
                                'username': tracker_repo.owner() }
            else:
                destination = { 'repo_name': repo_name,
                                'username': account.username }

            return HttpResponseRedirect( reverse( 'repo_visualize', kwargs=destination) )
        else:

            # Do validation of the data and add to repo!
            repo.add_data( request.POST, request.FILES )

            # Return to organization/user dashboard based on where the "New Repo"
            # button was clicked.  Send Non-users to thank-you page
            if not request.user.is_authenticated():
                return render_to_response( 'finish_survey.html' )

            # If part of a study, return to registry
            elif tracker_repo:
                destination = { 'repo_name': tracker_repo.name,
                                'username': tracker_repo.owner() }

                return HttpResponseRedirect( reverse( 'repo_visualize', kwargs=destination) )

            elif isinstance( account, User ):
                return HttpResponseRedirect(
                            reverse( 'user_dashboard',
                                     kwargs={ 'username': account.username } ) )
            else:
                return HttpResponseRedirect(
                            reverse( 'organization_dashboard',
                                     kwargs={ 'org': account.name } ) )

    serializer = RepoSerializer()
    repo_json = json.dumps( serializer.serialize( [repo] )[0] )
    flat_fields = repo.flatten_fields_with_group()
    first_field = flat_fields[0]

    # Check if first field is question/group with label translations. If the
    # first field is a tracker field, then check the second field for
    # translations. (The tracker field is added automatically and doesn't
    # have translations).
    if 'label' in first_field and first_field['label'] == 'id':
        first_field = flat_fields[1]
    if 'label' in first_field and isinstance(first_field['label'], dict):
        has_translations = True
        translations = first_field['label'].keys
    elif first_field['type'] == 'group' and isinstance( first_field['children'][0]['label'], dict):
        # The first field is a group w/o a translation, so check if the first
        # question in the group has a translation.
        has_translations = True
        translations = first_field['children'][0]['label'].keys
    else:
        has_translations = False
        translations = []

    flat_field_json = json.dumps(flat_fields)

    data_id = None
    if 'data_id' in request.GET:
        data_id = request.GET['data_id']

    return render_to_response( 'webform.html',
                               { 'repo': repo,
                                 'registry': tracker_repo,
                                 'repo_json': repo_json,
                                 'flat_fields': flat_fields,
                                 'flat_field_json':flat_field_json,
                                 'has_translations': has_translations,
                                 'translations': translations,
                                 'repo_id': repo.mongo_id,
                                 'account': account,
                                 'data_id': data_id
                                  },
                               context_instance=RequestContext( request ))
示例#14
0
文件: views.py 项目: ajermaky/keep
def repo_viz(request, username, repo_name, filter_param=None):
    """
        View repo <repo_name> under user <username>.

        Does the checks necessary to determine whether the current user has the
        authority to view the current repository.
    """

    # Grab the user/organization based on the username
    account = user_or_organization(username)
    if account is None:
        return HttpResponse(status=404)

    # Grab the repository
    repo = Repository.objects.get_by_username(repo_name, username)
    if repo is None:
        return HttpResponse(status=404)

    # If the repo is part of a study, grab the tracker repo
    tracker_repo = repo.registry()

    # Grab all the permissions!
    permissions = []
    if request.user.is_authenticated():
        permissions = get_perms(request.user, repo)
        for org in request.user.organization_users.all():
            permissions.extend(get_perms(org, repo))

    # Check to see if the user has access to view this survey
    if not repo.is_public and 'view_repository' not in permissions:
        return HttpResponse('Unauthorized', status=401)

    #----------------------------------------------------------------------
    #
    # Query and serialize data from this repository
    #
    #----------------------------------------------------------------------
    data_query = {'repo': ObjectId(repo.mongo_id)}

    if repo.study and filter_param:
        data_query['data.%s' % repo.study.tracker] = filter_param

    # Grab the data for this repository
    data = db.data.find( data_query,
                         { 'survey_label': False,
                           'user': False } )\
                  .sort( [ ('timestamp', pymongo.DESCENDING ) ] )\
                  .limit( 50 )

    data_serializer = DataSerializer()
    if repo.is_tracker and repo.study:
        linked = Repository.objects.filter(study=repo.study).exclude(
            id=repo.id)
        data = data_serializer.dehydrate(data, repo, linked)
    else:
        data = data_serializer.dehydrate(data, repo)

    # Is some unknown user looking at this data?
    # TODO: Make the privatizer take into account
    # geospatial location
    # if 'view_raw' not in permissions:
    #     data = privatize_geo( repo, data )

    # Get all accounts (users and orgs) with permissions to this repo.
    users_with_perms = get_users_with_perms(repo, attach_perms=True)
    # Don't want to show your own account
    users_with_perms.pop(account, None)
    orgs_with_perms = get_groups_with_perms(repo, attach_perms=True)
    account_perms = users_with_perms.copy()
    account_perms.update(orgs_with_perms)

    serializer = RepoSerializer()
    repo_json = json.dumps(serializer.serialize([repo])[0])

    # Grab linked repos if this repo is a "tracker" and part of study
    linked_json = '[]'
    if repo.study and repo.is_tracker:
        # If this repo is a tracker and part of a study, grab all repos that
        # are part of the study so that we can display data links.
        linked = []
        study_repos = Repository.objects.filter(study=repo.study).exclude(
            id=repo.id)
        orgs = request.user.organization_users.all()
        for r in study_repos:
            if repo.is_public or repo.is_form_public or request.user.has_perm(
                    'view_repository', repo):
                linked.append(r)
            else:
                for org in orgs:
                    if 'view_repository' in get_perms(org, r):
                        linked.append(r)

        linked_json = json.dumps(serializer.serialize(linked))

    # Grab the list of visualizations for this repo
    viz_serializer = VisualizationSerializer()
    viz_json = json.dumps(viz_serializer.serialize(repo.visualizations.all()))

    # Get JSON for filters using TastyPie serializers
    fsr = FilterSetResource()
    filters = FilterSet.objects.filter(repo=repo.id)
    bundles = [fsr.build_bundle(obj=f, request=request) for f in filters]
    filter_data = [fsr.full_dehydrate(bundle) for bundle in bundles]
    filter_json = fsr.serialize(request, filter_data, 'application/json')
    resource_ids = {'user_id': request.user.id, 'repo_id': repo.id}

    return render_to_response('visualize.html', {
        'repo': repo,
        'registry': tracker_repo,
        'repo_json': repo_json,
        'linked_json': linked_json,
        'viz_json': viz_json,
        'filter_json': filter_json,
        'resource_ids': resource_ids,
        'data': json.dumps(data),
        'permissions': permissions,
        'account': account,
        'account_perms': account_perms
    },
                              context_instance=RequestContext(request))
示例#15
0
文件: views.py 项目: ajermaky/keep
def webform(request, username, repo_name):
    """
        Simply grab the survey data and send it on the webform. The webform
        will handle rendering and submission of the final data to the server.
    """

    account = user_or_organization(username)
    if account is None:
        return HttpResponse(status=404)

    # Grab the repository
    repo = Repository.objects.get_by_username(repo_name, username)
    if repo is None:
        return HttpResponse(status=404)

    # If the repo is part of a study, grab the tracker repo
    tracker_repo = repo.registry()

    if request.method == 'POST':

        if 'detail_data_id' in request.POST:

            repo.update_data(request.POST, request.FILES)

            # If part of a study, return to registry
            if tracker_repo:
                destination = {
                    'repo_name': tracker_repo.name,
                    'username': tracker_repo.owner()
                }
            else:
                destination = {
                    'repo_name': repo_name,
                    'username': account.username
                }

            return HttpResponseRedirect(
                reverse('repo_visualize', kwargs=destination))
        else:

            # Do validation of the data and add to repo!
            repo.add_data(request.POST, request.FILES)

            # Return to organization/user dashboard based on where the "New Repo"
            # button was clicked.  Send Non-users to thank-you page
            if not request.user.is_authenticated():
                return render_to_response('finish_survey.html')

            # If part of a study, return to registry
            elif tracker_repo:
                destination = {
                    'repo_name': tracker_repo.name,
                    'username': tracker_repo.owner()
                }

                return HttpResponseRedirect(
                    reverse('repo_visualize', kwargs=destination))

            elif isinstance(account, User):
                return HttpResponseRedirect(
                    reverse('user_dashboard',
                            kwargs={'username': account.username}))
            else:
                return HttpResponseRedirect(
                    reverse('organization_dashboard',
                            kwargs={'org': account.name}))

    serializer = RepoSerializer()
    repo_json = json.dumps(serializer.serialize([repo])[0])
    flat_fields = repo.flatten_fields_with_group()
    first_field = flat_fields[0]

    # Check if first field is question/group with label translations. If the
    # first field is a tracker field, then check the second field for
    # translations. (The tracker field is added automatically and doesn't
    # have translations).
    if 'label' in first_field and first_field['label'] == 'id':
        first_field = flat_fields[1]
    if 'label' in first_field and isinstance(first_field['label'], dict):
        has_translations = True
        translations = first_field['label'].keys
    elif first_field['type'] == 'group' and isinstance(
            first_field['children'][0]['label'], dict):
        # The first field is a group w/o a translation, so check if the first
        # question in the group has a translation.
        has_translations = True
        translations = first_field['children'][0]['label'].keys
    else:
        has_translations = False
        translations = []

    flat_field_json = json.dumps(flat_fields)

    data_id = None
    if 'data_id' in request.GET:
        data_id = request.GET['data_id']

    return render_to_response('webform.html', {
        'repo': repo,
        'registry': tracker_repo,
        'repo_json': repo_json,
        'flat_fields': flat_fields,
        'flat_field_json': flat_field_json,
        'has_translations': has_translations,
        'translations': translations,
        'repo_id': repo.mongo_id,
        'account': account,
        'data_id': data_id
    },
                              context_instance=RequestContext(request))