Пример #1
0
    def lookup_attendee_from_barcode(self, barcode_value, full=False):
        """
        Returns a single attendee using the barcode value from their badge.

        Takes the (possibly encrypted) barcode value as the first parameter.

        Optionally, "full" may be passed as the second parameter to return the
        complete attendee record, including departments, shifts, and food
        restrictions.
        """
        badge_num = -1
        try:
            result = get_badge_num_from_barcode(barcode_value)
            badge_num = result['badge_num']
        except Exception as e:
            raise HTTPError(500, "Couldn't look up barcode value: " + str(e))

        # Note: A decrypted barcode can yield a valid badge num,
        # but that badge num may not be assigned to an attendee.
        with Session() as session:
            query = session.query(Attendee).filter_by(badge_num=badge_num)
            fields, query = _attendee_fields_and_query(full, query)
            attendee = query.first()
            if attendee:
                return attendee.to_dict(fields)
            else:
                raise HTTPError(
                    404, 'Valid barcode, but no attendee found with Badge #{}'.
                    format(badge_num))
Пример #2
0
    def generate_invites(self, id):
        req = cherrypy.request
        orm_session = req.orm_session
        data = req.json

        try:
            number = data['number']
            assert number >= 0
        except (TypeError, KeyError, AssertionError) as e:
            # Type- or KeyError if data is None or has no 'number'
            # AssertionError if number of invites is negative
            logger.exception()
            raise HTTPError(400, "Malformed request body") from e

        event = api.find_event_by_id(orm_session, id)
        if event is None:
            raise HTTPError(404)

        for _ in range(number):
            code = uuid4().hex
            invite = Invite(code=code, event=event)
            orm_session.add(invite)
        try:
            orm_session.commit()
        except Exception as e:
            # If here, then smth bad happened during
            # saving invites to db. We need to rollback.
            orm_session.rollback()
            logger.exception()
            raise HTTPError(500, "Cannot save generated invites") from e
        return {"ok": True}
Пример #3
0
    def sessionPanel(self, session, *args, **kwargs):
        name = kwargs.get('n')
        show = kwargs.get('show', None)
        x = kwargs.get('x', None)
        y = kwargs.get('y', None)

        if not isinstance(name, str) or name not in ("tools", ):
            raise HTTPError(500, "Panel operation without a valid panel name")

        if show != None:
            if not isinstance(show, str) or show not in ("yes", "no"):
                raise HTTPError(500, "Invalid panel show parameter")
            session['comp.panel.%s.show' % name] = show == "yes"

        if x != None:
            if not isinstance(x, str) or not re.match(r"^\d+$", x):
                raise HTTPError(500, "Invalid panel position parameter")
            session['comp.panel.%s.x' % name] = int(x)

        if y != None:
            if not isinstance(y, str) or not re.match(r"^\d+$", y):
                raise HTTPError(500, "Invalid panel position parameter")
            session['comp.panel.%s.y' % name] = int(y)

        self.gui._saveSession(session)
        return self._state(session)
Пример #4
0
    def save(self):
        """
    Receive changes to a file from the client
    Method : PUT
    (Path : /ide/save)

    Input must be JSON of the following format:
      {
        'file':   '<<Filepath of edited file>>',
        'vers':   '<<File version>>',
        'changes': [{
                     'type':    '<<Type of edit (ins | del)>>',
                     'pos':     '<<Position of edit>>',
                     'content': '<<Content of insert | Number of deletes>>'
                   }]
      }

    Output on the WS will be JSON of the following format:
      {
        'opCode': 'save',
        'data': {
                  'file':    '<<Filepath of edited file>>',
                  'vers':    '<<File version>>',
                  'changes': [{
                               'type':        '<<Type of edit (ins | del)>>',
                               'pos':         '<<Position of edit>>',
                               'content':     '<<Content of insert | Number of deletes>>'
                               'is_from_you': '<<If the user is the author>>'
                             }]
                }
      }
    """
        self._logger.debug("Save by {0} ({1}:{2}) JSON: {3}".format(
            cherrypy.session['username'], request.remote.ip,
            request.remote.port, request.json))

        username = cherrypy.session['username']
        filename = request.json['file']
        version = request.json['vers']
        changes = request.json['changes']
        self._logger.info(
            "Save for file {3} requested by {0} ({1}:{2})".format(
                username, request.remote.ip, request.remote.port, filename))
        if self.is_valid_path(filename):
            if self.is_valid_changes(changes):
                # Adds changes into a pool of task
                self._logger.info("Calling app for bundle {0}".format(version))
                self._app.file_edit(filename, [
                    self._app.Change(
                        c['pos'],
                        c.get('content') or c.get('count'), c['type']
                        == IDEController.CHANGE_ADD_TYPE) for c in changes
                ], username)
                self._logger.info(
                    "Return from app call for bundle {0}".format(version))

            else:
                raise HTTPError(400, "Invalid changes")
        else:
            raise HTTPError(400, "Invalid path")
