Esempio n. 1
0
def authorize_sign_in(state, code, flow):
    """Complete the authorization and return the response."""
    if state != tx.user.session["state"]:
        raise web.BadRequest("bad state")
    if flow == "profile":
        endpoint = tx.user.session["authorization_endpoint"]
    elif flow == "token":
        endpoint = tx.user.session["token_endpoint"]
    else:
        raise web.BadRequest("only `profile` and `token` flows supported")
    response = web.post(
        endpoint,
        headers={
            "Accept": "application/json"
        },
        data={
            "grant_type": "authorization_code",
            "code": code,
            "client_id": tx.user.session["client_id"],
            "redirect_uri": tx.user.session["redirect_uri"],
            "code_verifier": tx.user.session["code_verifier"],
        },
    ).json
    create_guest(tx.db, response)
    return response
Esempio n. 2
0
    def GET(self, req_path):
        req_path = cgi.escape(req_path)

        inputs = web.input()
        action = inputs.get("action", "read")
        if action not in consts.g_actions:
            raise web.BadRequest()

        if action == "read":
            return page.wp_read(config_agent=config_agent,
                                req_path=req_path,
                                tpl_render=tpl_render)
        elif action == "update":
            return page.wp_update(config_agent=config_agent,
                                  req_path=req_path,
                                  tpl_render=tpl_render)
        elif action == "rename":
            return page.wp_rename(config_agent=config_agent,
                                  req_path=req_path,
                                  tpl_render=tpl_render)
        elif action == "delete":
            return page.wp_de1lete(config_agent=config_agent,
                                   req_path=req_path,
                                   tpl_render=tpl_render)
        elif action == "source":
            return page.wp_source(config_agent=config_agent,
                                  req_path=req_path,
                                  tpl_render=tpl_render)
        else:
            raise web.BadRequest()
Esempio n. 3
0
    def POST(self, req_path):
        req_path = cgi.escape(req_path)

        inputs = web.input()
        action = inputs.get("action")
        if (not action) or (action not in ("update", "rename")):
            raise web.BadRequest()

        new_content = inputs.get("content")
        new_content = web.utils.safestr(new_content)

        if action == "update":
            if (req_path in consts.g_special_paths) or (
                    req_path
                    in consts.g_redirect_paths) or req_path.endswith("/"):
                raise web.BadRequest()

            return page.wp_update_post(config_agent=config_agent,
                                       req_path=req_path,
                                       new_content=new_content)

        elif action == "rename":
            new_path = inputs.get("new_path")
            if (req_path in consts.g_special_paths) or (
                    req_path in consts.g_redirect_paths) or (not new_path):
                raise web.BadRequest()

            return page.wp_rename_post(config_agent=config_agent,
                                       tpl_render=tpl_render,
                                       req_path=req_path,
                                       new_path=new_path)

        url = os.path.join("/", req_path)
        web.redirect(url)
        return
Esempio n. 4
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')
Esempio n. 5
0
    def POST(self):
        """
        Expects a JSON object that looks something like this:

        {
            "game_secret" : "a shared secret between you and the server per game",
            "ifa"         : "1ad75bdc85527914459b41f44f3af0ff",
            "ifv"         : "f43adc9fc7548eef59b9314ec88078f6",
            "receipt"     : "8f4c538fb296a31b49bd38360ce49f838f4c538fb296a31b49bd38360ce49f838f4c538fb296a31b49bd38360ce49f838f4c538fb296a31b49bd38360ce49f83==",
            "xact_id"     : "06f5d6cbfd02476834906e83816662f8",
            "bid"         : "some game bundle id",
            "bvrs"        : "1.0",
        }

        Passing along extra data with the transaction is encouraged.  Examples include:
        - device_type
        - device_version
        - os_version
        - level
        - playtime at transaction time

        Data passed that interferes with the internal usage of the verification server will be discarded.
        """

        post_body = urllib.unquote(web.data())

        try:
            # In theory I should check the header for compression.  This costs more, but is more foolproof.
            # Honestly, if your games are making so much money that this is a problem, you can afford to spin
            # up a medium instance instead of a micro.

            post_body = zlib.decompress(post_body)
        except zlib.error:
            pass

        try:
            post_body = post_body.decode("utf-8")
            data = json.loads(post_body)
        except ValueError:
            raise web.BadRequest("invalid json")

        for param in invalid_params:
            if param in data:
                raise web.BadRequest("invalid param " + param)

        try:
            return self.record_data(data)
        except InvalidGameError:
            return web.BadRequest("Invalid Game")
