예제 #1
0
 def POST(self):
     try:
         data = web.data()
         UpmpHandler.notify(data)
         web.header('Content-Type', 'text/html')
         raise web.OK('success')
     except InvalidMerchantException:
         raise web.BadRequest('Invalid merchant')
     except InvalidNotifyException:
         raise web.BadRequest('Notify fail')
     except InvalidContentTypeException:
         raise web.BadRequest('Invalid content type')
     except Exception, e:
         print e
         raise web.OK('success')
예제 #2
0
 def POST(self):
     data = web.input()
     if "cdr" in data:
         self.process_cdr(data.cdr)
         headers = {'Content-type': 'text/plain'}
         raise web.OK(None, headers)
     raise web.BadRequest()
예제 #3
0
    def POST(self):
        try:
            tid_value = web.input()['tid']
        except KeyError:
            return web.BadRequest()

        try:
            team_id = cfg['TEAM_ID_DICT'][tid_value.upper()]
        except KeyError:
            return web.Unauthorized()

        if len(web.data()) == 0:
            return web.BadRequest()

        data = simplejson.loads(web.data())
        # json validation
        good, errors = IssueValidator().validate(data)
        if not good:
            return errors

        r = requests.post(''.join(['http://', cfg['REMOTE_HOST'], '/pp']), data=simplejson.dumps({'tid': str(team_id), 'iid': data['ID']}))
        if r.status_code != 200:
            print 'Call remote server failed...'
            print r.text

        api = WxApi(cfg['CORP_ID'], cfg['SECRET'])
        api.send_text(self.build_msg(data), team_id, 0, '@all')

        return web.OK('ok')
예제 #4
0
 def POST(self):
     args = web.input()
     # convert the signature into byte string
     file_name = args["file"].encode("ascii")
     provided_string = args["signature"].decode("hex")
     if self.insecure_compare(file_name, provided_string) is True:
         raise web.OK()
     else:
         raise web.internalerror("bad mac")
예제 #5
0
def route_unrouted(handler, app):  # TODO XXX ???
    """Handle channels."""
    for channel in web.tx.posts.get_channels():
        if channel["resource"]["url"][0] == f"/{web.tx.request.uri.path}":
            posts = web.tx.posts.get_posts_by_channel(
                channel["resource"]["uid"][0])
            web.header("Content-Type", "text/html")
            raise web.OK(app.view.channel(channel, posts))
    yield
예제 #6
0
 def execute(self):
     try:
         dict = {"data": web.data(), "headers": {"Content-Type": web.ctx.env.get('CONTENT_TYPE')}, "type": self.type}
         AirwatchHandler(dict).handle()
         monitorutils.count_task("notificationrestservice", True)
         return web.OK()
     except AuthenticationFailureException, e:
         logger.error('Notification REST Service - %s' % e)
         monitorutils.count_task("notificationrestservice", False)
         raise web.Unauthorized()
예제 #7
0
    def POST(self):
        """
        Publishes the HostController address to be used by the sniffer.
        The payload must just contain json object like:
        {"hc_address":"XXX.XXX.XXX.XXX"}
        :return: 
        """

        # Parse input
        data = None
        address = None
        port = None

        try:
            raw = web.data()
            data = json.loads(raw)
        except:
            raise web.badrequest("Invalid payload. Please provide a valid JSON encoded payload")

        if 'address' not in data:
            raise web.badrequest("Missing address parameter")
        else:
            address = data['address']

        if 'port' not in data:
            raise web.badrequest("Missing port parameter")

        try:
            p = data.get('port')
            port = int(p)
            if port < 1 or port > 65535:
                raise ValueError()
        except:
            raise web.badrequest('Invalid port specified.')

        """
        # Try to contact the HostController directly from here. Note thta HostController must be already running
        # for this to work. We just want to establish a successful connection with the HostController.
        conn = None
        try:
            conn = socket.create_connection(address=(address, port))

            # Upon successful connection we save data into the manager.
            web.mgr.set_hc_address(address, port)
            log.info("New HC Address published: %s:%d" % (address, port))
            return web.OK()
        except:
            raise web.badrequest("Connection attempt against HostController failed. Please check that the HostController is running and network configuration is OK.")
        finally:
            if conn is not None:
                conn.close()
        """
        web.mgr.set_hc_address(address, port)
        return web.OK()