Пример #5
0
    def _sanitise_input(self, input_args=[], input_kwargs={}, method=None):
        """
        Pull out the necessary input from kwargs (by name) and, failing that,
        pulls out the number required args from args, which assumes the
        arguments are positional.

        _sanitise_input is called automatically if you use the _addMethod/_addDAO
        convenience functions. If you add your method to the methods dictionary
        by hand you should call _sanitise_input explicitly.

        In all but the most basic cases you'll likely want to over-ride this, or
        at least treat its outcome with deep suspicion.

        TODO: Would be nice to loose the method argument and derive it in this method.

        Returns a dictionary of validated, sanitised input data.
        """
        verb = request.method.upper()

        if len(input_args):
            input_args = list(input_args)
        if (len(input_args) + len(input_kwargs)) > len(
                self.methods[verb][method]['args']):
            self.debug('%s to %s expects %s argument(s), got %s' %
                       (verb, method, len(self.methods[verb][method]['args']),
                        (len(input_args) + len(input_kwargs))))
            raise HTTPError(
                400, 'Invalid input: Input arguments failed sanitation.')
        input_data = {}

        # VK, we must read input kwargs/args as string types
        # rather then unicode one. This is important for cx_Oracle
        # driver which will place parameters into binded queries
        # due to mixmatch (string vs unicode) between python and Oracle
        # we must pass string parameters.
        for a in self.methods[verb][method]['args']:
            if a in input_kwargs.keys():
                v = input_kwargs[a]
                if isinstance(v, basestring):
                    input_data[a] = str(v)
                else:
                    input_data[a] = v
                input_kwargs.pop(a)
            else:
                if len(input_args):
                    v = input_args.pop(0)
                    if isinstance(v, basestring):
                        input_data[a] = str(v)
                    else:
                        input_data[a] = v
        if input_kwargs:
            raise HTTPError(
                400, 'Invalid input: Input arguments failed sanitation.')
        self.debug('%s raw data: %s' % (method, {
            'args': input_args,
            'kwargs': input_kwargs
        }))
        self.debug('%s sanitised input_data: %s' % (method, input_data))
        return self._validate_input(input_data, verb, method)
Пример #6
0
def serveFile(contentType, prefix, *args):
    """Return a workflow from the cache"""
    name = path.normpath(path.join(prefix, *args))
    if path.commonprefix([name, prefix]) != prefix:
        raise HTTPError(403)
    if not path.exists(name):
        raise HTTPError(404, "Page not found")
    return serve_file(name, content_type=contentType)
Пример #7
0
 def set_response(self):
     HTTPError.set_response(self)
     cherrypy.response.headers[
         'Cdb-Status-Code'] = self.cdbException.getErrorCode()
     cherrypy.response.headers[
         'Cdb-Status-Message'] = self.cdbException.getErrorMessage()
     cherrypy.response.headers[
         'Cdb-Exception-Type'] = self.cdbException.getExceptionType()
