Exemple #1
0
async def donation(state):
    """Return the donation form for the Service corresponding to state"""
    service = await get_service(0, by_state=state)
    if not service:
        abort(HTTPStatus.NOT_FOUND, "Service does not exist.")
    return await render_template("streamalerts/display.html",
                                 twitchuser=service.twitchuser,
                                 service=service.id)
def get_user(identity):
    from modules.users.models import User
    if identity:
        user = User.query.filter_by(username=identity).first()
        return user
    else:
        print(identity)
        abort(401)
Exemple #3
0
def invoice_qr(invoice_id):
    invoice = Invoice.get_by_id(invoice_id)
    if invoice is None:
        abort(404)
    qr = qrcode.make(f"lightning:{invoice.payreq}".uppercase())
    response = make_response(qr)
    response.headers.set("Content-Type", "image/png")
    return response
Exemple #4
0
 async def put(self, update_data, pet_id):
     """Update existing pet"""
     try:
         item = Pet.get_by_id(pet_id)
     except ItemNotFoundError:
         abort(404)
     item.update(update_data)
     return item
Exemple #5
0
async def delete_game(token):
    global MULTIWORLDS

    if not token in MULTIWORLDS:
        abort(404, description=f'Game with token {token} was not found.')

    close_game(token)
    return jsonify(success=True)
Exemple #6
0
def render_words(language: str = "en-us"):
    try:
        with open(f"languages/{language}.json") as f:
            all_words = json.load(f)
    except Exception:
        abort(404, "Language not found...")

    return all_words
Exemple #7
0
    async def post_verify(self, mod_id: str):
        if not await Mod.exists(mod_id):
            abort(404, "Unknown mod")

        await Mod.update.values(verified=True).where(Mod.id == mod_id
                                                     ).gino.status()

        return jsonify(True)
Exemple #8
0
        async def wrapped_view(**kwargs):
            g.user = get_user(request.args.get(param, type=str)) or abort(
                HTTPStatus.NOT_FOUND, "User  does not exist.")

            if LNBITS_ALLOWED_USERS and g.user.id not in LNBITS_ALLOWED_USERS:
                abort(HTTPStatus.UNAUTHORIZED, "User not authorized.")

            return await view(**kwargs)
Exemple #9
0
def get_descriptors():
    try:
        app.clerk.wait_for_consensus()
        desc = quart.jsonify(app.clerk.descriptors)
        return desc, 200
    except Exception as e:
        logging.exception(e)
        quart.abort(503)
Exemple #10
0
async def healthcheck():
    if discordbot.is_closed():
        abort(500, description='Connection to Discord is closed.')

    appinfo = await discordbot.application_info()
    await discordbot.fetch_user(appinfo.owner.id)

    return jsonify(success=True)
Exemple #11
0
async def logout_page():
    try:
        logger.info(f"login page accessed")
        template = f"user/logout.html"
        return await render_template(template)  # , error=error)
    except Exception as e:
        logger.error(f"the page being access is not available: {e}")
        abort(404)
Exemple #12
0
async def api_new_key():
    identity = request.args.get('identity', None)
    if not identity:
        abort(400)
    api_key = generate_api_key()
    #await redis.set('unconfirmed-apikeys:' + api_key, identity, expire=300)
    await redis.set('apikeys:' + api_key, identity)
    return api_key
Exemple #13
0
        async def new_func(*args, **kwargs):
            logger.debug("Validating request data against the schema.")
            try:
                kwargs.update(schema(await _get_request_data()))
            except Invalid as e:
                quart.abort(400, description=f"Invalid data: {e.msg}")

            return await func(*args, **kwargs)