Esempio n. 6
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')
Esempio n. 7
0
    def GET(self, request_packer, package):
        if not request_packer or not package: web.BadRequest()
        else:
            packer = pdb['packer-symlinks'].get(
                request_packer,
                request_packer)  #try to resolve similar packers
            super_packer = pdb['super-packer'].get(packer, '')
            ret = pdb.get(package, {}).get(packer, False)
            ret = ret if ret else pdb.get(package, {}).get(super_packer, False)

            if not ret:
                try:
                    if polite:
                        local_announce(
                            "Client `%s` asked for the tool `%s` in packer `%s` but i do not have it in my Database. Please update me!"
                            % (web.ctx.ip, package, packer))
                    else:
                        local_announce("404: no %s/%s for %s" %
                                       (request_packer, package,
                                        gethostbyaddr(web.ctx.ip)[0]))
                except Exception, e:
                    print("Got Exception %s: %s" % (str(Exception), (e)))
                web.NotFound()
                return "not found. i'm so sorry :("
            else:
Esempio n. 8
0
def wp_update(config_agent, tpl_render, req_path):
    view_settings = get_view_settings(config_agent, simple=True)
    static_files = static_file.get_global_static_files(**view_settings)

    folder_pages_full_path = config_agent.get_full_path("paths", "pages_path")
    local_full_path = mdutils.req_path_to_local_full_path(
        req_path, folder_pages_full_path)

    title = "Editing %s" % req_path
    create_new = False

    if local_full_path.endswith("/"):
        msg = "not allow to edit path/to/folder, using path/to/folder/index instead"
        raise web.BadRequest(message=msg)

    # os.path.exists(local_full_path)
    if os.path.isfile(local_full_path):
        buf = commons.shutils.cat(local_full_path)
    else:
        # not os.path.exists(local_full_path)
        create_new = True
        buf = ""

    return tpl_render.update(config_agent=config_agent,
                             static_files=static_files,
                             req_path=req_path,
                             create_new=create_new,
                             title=title,
                             content=buf,
                             **view_settings)
Esempio n. 9
0
    def POST(self):
        def update(d, i):
            for c in column_names():
                # input names are not decoded
                u = c.encode('utf8')
                if i.has_key(u):
                    d[c] = i.get(u)
                d['_tags'] = get_tags(d)

        i = web.input()
        a = i.get('__action', None)
        if a == 'add':
            d = {}
            update(d, i)
            o = objs.save(d)
            o = list(objs.find(d))
            return render.index(conf.title, columns(), o, 'add')
        elif a == 'update':
            if i.get('_id', None):
                d = objs.find_one(ObjectId(i['_id']))
                if d:
                    update(d, i)
                    oid = objs.save(d)
                    o = [objs.find_one(oid)]
                    return render.index(conf.title, columns(), o, 'update')
        elif a == 'delete':
            if i.get('_id', None):
                objs.remove(ObjectId(i['_id']))
                raise web.SeeOther('/')
        raise web.BadRequest()
Esempio n. 10
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()
Esempio n. 11
0
    def create_task(self):
        parameters = web.input()
        if not ("service" in parameters and "generator_type" in parameters
                and "generator_options" in parameters):
            raise web.BadRequest()

        t = db.transaction()

        result = db.select("service",
                           what="id",
                           where="name = $name",
                           vars={"name": parameters["service"]})
        try:
            service_id = result[0]["id"]
        except IndexError:
            service_id = db.insert("service", name=parameters["service"])

        task_id = str(uuid.uuid1())
        db.insert("task",
                  id=task_id,
                  status="available",
                  service_id=service_id,
                  generator_type=parameters["generator_type"],
                  generator_options=parameters["generator_options"])

        t.commit()

        return task_id