Пример #8
0
    def _classifyHTTPError(self, verb, args, kwargs):
        """
        There are a few cases where input will cause an error which needs
        appropriate classification:
            - request uses a globally unsupported verb (raise 501)
            - request is to a non-existant method (raise 404)
            - request is to a valid method, and uses a valid VERB but the
              VERB isn't supported by the method
        """

        method = args[0]

        he = False
        # Make sure the verb and method are well named
        try:
            check("^[A-Z]+$", verb)
            check("^[a-z][A-Za-z0-9]+$", method)
        except:
            he = HTTPError(400, 'bad VERB or method')

        # Checks whether verb is supported, if not return 501 error
        if verb not in self.methods.keys():
            data = "Unsupported verb: %s" % (verb)
            he = HTTPError(501, data)
        else:
            # We know how to deal with this VERB
            # Do we know the method?
            method_for_verb = method in self.methods[verb].keys()

            if method_for_verb:
                return
            # Is the method supported for a VERB different to the the requests?
            unsupported_verb = False

            other_verbs = self.methods.keys()
            other_verbs.remove(verb)

            for v in other_verbs:
                unsupported_verb = unsupported_verb | (
                    method in self.methods[v].keys())

            # Checks whether method exists but used wrong verb
            if unsupported_verb:
                data = "Unsupported method for %s: %s" % (verb, method)
                he = HTTPError(405, data)

            # The method doesn't exist
            elif not method_for_verb and not he:
                data = "Method not found for the verb %s: %s" % (verb, method)
                he = HTTPError(404, data)

        if he:
            self.debug(he[1])
            self.debug(traceback.format_exc())
            raise he
Пример #9
0
    def default(self, id, attribute=None):
        if cherrypy.request.method == 'POST' and attribute is None:
            ciel.log('Creating job for ID: %s' % id, 'JOB_POOL', logging.INFO)
            # Need to support this for backup masters, so that the job ID is
            # consistent.
            
            # 1. Read task descriptor from request.
            request_body = cherrypy.request.body.read()
            task_descriptor = simplejson.loads(request_body, 
                                               object_hook=json_decode_object_hook)

            # 2. Add to job pool (synchronously).
            job = self.job_pool.create_job_for_task(task_descriptor, job_id=id)

            # 2bis. Send to backup master.
            self.backup_sender.add_job(job.id, request_body)
            
            if self.monitor is not None and self.monitor.is_primary:
                # 2a. Start job. Possibly do this as deferred work.
                self.job_pool.queue_job(job)
            else:
                ciel.log('Registering job, but not starting it: %s' % job.id, 'JOB_POOL', logging.INFO)
                #self.job_pool.task_pool.add_task(job.root_task, False)
            
            # 3. Return descriptor for newly-created job.
            
            ciel.log('Done handling job POST', 'JOB_POOL', logging.INFO)
            return simplejson.dumps(job.as_descriptor())            
        
        try:
            job = self.job_pool.get_job_by_id(id)
        except KeyError:
            raise HTTPError(404)
        
        if attribute is None:
            # Return the job descriptor as JSON.
            return simplejson.dumps(job.as_descriptor(), cls=SWReferenceJSONEncoder, indent=4)
        elif attribute == 'completion':
            # Block until the job is completed.
            try:
                timeout = simplejson.loads(cherrypy.request.body.read(), object_hook=json_decode_object_hook)['timeout']
            except:
                timeout = None
            done = self.job_pool.wait_for_completion(job, timeout)            
            if timeout is None:
                return simplejson.dumps(job.as_descriptor(), cls=SWReferenceJSONEncoder) 
            else:
                return simplejson.dumps(done)
        elif attribute == 'resume':
            self.job_pool.queue_job(job)
        elif attribute == 'poke':
            job.schedule()
        else:
            # Invalid attribute.
            raise HTTPError(404)