예제 #8
0
 def POST(self):
     data = web.data()
     data_json = json.loads(data)
     result = dna_expert.isMutant(data_json['dna'])
     r.set(data, int(0 if result == None else result))
     if result == False:
         raise web.Forbidden()
     elif result:
         return web.OK()
     else:
         return web.HTTPError('400 Bad Request')
예제 #9
0
def internalerror():
    """ HTTP 500 handler"""
    # err_msg = wrap_error(ERROR_SERVER_ERROR,'Server Error 500', HTTP500_DELAY)
    log_normal(logger, {
        'action': 'server-internal-error',
        'error': format_exc()
    }, LOG_ERROR)

    # return web.internalerror(err_msg)
    result = wrap_result(DEFAULT_JSONRPC_ID, OVERALL_WORKING, [])
    web.header('Retry-After', '%d' % RETRY_AFTER)
    web.header('X-Processing-Retry', '%d' % int(PROCESSING_RETRY))
    return web.OK(result)
예제 #10
0
 def POST(self):
     try:
         data = web.data()
         json_data = json.loads(data) if data else {}
         res = UpmpHandler.charge(json_data)
         web.header('Content-Type', 'application/json')
         raise web.OK(json.dumps(res))
     except InvalidMerchantException:
         raise web.BadRequest('Invalid merchant')
     except ChargeFailException:
         raise web.BadRequest('Charge fail')
     except InvalidContentTypeException:
         raise web.BadRequest('Invalid content type')
예제 #11
0
    def generate_http_response(self,
                               status_code,
                               data=None,
                               exc_cls=None,
                               exc_msg=None):

        if status_code == HTTP_STATUS_CODE.OK:
            if data:
                raise web.OK(data=json.dumps(data), headers={})
            else:
                raise web.OK()
        elif status_code == HTTP_STATUS_CODE.Created:
            raise web.Created()
        elif status_code == HTTP_STATUS_CODE.Accepted:
            raise web.Accepted()
        elif status_code == HTTP_STATUS_CODE.BadRequest:
            raise web.BadRequest(
                message=self.generate_message(exc_cls, exc_msg))
        elif status_code == HTTP_STATUS_CODE.Unauthorized:
            raise web.Unauthorized(
                message=self.generate_message(exc_cls, exc_msg))
        elif status_code == HTTP_STATUS_CODE.Forbidden:
            raise web.Forbidden(
                message=self.generate_message(exc_cls, exc_msg))
        elif status_code == HTTP_STATUS_CODE.NotFound:
            raise web.NotFound(message=self.generate_message(exc_cls, exc_msg))
        elif status_code == HTTP_STATUS_CODE.Conflict:
            raise web.Conflict(message=self.generate_message(exc_cls, exc_msg))
        elif status_code == HTTP_STATUS_CODE.InternalError:
            raise web.InternalError(
                message=self.generate_message(exc_cls, exc_msg))
        else:
            if data:
                raise web.HTTPError(status_code, data=json.dumps(data))
            else:
                raise web.HTTPError(status_code)
예제 #12
0
    def POST(self):
        '''handles post requests to the server'''
        print('starting server shutdown process')

        # shutsdown the LEDs
        # display_controller is added via a add_processor
        # pylint: disable=no-member
        if web.ctx.web_server_only_mode:
            print('starting server shutdown process')
        else:
            web.ctx.display_controller.stop()

        shutdown_script()
        web.header('Content-Type', 'text/plain')
        return web.OK()
예제 #13
0
    def POST(self):
        try:
            tid_value = web.input()['tid']
        except KeyError:
            return web.BadRequest()

        try:
            team_id = cfg['TEAM_ID_DICT'][tid_value.upper()]
        except KeyError:
            return web.Unauthorized()

        if len(web.data()) == 0:
            return web.BadRequest()

        api = WxApi(cfg['CORP_ID'], cfg['SECRET'])
        api.send_text(web.data(), team_id, 0, '@all')

        return web.OK('ok')