Esempio n. 12
0
def wp_rename_post(config_agent, tpl_render, req_path, new_path):
    folder_pages_full_path = config_agent.get_full_path("paths", "pages_path")

    old_path = req_path
    old_full_path = mdutils.req_path_to_local_full_path(
        old_path, folder_pages_full_path)
    new_full_path = mdutils.req_path_to_local_full_path(
        new_path, folder_pages_full_path)

    if old_full_path == new_full_path:
        return web.seeother("/%s" % new_path)
    elif not os.path.exists(old_full_path):
        msg = "old %s doesn't exists" % old_full_path
        raise web.BadRequest(msg)

    msg = """<pre>
allow
    file -> new_file
    folder -> new_folder

not allow
    file -> new_folder
    folder -> new_file
</pre>"""

    if os.path.isfile(old_full_path):
        if new_full_path.endswith("/"):
            raise web.BadRequest(msg)
    elif os.path.isdir(old_full_path):
        if not new_full_path.endswith("/"):
            raise web.BadRequest(msg)

    parent = os.path.dirname(new_full_path)
    if not os.path.exists(parent):
        os.makedirs(parent)

    shutil.move(old_full_path, new_full_path)

    cache.update_all_pages_list_cache(folder_pages_full_path)
    cache.update_recent_change_cache(folder_pages_full_path)

    if os.path.isfile(new_full_path):
        return web.seeother("/%s" % new_path)
    elif os.path.isdir(new_full_path):
        return web.seeother("/%s/" % new_path)
    else:
        raise web.BadRequest()
Esempio n. 13
0
    def POST(self):
        data = web.input()
        if not ("ident" in data and "csr" in data):
            raise web.BadRequest()

        crt = sign_csr(data.csr, data.ident)
        web.header('Content-Type', "application/json")
        return json.dumps({'certificate': crt})
Esempio n. 14
0
def render_error(msg):
    """
	Renders an error response.

	"""
    web.BadRequest()
    response = {'error': True, 'msg': msg}
    return response_renderer.render(response)
Esempio n. 15
0
    def adjust_credits(self, data):
        required_fields = ["imsi", "change"]
        if not all([_ in data for _ in required_fields]):
            return web.BadRequest()
        imsi = data["imsi"]
        try:
            change = int(data["change"])
        except ValueError:
            return web.BadRequest()
        old_credit = subscriber.get_account_balance(imsi)
        if change > 0:
            subscriber.add_credit(imsi, str(abs(change)))
        elif change < 0:
            subscriber.subtract_credit(imsi, str(abs(change)))

        new_credit = subscriber.get_account_balance(imsi)

        # Codeship is stupid. These imports break CI and this is an untested
        # method :)
        from core import freeswitch_interconnect, freeswitch_strings

        # Send a confirmation to the subscriber
        number = subscriber.get_caller_id(imsi)
        change_frmt = freeswitch_strings.humanize_credits(change)
        balance_frmt = freeswitch_strings.humanize_credits(new_credit)

        fs_ic = freeswitch_interconnect.freeswitch_ic(self.conf)
        fs_ic.send_to_number(
            number, '000',
            freeswitch_strings.gt(
                "The network operator adjusted your credit by %(change)s. "
                "Your balance is now %(balance)s.") % {
                    'change': change_frmt,
                    'balance': balance_frmt
                })

        # TODO(matt): all credit adjustments are of the kind "add_money," even
        #             if they actually subtract credit.
        reason = 'Update from web UI (add_money)'
        events.create_add_money_event(imsi,
                                      old_credit,
                                      new_credit,
                                      reason,
                                      to_number=number)
        return web.ok()
Esempio n. 16
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')
Esempio n. 17
0
 def cmdConfighelp(self):
     service = web.ctx.env["QUERY_STRING"].split('_')
     if len(service) != 2:
         raise web.BadRequest()
     var = service[1]
     service = service[0]
     if not service in ['cache', 'redirect', 'forward', 'image']:
         raise web.BadRequest()
     from lib import cache, redirect, forward, image
     data = eval('%s.Service.__doc__' % service)
     e = re.search('- %s: ([^-]+)' % var, data, re.MULTILINE)
     # Force browser cache
     web.header("Cache-Control", "public, max-age=3600")
     web.header("Age", "0")
     if not e:
         return 'No help available'
     doc = textwrap.wrap(e.group(1).strip(), 50)
     return '<br />'.join(doc)
Esempio n. 18
0
 def POST(self, command):
     """Handles certain POST commands."""
     # Always send back these headers.
     headers = {'Content-type': 'text/plain'}
     # Validate the exact endpoint.
     valid_post_commands = ('deactivate_number', 'deactivate_subscriber')
     if command not in valid_post_commands:
         return web.NotFound()
     # Get the posted data and validate.  There should be a 'jwt' key with
     # signed data.  That dict should contain a 'number' key -- the one we
     # want to deactivate.
     data = web.input()
     jwt = data.get('jwt', None)
     if not jwt:
         return web.BadRequest()
     serializer = itsdangerous.JSONWebSignatureSerializer(
         self.conf['bts_secret'])
     try:
         jwt = serializer.loads(jwt)
     except itsdangerous.BadSignature:
         return web.BadRequest()
     if command == 'deactivate_number':
         if 'number' not in jwt:
             return web.BadRequest()
         # The params validated, deactivate the number.  ValueError is
         # raised if this is the subscriber's last number.
         # The number should correspond to an IMSI or give a 404
         try:
             imsi = subscriber.get_imsi_from_number(jwt['number'])
             subscriber.delete_number(imsi, jwt['number'])
         except SubscriberNotFound:
             return web.NotFound()
         except ValueError:
             return web.BadRequest()
         return web.ok(None, headers)
     elif command == 'deactivate_subscriber':
         if 'imsi' not in jwt:
             return web.BadRequest()
         # The number should correspond to an IMSI.
         try:
             subscriber.delete_subscriber(jwt['imsi'])
         except SubscriberNotFound:
             return web.NotFound()
         return web.ok(None, headers)