Пример #10
0
    def _get_earliest_latest(item_type, item_list, time_basis):
        accepted_item_types = list(
            set(
                list(QueryBase.object_type_mappings.keys()) +
                list(QueryBase.object_type_mappings.values())))
        accepted_time_basis_types = [
            'submitted',
            'modified',
            'created',
            'submit',
            'modified',
            'create',
            'submit_time',
            'modified_time',
            'create_time',
            'submitted_date',
            'modified_date',
            'created_date',
        ]
        item_type = QueryBase.object_type_mappings.get(item_type)
        time_basis = time_basis.lower()
        if item_type not in accepted_item_types or time_basis not in accepted_time_basis_types:
            raise HTTPError('400 Invalid Query')

        short_time_basis = time_basis[:5]

        time_basis = {
            'submi': lambda x: 'submitted',
            'modif': lambda x: 'modified',
            'creat': lambda x: 'created'
        }[short_time_basis](short_time_basis)
        search_field = getattr(TransSIP, '{0}'.format(item_type))
        if time_basis == 'submitted':
            query = TransSIP().select(
                fn.Min(TransSIP.updated).alias('earliest'),
                fn.Max(TransSIP.updated).alias('latest'),
            )
        if time_basis in ['modified', 'created']:
            time_basis_field = getattr(Files, '{0}time'.format(time_basis[:1]))
            query = Files().select(
                fn.Min(time_basis_field).alias('earliest'),
                fn.Max(time_basis_field).alias('latest'),
            ).join(TransSIP, on=(TransSIP.id == Files.transaction))

        query = query.where(search_field << item_list)
        row = query.get()
        if row.earliest is None or row.latest is None:
            message = ''
            raise HTTPError('404 Not Found', message)

        return {
            'earliest': row.earliest.strftime('%Y-%m-%d %H:%M:%S'),
            'latest': row.latest.strftime('%Y-%m-%d %H:%M:%S')
        }
Пример #11
0
    def jobinfo(self, id_):
        """CherryPy handler returning the job information for the given job."""
        try:
            info = self.store.get_job_info(int(id_))
        except ValueError:
            raise HTTPError(400, 'Job ID not a number')
        if info is None:
            raise HTTPError(404, 'Job not found')

        info["id"] = id_
        return self.json_encoder.encode(info)
Пример #12
0
    def GET(start_date=None, end_date=None):
        """Return a transaction summary for a given date range."""
        if start_date is None:
            raise HTTPError('400 Invalid Start Date',
                            'No starting date specified')

        if end_date is None:
            raise HTTPError('400 Invalid End Date', 'No ending date specified')

        return TransactionReporting.get_transaction_date_range_details(
            start_date, end_date)
Пример #13
0
  def start(self, session, date = None, page = None, **kwargs):
    if date != None:
      if not isinstance(date, str) or not re.match(r"^[\d.]*$", date):
        raise HTTPError(500, "Incorrect date parameter")
      session['evd.date'] = date

    if page != None:
      if not isinstance(page, str) or not re.match(r"^\d*$", page):
        raise HTTPError(500, "Incorrect page parameter")
      if page == '0':
        page = '1'
      session['evd.page'] = page
Пример #14
0
    def read(self, spec, fields):
        """
        Send request to proxy server to read data for given query.
        Yield list of found documents or None.
        """
        self.read_access += 1
        dbname = spec.get('dtype', 'fwjr')
        result = {'input': {'spec': spec, 'fields': fields},
                  'results': [], 'storage': self.sts[dbname].stype, 'status': 'ok'}
        # convert given spec into query suitable for sts/lts
        if  isinstance(spec, dict):
            try:
                trange = spec.pop('timerange')
            except KeyError:
                print(tstamp("WMArchiveManager::read"), "timerange is not provided in spec", spec)
                raise HTTPError(400, 'WMArhchive no timerange, spec=%s' % spec)

            if  trange_check(trange):
                print(tstamp("WMArchiveManager::read"), "bad timerange: %s" % trange)
                raise HTTPError(400, 'WMArhchive unable to parse timerange, spec=%s' % spec)

            # based on given time range define which manager
            # we'll use for data look-up
            mgr = self.sts[dbname]
            if  use_lts(trange, self.tls_thr):
                spec['timerange'] = trange # put back timerange for HDFS hdir constraint
                mgr = self.lts

            # convert spec into WMArchive one
            spec, fields = self.qmap(mgr, spec, fields)
        else:
            # if spec is a list, it means user look-up docs by wmaids
            # they represents results of LTS data look-up
            mgr = self.sts[dbname]
        status = 'ok'
        reason = None
        try:
            # request data from back-end
            data = mgr.read(spec, fields)
        except ReadError as exp:
            print(tstamp("WMArchiveManager::read"), "exception: %s" % str(exp))
            traceback.print_exc()
            raise HTTPError(400, 'WMArhchive ReadError, exception %s' % str(exp))
        except Exception as exp:
            print(tstamp("WMArchiveManager::read"), "exception: %s" % str(exp))
            traceback.print_exc()
            raise HTTPError(400, 'WMArhchive exception %s' % str(exp))
        result['data'] = data
        result['status'] = status
        if  reason:
            result['reason'] = reason
        return result
