예제 #1
0
    def submit(self, params):
        url = params.get('url')
        content = params.get('content')
        user = self.getCurrentUser()

        # check permissions
        group = ModelImporter().model('group').find({'name': config['group']})

        if group.count():
            # the group must exist
            group = group[0]

            # the user must have read access to the group
            ModelImporter().model('group').requireAccess(
                group, user, AccessType.READ)

        else:
            raise AccessException('Invalid group name configured')

        # Create the diagnosis task
        statusMethod = server_support.handleDiagnosis(content=content, url=url)

        # Get the initial status
        status = statusMethod()

        # Get the maximum number of times to poll the task
        maxLoops = config['maxTaskWait'] / config['pollingInterval']

        # Loop until the task is finished
        iloop = 0
        while status['status'] == 'pending' and iloop < maxLoops:
            iloop += 1
            time.sleep(config['pollingInterval'])
            status = statusMethod()

        # Get status and report errors
        if status['status'] == 'pending':
            raise RestException("Task timed out.", code=408)

        if status['status'] == 'failure':
            raise RestException(status['message'], code=400)

        # check access to private data
        group = ModelImporter().model('group').find(
            {'name': config['privateGroup']})
        hasAccess = False
        if group.count():
            group = group[0]
            try:
                ModelImporter().model('group').requireAccess(
                    group, user, AccessType.READ)
                hasAccess = True
            except AccessException:
                pass

        # Append content data if the user has access
        if hasAccess:
            status["result"]["scrapedData"] = status["content"]

        return status["result"]
예제 #2
0
def createUser():
    ModelImporter().model('user').createUser(login='******',
                                             password='******',
                                             email='*****@*****.**',
                                             firstName='Admin',
                                             lastName='Admin',
                                             admin=True)
예제 #3
0
    def mongoSearch(self, params):
        self.requireParams(('type', 'q'), params)
        allowed = {
            'collection': ['_id', 'name', 'description'],
            'folder': ['_id', 'name', 'description'],
            'item': ['_id', 'name', 'description', 'folderId'],
            'user': ['_id', 'firstName', 'lastName', 'login']
        }
        limit, offset, sort = self.getPagingParameters(params, 'name')
        coll = params['type']

        events.trigger('mongo_search.allowed_collections', info=allowed)

        if coll not in allowed:
            raise RestException('Invalid resource type: %s' % coll)

        try:
            query = bson.json_util.loads(params['q'])
        except ValueError:
            raise RestException('The query parameter must be a JSON object.')

        model = ModelImporter().model(coll)
        if hasattr(model, 'filterResultsByPermission'):
            cursor = model.find(
                query, fields=allowed[coll] + ['public', 'access'])
            return list(model.filterResultsByPermission(
                cursor, user=self.getCurrentUser(), level=AccessType.READ,
                limit=limit, offset=offset, removeKeys=('public', 'access')))
        else:
            return list(model.find(query, fields=allowed[coll], limit=limit,
                                   offset=offset))
예제 #4
0
파일: __init__.py 프로젝트: dsa-code/girder
    def points(self, params):
        self.requireParams(('q',), params)
        limit, offset, sort = self.getPagingParameters(params, 'name')
        latitude = params.get('latitude', 'meta.latitude')
        longitude = params.get('longitude', 'meta.longitude')

        spec = {
            'type': 'point',
            'latitude': latitude,
            'longitude': longitude,
            'keys': ['meta', 'name', 'description', '_id'],
            'flatten': ['meta']
        }

        try:
            query = bson.json_util.loads(params['q'])
        except ValueError:  # pragma: no cover
            raise RestException('The query parameter must be a JSON object.')

        events.trigger('geojson.points', info={
            'spec': spec,
            'query': query
        })

        # make sure the lat/lon are whitelisted keys to prevent private
        # data leaking
        if spec['latitude'].split('.')[0] not in spec['keys'] or \
                spec['longitude'].split('.')[0] not in spec['keys']:
            raise RestException('Invalid latitude/longitude key.', code=402)

        coll = features.FeatureCollection(points=spec)

        item = ModelImporter().model('item')
        cursor = item.find(
            query,
            limit=0
        )

        cursor = item.filterResultsByPermission(
            cursor,
            user=self.getCurrentUser(),
            level=AccessType.READ,
            limit=limit,
            offset=offset
        )

        try:
            obj = coll(points=cursor)
        except features.GeoJSONException:
            raise RestException(
                'Could not assemble a geoJSON object from spec.',
                code=401
            )

        return obj
예제 #5
0
파일: rest.py 프로젝트: girder/pvcinema
    def makeInfo(self, params):
        """
        Dynamically generate a cinema info file from girder data marked as
        cinema-viewable.
        """

        folderModel = ModelImporter().model('folder')
        folders = folderModel.find({'meta.pvcinema': 1})
        ret = [{
            'title': f['name'],
            'description': f['description'],
            'path': f['meta']['webpath']
        } for f in folders]
        return ret
예제 #6
0
import collections
import datetime
import json
import pymongo
import sys
import traceback
import types

from . import docs
from girder import events, logger
from girder.constants import SettingKey, TerminalColor
from girder.models.model_base import AccessException, ValidationException
from girder.utility.model_importer import ModelImporter
from girder.utility import config

_importer = ModelImporter()


def _cacheAuthUser(fun):
    """
    This decorator for getCurrentUser ensures that the authentication procedure
    is only performed once per request, and is cached on the request for
    subsequent calls to getCurrentUser().
    """
    def inner(self, *args, **kwargs):
        if hasattr(cherrypy.request, 'girderUser'):
            return cherrypy.request.girderUser

        user = fun(self, *args, **kwargs)
        if type(user) is tuple:
            setattr(cherrypy.request, 'girderUser', user[0])