예제 #14
0
 def POST(self):
     """Handles POST requests."""
     data = web.input()
     if ('from_name' not in data or 'service_type' not in data or
             'destination' not in data):
         raise web.BadRequest()
     # Process the CDR data.
     cost_in_credits = billing.get_sms_cost(
         data.service_type, destination_number=data.destination)
     try:
         old_balance = subscriber.get_account_balance(data.from_name)
         subscriber.subtract_credit(data.from_name, str(cost_in_credits))
     except SubscriberNotFound:
         # The subscriber does not exist yet but has sent an SMS
         if data.service_type == 'free_sms':
             # But that is OK for a free service like provisioning
             old_balance = 0
         else:
             raise
     reason = "SMS sent to %s (%s)" % (data.destination, data.service_type)
     events.create_sms_event(
         data.from_name, old_balance, cost_in_credits, reason,
         data.destination, from_imsi=data.from_name,
         from_number=data.from_number)
     # If this was an in-network event, find the cost for the recipient.  We
     # can lookup the recipient by data.destination (the "to number").
     if 'local' in data.service_type:
         recipient_imsi = subscriber.get_imsi_from_number(data.destination)
         old_balance = subscriber.get_account_balance(recipient_imsi)
         cost_in_credits = billing.get_sms_cost(
             'local_recv_sms', destination_number=data.destination)
         subscriber.subtract_credit(recipient_imsi, str(cost_in_credits))
         reason = "SMS received from %s (local_recv_sms)" % data.from_name
         events.create_sms_event(
             recipient_imsi, old_balance, cost_in_credits, reason,
             data.destination, from_imsi=data.from_name,
             from_number=data.from_number)
     # Return 200 OK.
     headers = {
         'Content-type': 'text/plain'
     }
     raise web.OK(None, headers)
예제 #15
0
 def GET(self):
     merchant_data = UpmpHandler.query_merchant_info(data_path)
     web.header('Content-Type', 'application/json')
     raise web.OK(json.dumps(merchant_data))
예제 #16
0
 def GET(self):
     return web.OK()
예제 #17
0
    def callback(self, auth_storage):
        req = prepare_request(self._settings)
        input_data = web.input()

        if "alreadyRedirected" not in input_data:
            raise web.OK(AvoidCreatingSession("""
                <!DOCTYPE html>
                <html>
                    <head>
                        <meta charset="utf-8" />
                    </head>
                    <body onload="document.forms[0].submit()">
                        <noscript>
                            <p>
                                <strong>Note:</strong> Since your browser does not support JavaScript,
                                you must press the Continue button once to proceed.
                            </p>
                        </noscript>
                        <form method="post">
                            <div>
                                <input type="hidden" name="RelayState" value="{RelayState}"/>
                                <input type="hidden" name="SAMLResponse" value="{SAMLResponse}"/>
                                <input type="hidden" name="alreadyRedirected" value="yes"/>
                            </div>
                            <noscript>
                                <div>
                                    <input type="submit" value="Continue"/>
                                </div>
                            </noscript>
                        </form>
                    </body>
                </html>
            """.format(RelayState=html.escape(input_data["RelayState"]), SAMLResponse=html.escape(input_data["SAMLResponse"]))))

        auth = OneLogin_Saml2_Auth(req, self._settings)
        auth.process_response()
        errors = auth.get_errors()

        # Try and check if IdP is using several signature certificates
        # This is a limitation of python3-saml
        for cert in self._settings["idp"].get("additionalX509certs", []):
            if auth.get_last_error_reason() == "Signature validation failed. SAML Response rejected":
                # Change used IdP certificate
                logging.getLogger('inginious.webapp.plugin.auth.saml').debug("Trying another certificate...")
                new_settings = copy.deepcopy(self._settings)
                new_settings["idp"]["x509cert"] = cert
                # Retry processing response
                auth = OneLogin_Saml2_Auth(req, new_settings)
                auth.process_response()
                errors = auth.get_errors()

        if len(errors) == 0 and "attributes" in self._settings:
            attrs = auth.get_attributes()
            username = attrs[self._settings["attributes"]["uid"]][0]
            realname = attrs[self._settings["attributes"]["cn"]][0]
            email = attrs[self._settings["attributes"]["email"]][0]

            additional = {}
            for field, urn in self._settings.get("additional", {}).items():
                additional[field] = attrs[urn][0] if urn in attrs else ""

            # Redirect to desired url
            self_url = OneLogin_Saml2_Utils.get_self_url(req)
            if 'RelayState' in input_data and self_url != input_data['RelayState']:
                auth_storage.update(json.loads(input_data['RelayState']))
                # Initialize session in user manager and update cache
                return str(username), realname, email, additional
        else:
            logging.getLogger('inginious.webapp.plugin.auth.saml').error("Errors while processing response : " +
                                                                         ", ".join(errors))
            return None