Пример #15
0
    def _set(self, session, submenu=None, view=None, **kwargs):

        if submenu != None:
            if not isinstance(submenu, str) \
               or submenu not in ("none", "workspace", "view"):
                raise HTTPError(500, "Incorrect submenu parameter")
            session['comp.submenu'] = submenu

        if view != None:
            if not isinstance(view, str) \
               or view.lower() not in (x.label for x in self.views):
                raise HTTPError(500, "Incorrect view parameter")
            session[self.tag + '.view'] = view.lower()
Пример #16
0
    def default(self, job_id, ref_id):
        
        try:
            job = self.job_pool.get_job_by_id(job_id)
        except KeyError:
            raise HTTPError(404)
        
        try:
            ref = job.task_graph.get_reference_info(ref_id).ref
        except KeyError:
            raise HTTPError(404)

        return simplejson.dumps(ref, cls=SWReferenceJSONEncoder)
    def GET(user_id=None):
        """Return a set of proposals for a given user."""
        if user_id is not None:
            user_ids = re.findall('[0-9]+', user_id)
            if user_ids:
                user_id = int(user_ids.pop(0))
            else:
                raise HTTPError('400 Invalid User ID',
                                '"{0}" is not a valid user ID'.format(user_id))
        else:
            raise HTTPError('400 Invalid User ID', 'No user ID specified')

        return ProposalUserSearch.get_proposals_for_user(user_id)
Пример #18
0
 def login(self, **kwargs):
     req = cherrypy.request
     orm_session = req.orm_session
     params = req.json
     if 'username' in params and 'password' in params:
         user = api.find_user_by_name(orm_session, params['username'])
         if user and user.validate_password(params['password']):
             cherrypy.session['user_id'] = user.id
             return to_collection(user,
                                  excludes=("password", "salt"),
                                  sort_keys=True)
         raise HTTPError(401)
     raise HTTPError(400)
Пример #19
0
 def show(self, id, **kwargs):
     try:
         id = int(id)
         req = cherrypy.request
         orm_session = req.orm_session
         event = find_event_by_id(cherrypy.request.orm_session, id)
         if event:
             tmpl = get_template('event.html')
             return tmpl.render(event=event,
                                host_gdg=find_host_gdg_by_event(orm_session,
                                                                event))
         raise HTTPError(404)
     except ValueError:
         raise HTTPError(400, 'Invalid URL')
Пример #20
0
 def submit(self, key_yaml=None, sub_yaml=None):
     try:
         key = yaml.load(key_yaml)
         submission = yaml.load(sub_yaml)
     except:
         raise HTTPError(400)
     with self.status_lock:
         if not key in self.tasks:
             raise HTTPError(404)
         task = self.tasks[key]
         if not task.finished:
             self.handle(key, task, submission)
             task.finish()
     return "OK"
Пример #21
0
 def _http_get(event_uuid):
     """Internal get event by UUID and return peewee obj."""
     cherrypy.response.headers['Content-Type'] = 'application/json'
     orm.EventMatch.database_connect()
     try:
         event_obj = orm.EventMatch.get(
             orm.EventMatch.uuid == UUID('{{{}}}'.format(event_uuid)))
     except DoesNotExist:
         orm.EventMatch.database_close()
         raise HTTPError(403, 'Forbidden')
     orm.EventMatch.database_close()
     if event_obj.user != get_remote_user() or event_obj.deleted:
         raise HTTPError(403, 'Forbidden')
     return event_obj
Пример #22
0
 def submit(self, key_yaml=None, sub_yaml=None):
     try:
         key = yaml.load(key_yaml, Loader=Loader)
         submission = yaml.load(sub_yaml, Loader=Loader)
     except:
         raise HTTPError(400)
     with self.status_lock:
         if not key in self.tasks:
             raise HTTPError(404)
         task = self.tasks[key]
         if not task.finished:
             task.store_results(submission)
             task.finish()
     return "OK"