Exemple #14
0
async def create_problem():
    if not current_user.role or current_user.role.name != "Admin":
        abort(401)
    if request.method == "GET":
        return await render_template('creator.html')

    form = await request.form
    files = (await request.files).getlist('file')
    test_name = form.get('test_name')
    readable_name = form.get('readable_name')
    max_time = int(form.get('max_time'))
    i_sample = form.get('i_sample')
    o_sample = form.get('o_sample')
    details = form.get('details')

    if not files:
        await flash("Please upload valid test cases.")
        return await render_template('creator.html')

    if not any(x.filename == 'correct.py' for x in files):
        await flash("You must provide a correct.py file!")
        return await render_template('creator.html')

    if len(files) == 1:
        await flash("Please provide at least one test case!")
        return await render_template('creator.html')

    existing_db = Problem.query.filter_by(test_folder=test_name).first()
    if existing_db:
        await flash("There's already a test with that name.")
        return await render_template('creator.html')

    if not all((files, test_name, readable_name, max_time, i_sample, o_sample, details)):
        await flash("Please input all fields.")
        return await render_template('creator.html')

    details = html.escape(details)

    try:
        tmpdir = test_checker(files, max_time)
    except subprocess.TimeoutExpired:
        await flash("Your correct.py timed out. Consider raising maximum time or optimize your code.")
        return await render_template('creator.html')
    except subprocess.CalledProcessError as e:
        await flash("An error has occured on your correct.py.")
        await flash(e.stderr)
        return await render_template('creator.html')

    try:
        dirname = 'cases/' + test_name
        shutil.move(tmpdir, dirname)
        make_problem(test_name, readable_name, max_time, i_sample, o_sample, details)
        await flash("OK!")
    except:
        traceback.print_exc()
        await flash("Something went wrong...")
    finally:
        return await render_template('creator.html')
Exemple #15
0
    async def get_download(self, mod_id: str):
        mod = await Mod.get(mod_id)

        if mod is None:
            abort(404, "Unknown mod")
        elif not mod.zip_url:
            abort(404, "Mod has no download")

        return jsonify(url=mod.zip_url)
Exemple #16
0
    async def _post_receive(self) -> Response:
        payload = await request.json
        if not isinstance(payload, dict):
            abort(400)

        response = await self._handle_event(payload)
        if isinstance(response, dict):
            return jsonify(response)
        return Response('', 204)
Exemple #17
0
async def index(filename):
    if filename not in (None, "index.html"):
        abort(404)
        return
    file = "index.html" if filename is None else filename
    for path in RESOURCE_PATHS:
        await make_push_promise(url_for("static", filename=path))

    return await make_response(await render_template(file))
Exemple #18
0
 async def post(self):
     data = await request.get_json()
     if 'auth' in data and data['auth'] == c.InternalApiToken:
         if not client.in_channel(data['channel']):
             abort(400, "Bot not in specified channel")
         result = await client.message(data['channel'], data['message'])
         return jsonify({"success": True})
     else:
         abort(401)
Exemple #19
0
async def remove_host():
    try:
        id = await request.json.get('id', int)
    except ValueError:
        abort(404)

    Host.delete_by_id(id)

    return 'OK', 200
Exemple #20
0
async def register(event_id):
    event = await get_event(event_id)
    if not event:
        abort(HTTPStatus.NOT_FOUND, "Event does not exist.")

    return await render_template("events/register.html",
                                 event_id=event_id,
                                 event_name=event.name,
                                 wallet_id=event.wallet)
Exemple #21
0
async def tcdel():

    data = await request.json
    if data is None or 'id' not in data:
        return abort(400)

    c_id = data.get('id')

    dc = get_docker_client(c_id)
    try:
        container = dc.containers.get(c_id)
    except docker.errors.NotFound:
        return abort(404)

    cmd = 'tcdel --all --docker ' + c_id

    print('[ CMD ]', cmd, sep='\n', end='\n')

    try:
        node = Node.get(Node.short_id == c_id)

        if node.lab.runtime != 'cluster':
            raise peewee.DoesNotExist

        host = node.host
        dc = host.get_docker_client()
        lab_name = node.lab.name

        return_code, stdout = ssh_exec('tcwrap ' + cmd + ' --lab ' + lab_name,
                                       host.get_config())

        stderr = ''

    except peewee.DoesNotExist:
        dc = docker.from_env()

        tcset_process = subprocess.run(cmd,
                                       shell=True,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE,
                                       universal_newlines=True,
                                       timeout=25)

        return_code = tcset_process.returncode
        stdout = tcset_process.stdout
        stderr = tcset_process.stderr

    print('[ returncode ] ', return_code)
    print('[ stdout ]', stdout, sep='\n')
    print('[ stderr ]', stderr, sep='\n')

    container = dc.containers.get(c_id)

    if is_router(container):
        routers_cache.delete(container.name)

    return 'OK', 200
