CoddityTeam / movaicode

Concours mensuel du Pire Développeur de France
123 stars 10 forks source link

Python − cloud AI implementation #38

Closed pinaraf closed 2 years ago

pinaraf commented 3 years ago

This is a very simple implementation, allowing you to set up a wonderful business. On one hand, you sell a string reverse business (obviously). These guys will have to go to /request to submit a query and wait for the AI to find the reverse. On the other hand, you sell a magic way to tell if users are human or bots. These will have to go to /captcha and do the work for free.

Don't worry, no need to thank me.

#!/usr/bin/env python3

from starlette.applications import Starlette
from starlette.responses import RedirectResponse, Response
from starlette.routing import Route
from hashlib import md5
import random

known_reverses = {
    md5(b"hello").hexdigest(): ("hello", "olleh"),
    md5(b"world").hexdigest(): ("world", "dlrow")
}

pending_reverses = []

human_ips = []

async def request_reverse(request):
    global pending_reverses
    if request.method == "POST":
        form = await request.form()

    if request.method == "GET" or request.method == "POST" and not "esrever" in form:
        return Response("""<h1>Request a reverse</h1>
<form method="POST">
    <input type="text" name="esrever">
    <input type="submit">
</form>""")
    else:
        # TODO : check for dups ?
        pending_reverses.append(form["esrever"])
        return RedirectResponse(url=request.url_for("get_reverse", query = md5(form["esrever"].encode("utf8")).hexdigest()), status_code=303)

async def get_reverse(request):
    requested_hash = str(request.path_params['query'])
    if not requested_hash in known_reverses:
        return Response("""<h1>Still no answer, please try again, our artificial intelligence is working for you!</h1>""")
    else:
        return Response("<h1>We found your reverse is <pre>%s</pre></h1>" % known_reverses[requested_hash][1])

async def captcha(request):
    global pending_reverses
    if request.method == "GET":
        challenge = None

        # If this is a client we checked in the past and he behaved fine, then we can give him real challenges
        # and he will never suspect he is working for us for free.
        if request.client.host in human_ips:
            if len(pending_reverses) > 0:
                challenge, pending_reverses = pending_reverses[0], pending_reverses[1:]
        if challenge is None:
            challenge = random.choice([x for x in known_reverses.values()])
            challenge = challenge[0]

        return Response(f"""<h1>CAPTCHA!</h1><br />We want to check that you are a human.<br />What is the reverse of <b><pre>{challenge}</pre></b> ?<br />
                        <form method="POST"><input type="hidden" name="challenge" value="{challenge}"><input type="text" name="reverse"><input type="submit"></form>""")
    elif request.method == "POST":
        form = await request.form()
        challenge = form["challenge"]
        reverse = form["reverse"]
        hash_challenge = md5(challenge.encode("utf8")).hexdigest()
        passed = False
        if hash_challenge in known_reverses and (challenge, reverse) != known_reverses[hash_challenge]:
            try:
                human_ips.remove(request.client.host)
            except:
                pass
        elif request.client.host in human_ips:
            # We accept his work of course
            known_reverses[hash_challenge] = (challenge, reverse)
            try:
                pending_reverses.remove(challenge)
            except:
                pass
            passed = True
        else:
            # Remember, we don't trust him, previous if, so the following assert must be true
            assert(hash_challenge in known_reverses)
            if (challenge, reverse) == known_reverses[hash_challenge]:
                human_ips.append(request.client.host)
                passed = True

        if passed:
            return Response("Congratulations, you are human!")
        else:
            return Response("Go rust somewhere else, you slimy bot!")

app = Starlette(debug=True, routes=[
    Route('/request', request_reverse, methods=["GET", "POST"]),
    Route('/captcha', captcha, methods=["GET", "POST"]),
    Route("/answer/{query:str}", get_reverse, name="get_reverse", methods=["GET"])
])
louismarslen commented 3 years ago

Pour l'ensemble de votre oeuvre (vos 9 contributions), mon cher @pinaraf, vous remportez le grand prix d'honneur du MOVAI CODE épisode 1 ! 😊

Vous le méritez amplement, voici votre trophée ! IMG_2641

louismarslen commented 2 years ago

Je fais un peu de ménage dans les issues -> d'ailleurs go participer à l'édition 5