Пример #23
0
def login(request, **kwargs):
    global tokmgr
    if request.method == 'POST':
        auth_header = request.headers.get('authorization')
        db = get_database(None)
        username = kwargs.get('user')
        if username:
            try:
                user_info = db.get_user_by_name(super_context, username)
            except NotFound:
                logger.error('user {0} is not found'.format(username))
                raise HTTPError(401, 'user {0} is not found'.format(username))
        else:
            logger.error('no username')
            raise HTTPError(400, 'please input the username')

        logger.info('user {0} is trying to log in'.format(username))
        if auth_header:
            try:
                check_token(auth_header, user_info)
            except HTTPError:
                raise
        else:
            password = kwargs.get('password')
            valid = auth_basic.verify_user(user_info, username, password)
            if valid:
                payload = tokmgr.build_payload(username)
                tok = token.genarate_token(payload, user_info.key)
                role = user_info.role
                rolename = ''
                if role:
                    rolename = role.name
                msg = 'user {0} is logged in from {1}'.format(username, request.headers.get('Remote-Addr'))
                logger.info(msg)
                oplogger.log_event(super_context, msg)
                return {'token': tok,
                        'role':rolename,
                        'user_id': user_info.id
                        }
            raise HTTPError(401, 'user {0} password is not right'.format(username))


    elif cherrypy.request.method == 'OPTIONS':
        cherrypy.response.headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE'
        cherrypy.response.headers['Access-Control-Allow-Headers'] = 'content-type'
        cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
        return
    else:
        raise cherrypy.HTTPRedirect('/')
Пример #24
0
 def fail(self, key_yaml=None):
     try:
         key = yaml.load(key_yaml)
     except:
         raise HTTPError(400)
     with self.status_lock:
         if not key in self.tasks:
             raise HTTPError(404)
         task = self.tasks[key]
         if not task.finished:
             task.fail()
         else:
             # Someone else already finished
             raise HTTPError(410)
     return "OK"
Пример #25
0
    def create(self, first_name, last_name, email, params):
        """
        Create an attendee with at least a first name, last name, and email. Prevents duplicate attendees.

        `params` should be a dictionary with column name: value to set other values, or a falsey value.
        Use labels for Choice and MultiChoice columns, and a string like "no" or "yes" for Boolean columns.
        Date and DateTime columns should be parsed correctly as long as they follow a standard format.

        Example `params` dictionary for setting extra parameters:
        <pre>{"placeholder": "yes", "legal_name": "First Last", "cellphone": "5555555555"}</pre>
        """
        with Session() as session:
            attendee_query = session.query(Attendee).filter(
                Attendee.first_name.ilike("first_name"),
                Attendee.last_name.ilike("last_name"),
                Attendee.email.ilike("*****@*****.**"))

            if attendee_query.first():
                raise HTTPError(
                    400,
                    'An attendee with this name and email address already exists'
                )

            attendee = Attendee(first_name=first_name,
                                last_name=last_name,
                                email=email)

            if params:
                for key, val in params.items():
                    params[key] = _parse_if_datetime(key, val)
                    params[key] = _parse_if_boolean(key, val)

            attendee.apply(params, restricted=False)
            session.add(attendee)

            message = check(attendee)
            if message:
                session.rollback()
                raise HTTPError(400, message)

            # Duplicates functionality on the admin form that makes placeholder badges need not pay
            # Staff (not volunteers) also almost never need to pay by default
            if (attendee.placeholder
                    or attendee.staffing and c.VOLUNTEER_RIBBON
                    not in attendee.ribbon_ints) and 'paid' not in params:
                attendee.paid = c.NEED_NOT_PAY

            return attendee.id
Пример #26
0
    def default(self, *args, **kwargs):
        fname = kwargs.get("fname", None)
        zipcode = kwargs.get("zipcode", None)
        phone = kwargs.get("phone", None)
        email = kwargs.get("email", None)
        category = kwargs.get("category", [])
        language = kwargs.get("language", [])
        additional_info = kwargs.get("additional_info", None)

        if controller.lib.db.check_zip_code(zipcode) is None:
            raise HTTPError(400, "Uknown zip code")

        if type(language) in (tuple, list):
            if language.__len__() == 0:
                language = controller.get_lang()
            else:
                language = "|".join(language)

        if type(category) in (tuple, list):
            category = "|".join(category)

        self.add_seeker_request(additional_info, category, email, fname,
                                language, phone, zipcode)
        self.notify_providers(email, language, zipcode)

        return json.dumps({"status": "OK"})