Esempio n. 19
0
    def DELETE(self, transferId):
        ''' DELETE /transfer/{ID}
        
        Deletes one transfer resource.
        '''
        if not transferId:
            msg = "Cannot DELETE the transfer resource without specifying a valid transfer resource ID in the path transfer/{ID}"
            web.debug(msg)
            raise web.BadRequest(msg)

        try:
            transferId = int(transferId)
            policy.remove(transferId)
            return ''
        except TransferNotFound:
            msg = "Cannot DELETE transfer resource transfer/" + str(
                transferId) + ". Resource not found."
            web.debug(msg)
            raise web.BadRequest(msg)
Esempio n. 20
0
 def cmdConfigvars(self):
     if not web.ctx.env["QUERY_STRING"] in [
             'cache', 'redirect', 'forward', 'image'
     ]:
         raise web.BadRequest()
     from lib import cache, redirect, forward, image
     try:
         service = '%s.Service' % web.ctx.env["QUERY_STRING"]
         d = eval("dir(%s)" % service)
         vars = [
             x for x in d
             if not x[0] == '_' and not callable(getattr(eval(service), x))
         ]
         # Force browser cache
         web.header("Cache-Control", "public, max-age=3600")
         web.header("Age", "0")
         return str(vars)
     except Exception:
         raise web.BadRequest()
Esempio n. 21
0
    def PUT(self, transferId):
        ''' PUT /transfer/{ID}
        
        Updates one transfer.
        '''
        if not transferId:
            msg = "Cannot PUT to the transfer resource without specifying a valid transfer resource ID in the path transfer/{ID}"
            web.debug(msg)
            raise web.BadRequest(msg)

        try:
            transferId = int(transferId)
        except ValueError as e:
            msg = "Invalid transfer id: " + str(e)
            web.debug(msg)
            raise web.BadRequest(msg)

        try:
            raw = web.data()
            if config.audit:
                web.debug("Request Body: " + str(raw))
            parsed = json.loads(raw)
            transfer = web.storify(parsed)
            transfer = policy.update(transferId, transfer)
            return json.dumps(transfer)
        except TransferNotFound:
            msg = "Cannot PUT to transfer resource transfer/" + str(
                transferId) + ". Resource not found."
            web.debug(msg)
            raise web.BadRequest(msg)
        except MalformedTransfer as e:
            msg = "Bad request body in PUT to transfer/ resource: " + str(e)
            web.debug(msg)
            raise web.BadRequest(msg)
        except NotAllowed as e:
            msg = "Bad request body in PUT to transfer/ resource: " + str(e)
            web.debug(msg)
            raise web.BadRequest(msg)
        except PolicyError as e:
            msg = "Internal server error: " + str(e)
            web.debug(msg)
            raise web.InternalError(msg)
Esempio n. 22
0
    def delete_task(self):
        parameters = web.input()
        if not "id" in parameters:
            raise web.BadRequest()

        db.update("task",
                  where="id = $id",
                  vars={"id": parameters["id"]},
                  status="deleted",
                  data_file=None)

        return ""
Esempio n. 23
0
 def POST(self):
     try:
         logger.debug('Request description: POST request for saving valve data')
         valve_info = json.loads(web.data())
         logger.info('Data to save: %s', valve_info)
         update_valve_info(self.valve_id, valve_info)
         logger.info('Request completed successfully')
     except ValueError as ex:
         logger.exception("Could not save data as it is invalid")
         raise web.BadRequest(ex.message)
     except Exception as ex:
         logger.exception("Could not save data due to unknown error")
         raise web.InternalError(ex.message)