Exemple #22
0
async def get_mapstyle_fontstack(fontstack, fontrange):
    # TODO EXTREMELY IMPORTANT: this is unsanitized input being put on the
    # filesystem. This is extremely unsafe! THIS IS AN ATTACK VECTOR!
    # DO NOT SHIP THIS TO PROD!
    fontstack_path = FONTS_STATIC_PATH / fontstack / f'{fontrange}.pbf'
    if await fontstack_path.exists():
        return await fontstack_path.read_bytes()
    else:
        abort(404)
Exemple #23
0
async def dbl():
    json = await request.get_json()
    uid = int(json["user"])

    res = await db.member.find_one({"_id": uid})

    if res is None:
        print(f"VOTING: User {uid} not found")
        abort(400, description="Invalid User")

    streak = res.get("vote_streak", 0)
    last_voted = res.get("last_voted", datetime.min)
    tickets = 10 if json["isWeekend"] else 5

    if datetime.utcnow() - last_voted > timedelta(days=2):
        streak = 0

    streak += 1

    if streak >= 40 and streak % 10 == 0:
        box_type = "master"
    elif streak >= 14:
        box_type = "ultra"
    elif streak >= 7:
        box_type = "great"
    else:
        box_type = "normal"

    await db.member.update_one(
        {"_id": uid},
        {
            "$set": {
                "vote_streak": streak,
                "last_voted": datetime.utcnow()
            },
            "$inc": {
                "vote_total": 1,
                f"gifts_{box_type}": 1,
                "halloween_tickets": tickets,
            },
        },
    )

    article = "an" if box_type == "ultra" else "a"

    try:
        await req(
            0,
            "send_dm",
            user=uid,
            message=
            f"Thanks for voting! You received {article} **{box_type} box** and **{tickets} Halloween Candies**.",
        )
    except OSError:
        pass

    return "Success", 200
Exemple #24
0
def abort(http_status_code, exc=None, **kwargs):
    try:
        quart.abort(http_status_code)
    except HTTPException as err:
        err.description = json.dumps(kwargs.get("messages"))
        err.data = kwargs
        err.exc = exc

        raise err
Exemple #25
0
async def ws(service_name: str):
    if service_name not in rpc_services:
        abort(404)

    while True:
        await websocket.send(
            json.dumps(await handle_rpc_request(
                rpc_services[service_name],
                json.loads(await websocket.receive()))))
Exemple #26
0
async def ticket(ticket_id):
    ticket = get_ticket(ticket_id) or abort(HTTPStatus.NOT_FOUND,
                                            "Ticket does not exist.")
    event = get_event(ticket.event) or abort(HTTPStatus.NOT_FOUND,
                                             "Event does not exist.")
    return await render_template("events/ticket.html",
                                 ticket_id=ticket_id,
                                 ticket_name=event.name,
                                 ticket_info=event.info)
Exemple #27
0
async def profile(username) -> Union[str, "Response"]:
    # fetch the user
    user = await User().get_user(username=username)

    # user not found
    if not user:
        abort(404)

    return await render_template("user/profile.html", user=user)
Exemple #28
0
async def weather(zip_code: str, country: str):
    if not weather_service.__api_key:
        return quart.jsonify({'status': 'disabled', 'reason': 'no API key'})

    weather_data = await weather_service.get_current(zip_code, country)
    if not weather_data:
        quart.abort(404)

    return quart.jsonify(weather_data)
Exemple #29
0
async def scrape():
    data = await request.json
    if not data["url"].startswith("https://tabs.ultimate-guitar.com/"):
        abort(404)
    r = await asks.get(data["url"])
    return html.unescape(
        r.text.partition("content":"")[2].partition("",&quot")
        [0].replace("[ch]",
                    "").replace("[/ch]", "").replace("[tab]", "").replace(
                        "[/tab]", "").replace("\\r\\n", "\n"))
Exemple #30
0
def abort(http_status_code, exc=None, **kwargs):
    """Raise a HTTPException for the given http_status_code. Attach any keyword
    arguments to the exception for later processing.
    """
    try:
        quart.abort(http_status_code)
    except HTTPException as err:
        err.data = kwargs
        err.exc = exc
        raise err