Пример #27
0
    def _user_host_crontabs(self, host=None, user=None):
        """Displays crontab listing, either by host or user."""

        jobs = {}
        raw = {}
        info = {'jobs': jobs, 'raw': raw}

        if host is None and user is not None:
            by_user = False
            info['user'] = user
            info['host'] = None
        elif host is not None and user is None:
            by_user = True
            info['host'] = host
            info['user'] = None
        else:
            raise HTTPError(500, 'Need one of host or user to be specified')

        for job in self.store.get_jobs(host, user, include_deleted=True):
            if by_user:
                key = job['user']
            else:
                key = job['host']

            if key in jobs:
                jobs[key].append(job)
            else:
                jobs[key] = [job]
                raw[key] = self.store.get_raw_crontab(job['host'], job['user'])

        return self._write_template('crontabs.html', info)
Пример #28
0
 def _validate_input(self, input_data, verb, method):
     """
     Apply some checks to the input data. Run all the validation funstions
     for the given method. Validation functions should raise exceptions if
     the data doesn't pass the validation (assert's are your friend!). These
     exceptions are caught here and converted into 400 HTTPErrors.
     """
     validators = self.methods[verb][method].get('validation', [])
     if len(validators) == 0:
         # Do nothing
         return input_data
     result = {}
     # Run the validation functions, these should raise exceptions. If the
     # exception is an HTTPError re-raise it, else raise a 400 HTTPError (bad input).
     for fnc in validators:
         try:
             filteredInput = fnc(input_data)
         except HTTPError as he:
             self.debug(he)
             raise he
         except Exception as e:
             self.debug(e)
             raise HTTPError(
                 400, 'Invalid input: Input data failed validation.')
         result.update(filteredInput)
     return result
Пример #29
0
 def wrapper(*input_args, **input_kwargs):
     if secured:
         # set up security
         security = cherrypy.tools.secmodv2
         # security_params should be a dict like:
         #{'role':[], 'group':[], 'site':[], 'authzfunc':None}
         security.callable(role=security_params.get('role', []),
                           group=security_params.get('group', []),
                           site=security_params.get('site', []),
                           authzfunc=security_params.get(
                               'authzfunc', None))
     if len(args) != 0:
         # store the method name
         method = methodKey
         input_data = self._sanitise_input(input_args, input_kwargs,
                                           method)
         # store the function
         func = function
         # execute the requested input, now a list of keywords
         return func(**input_data)
     else:
         # If the method isn't meant to have arguments the wrapper isn't needed
         # so we need to raise a 400 error
         if (len(input_args) + len(input_kwargs)):
             raise HTTPError(
                 400,
                 'Invalid input: Arguments added where none allowed')
         return function()
Пример #30
0
    def handler(self, verb, args, kwargs):
        """
        Call the appropriate method from self.methods for a given VERB. args are
        URI path elements, the first (arg[0]) is the method name, other elements
        (arg[1:]) are positional arguments to the method. kwargs are query string
        parameters (e.g. method?thing1=abc&thing2=def). All args and kwargs are
        passed to the model method, this is so configuration for a given method
        can be identified.
        """

        verb = verb.upper()
        if not args:
            args = []
        if not kwargs:
            kwargs = {}
        self._classifyHTTPError(verb, args, kwargs)
        try:
            method = args[0]
            methodCall = self.methods[verb][method]['call']
            # if there is nothing to be processed about the parameter
            # it will just return original parameters
            params, kwargs = self._processParams(args[1:], kwargs)
            if not getattr(methodCall, 'restexposed', False):
                msg = 'Using an implicitly exposed method, '
                msg += 'please use _addDAO, _addMethod or @restexposed around %s' % method
                self.warning(msg)
            data = methodCall(*params, **kwargs)
        # If a type error is raised the data from the client is bad - 400 error
        except TypeError, e:
            error = e.__str__()
            self.debug(error)
            self.debug(traceback.format_exc())
            raise HTTPError(400, error)