Esempio n. 24
0
 def convertfrom(self, value, tag, mimetype):
     if mimetype == 'application/xml':
         element = self.db.elementFromXML(value)
         if element.tagName != tag:
             raise web.BadRequest(
                 "Bad request, toplevel XML tag %s does not match final XPath element %s"
                 % (element.tagName, tag))
         return element
     elif mimetype == 'application/x-www-form-urlencoded':
         # xxxjack here comes a special case, and I don't like it.
         # if the url-encoded data contains exactly one element and its name is the same as the
         # tag name we don't encode.
         if type(value) == type({}) and len(value) == 1 and tag in value:
             value = value[tag]
         element = self.db.elementFromTagAndData(tag, value)
         return element
     elif mimetype == 'application/json':
         try:
             valueDict = json.loads(value)
         except ValueError:
             raise web.BadRequest(
                 "No JSON object could be decoded from body")
         if not isinstance(valueDict, dict):
             raise web.BadRequest(
                 "Bad request, JSON toplevel object must be object")
         # xxxjack here comes a special case, and I don't like it.
         # if the JSON dictionary contains exactly one element and its name is the same as the
         # tag name we don't encode.
         if len(valueDict) == 1 and tag in valueDict:
             element = self.db.elementFromTagAndData(tag, valueDict[tag])
         else:
             element = self.db.elementFromTagAndData(tag, valueDict)
         return element
     elif mimetype == 'text/plain':
         element = self.db.elementFromTagAndData(tag, value)
         return element
     else:
         raise web.InternalError("Conversion from %s not implemented" %
                                 mimetype)
Esempio n. 25
0
 def process(self):
     req = web.input()
     data = web.data()
     logging.info(req)
     self.context = {}
     try:
         d = loads(data)
         response = self.dispatch(d)
         web.header('Content-Type', 'application/json')
         return dumps(response)
     except Exception as e:
         logging.warn("couldn't dispatch")
         return web.BadRequest("couldn't dispatch: %s" % e)
Esempio n. 26
0
    def DELETE(self, name):
        user = web.input('user')['user']
        machine = load_machine(name)
        if not machine.locked:
            raise web.BadRequest()
        if machine.locked_by != user:
            raise web.Forbidden()

        res = DB.update('machine',
                        where='locked = true AND name = $name AND locked_by = $user',
                        vars=dict(name=name, user=user),
                        locked=False, locked_by=None)
        assert res == 1, 'Failed to unlock machine {name}'.format(name=name)
Esempio n. 27
0
def wp_source(config_agent, tpl_render, req_path):
    folder_pages_full_path = config_agent.get_full_path("paths", "pages_path")
    local_full_path = mdutils.req_path_to_local_full_path(
        req_path, folder_pages_full_path)

    if os.path.isfile(local_full_path):
        web.header("Content-Type", "text/plain; charset=UTF-8")
        buf = commons.shutils.cat(local_full_path)
        return buf
    elif os.path.isdir(local_full_path):
        msg = "folder doesn't providers source in Markdown, using file instead"
        raise web.BadRequest(msg)
    else:
        raise web.NotFound()
Esempio n. 28
0
    def PUT(self, site):
        logger = web.ctx.env.get('wsgilog.logger')
        logger.info("Processing NewSEG. site=%s", site)

        try:
            data = web.data()
            parser = seg.NEWSEGParser(data)
            ret = self.process(parser,
                               type=constants.SPLUNK_METRICS,
                               logger=logger)
            return json.dumps(ret, indent=4, sort_keys=True)
        except Exception as ex:
            logger.error(str(ex), exc_info=True)
            raise web.BadRequest(str(ex))
Esempio n. 29
0
    def POST(self):
        input_data = web.data()
        if len(input_data) == 0:
            return web.BadRequest()

        json_data = simplejson.loads(input_data)

        for i in ISSUES:
            if json_data['tid'] == i['tid']:
                i['issue_list'].append(json_data['iid'])
                return

        # if not found, create a init issue list
        ISSUES.append({'tid': json_data['tid'], 'issue_list': [json_data['iid']]})
        return web.OK
Esempio n. 30
0
    def PUT(self, name):
        desc = web.input(desc=None)['desc']
        status = web.input(status=None)['status']
        sshpubkey = web.input(sshpubkey=None)['sshpubkey']

        updated = {}
        if desc is not None:
            updated['description'] = desc
        if status is not None:
            updated['up'] = (status == 'up')
        if sshpubkey is not None:
            updated['sshpubkey'] = sshpubkey

        if not updated:
            raise web.BadRequest()
        DB.update('machine', where='name = $name',
                  vars=dict(name=name), **updated)