#!/usr/bin/env python3.9

from flask import Flask, render_template_string, request
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

app = Flask(__name__)
limiter = Limiter(
    app,
    key_func=get_remote_address,
    default_limits=["10000 per hour"]
)

passwords = set(i.strip() for i in open("words.txt").read().splitlines())

@limiter.limit("5/second")
@app.route('/')
def index():
    return ("\x3cpre\x3e\x3ccode\x3e%s\x3c/code\x3e\x3c/pre\x3e")%open(__file__).read()


def find_matches(key):
    ret = "\x3chtml\x3e\x3ch1\x3eMatching passwords\x3c/h1\x3e"
    num = 0
    for i in passwords:
        if key in i:
            num += 1
            if 'ict' in i:
                ret += "\x3cdiv\x3e[REDACTED]\x3c/div\x3e"
            else:
                ret += f"\x3cdiv\x3e{i}\x3c/div\x3e"
    ret += "\x3c/html\x3e"
    ret = ret.replace("\x3c/h1\x3e", f"\x3c/h1\x3e\x3ch3\x3eNumber of results: {num}\x3c/h3\x3e")
    return ret

@limiter.limit("5/second")
@app.route('/search')
def check():
    if "key" not in request.args:
        return '''
            \x3chtml\x3e
                \x3ccenter\x3e
                    \x3ch1\x3eHave you been hacked?\x3c/h1\x3e
                    \x3ch3\x3eEnter your password here to see if it's been hacked!\x3c/h3\x3e
                    \x3cform action="/search"\x3e
                        \x3cinput name="key" type="text" rows="1" cols="100"\x3e\x3c/textarea\x3e\x3cbr\x3e
                        \x3cinput type="submit" value="Search for password"\x3e\x3c/input\x3e
                \x3c/center\x3e
                \x3c/form\x3e
            \x3c/html\x3e
        '''

    key = request.args["key"]
    return find_matches(key)

app.run('0.0.0.0', 1003)