import mimetypes

from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.db import connection
from wsgiref.util import FileWrapper
from django_ratelimit.decorators import ratelimit


# Create your views here.
def index(request):
    return render(request, 'core/index.html')


def about(request):
    return render(request, 'core/about.html')


def problems(request):
    return render(request, 'core/problems.html')


def broken_access(request):
    return render(request, 'core/Broken Access Control/broken-access.html')


def ba_explanation(request):
    return render(request, 'core/Broken Access Control/ba-explanation.html')


def ba_showcase(request):
    return render(request, 'core/Broken Access Control/ba-showcase.html')


def ba_countermeasures(request):
    return render(request, 'core/Broken Access Control/ba-countermeasures.html')


def ba_badexample(request):
    return render(request, 'core/Broken Access Control/ba-badexample.html')


def injections(request):
    return render(request, 'core/Injections/injections.html')


def ij_explanation(request):
    return render(request, 'core/Injections/ij-explanation.html')


def ij_showcase(request):
    return render(request, 'core/Injections/ij-showcase.html')


def ij_example(request):
    if request.method == 'POST':
        pass_username = request.POST['username']
        pass_password = request.POST['password']

        pass_username = pass_username.lower().replace('delete', ' ')

        cursor = connection.cursor()

        cursor.execute(
            "SELECT * FROM auth_user WHERE username = '%s' AND password='%s'" % (pass_username, pass_password))
        row = cursor.fetchone()

        if row is not None:
            msg = 'Log in Successful'
        else:
            msg = 'Wrong Credentials'

        form = AuthenticationForm(request.POST)
        sent = True
        return render(request, 'core/Injections/ij-example.html', {'form': form, 'msg': msg, 'sent': sent, 'data': row})
    else:
        form = AuthenticationForm()
        return render(request, 'core/Injections/ij-example.html', {'form': form})


def ij_countermeasures(request):
    return render(request, 'core/Injections/ij-countermeasures.html')


def cryptographic_failures(request):
    return render(request, 'core/Cryptographic Failures/cryptographic_failures.html')


def cf_explanation(request):
    return render(request, 'core/Cryptographic Failures/cf-explanation.html')


def ia_example(request):
    if request.user.is_authenticated:
        return render(request, 'home.html')
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('/')  # profile
        else:
            msg = 'Wrong Credentials'
            form = AuthenticationForm(request.POST)
            return render(request,
                          'core/Identification and Authentication Failures/ia-example.html', {'form': form, 'msg': msg})
    else:
        form = AuthenticationForm()
        return render(request,
                      'core/Identification and Authentication Failures/ia-example.html', {'form': form})


def download_usernames(request):
    usernames = open("usernames.txt", 'r')

    mime_type, _ = mimetypes.guess_type("usernames.txt")

    response = HttpResponse(usernames, content_type=mime_type)
    response['Content-Disposition'] = "attachment; filename=%s" % 'usernames.txt'

    return response


def download_passwords(request):
    usernames = open("passwords.txt", 'r')

    mime_type, _ = mimetypes.guess_type("passwords.txt")

    response = HttpResponse(usernames, content_type=mime_type)
    response['Content-Disposition'] = "attachment; filename=%s" % 'passwords.txt'

    return response


def download_script(request):
    usernames = open("brute_force.py", 'r')

    mime_type, _ = mimetypes.guess_type("brute_force.py")

    response = HttpResponse(usernames, content_type=mime_type)
    response['Content-Disposition'] = "attachment; filename=%s" % 'brute_force.py'

    return response


def download_script_ia(request):
    usernames = open("hash_crack.py", 'r')

    mime_type, _ = mimetypes.guess_type("hash_crack.py")

    response = HttpResponse(usernames, content_type=mime_type)
    response['Content-Disposition'] = "attachment; filename=%s" % 'MD5_crack.py'

    return response


def download_script_rsa(request):
    usernames = open("RSA.py", 'r')

    mime_type, _ = mimetypes.guess_type("RSA.py")

    response = HttpResponse(usernames, content_type=mime_type)
    response['Content-Disposition'] = "attachment; filename=%s" % 'RSA.py'

    return response


def cf_showcase(request):
    return render(request, 'core/Cryptographic Failures/cf-showcase.html')


def cf_countermeasures(request):
    return render(request, 'core/Cryptographic Failures/cf-countermeasures.html')


def Ident_Auth_Failures(request):
    return render(request, 'core/Identification and Authentication Failures/IA-Failures.html')


def ia_explanation(request):
    return render(request, 'core/Identification and Authentication Failures/ia-explanation.html')


def ia_showcase(request):
    return render(request, 'core/Identification and Authentication Failures/ia-showcase.html')


def ia_countermeasures(request):
    return render(request, 'core/Identification and Authentication Failures/ia-countermeasures.html')


def Vuln_Outd_Components(request):
    return render(request, 'core/Vulnerable and Outdated Components/VulnerableOutdated.html')


def vo_explanation(request):
    return render(request, 'core/Vulnerable and Outdated Components/vo-explanation.html')


def vo_showcase(request):
    return render(request, 'core/Vulnerable and Outdated Components/vo-showcase.html')


def vo_countermeasures(request):
    return render(request, 'core/Vulnerable and Outdated Components/vo-countermeasures.html')


def profile(request):
    if request.user.is_authenticated:
        return render(request, 'core/Profile.html')
    else:
        return redirect('/')


def signup(request):
    if request.user.is_authenticated:
        return redirect('/')
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('/')
        else:
            return render(request, 'core/signup.html', {'form': form})
    else:
        form = UserCreationForm()
        return render(request, 'core/signup.html', {'form': form})


@ratelimit(key='ip', rate='10/m', block=True)
def signin(request):
    if request.user.is_authenticated:
        return render(request, 'home.html')
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('/')  # profile
        else:
            msg = 'Wrong Credentials'
            form = AuthenticationForm(request.POST)
            return render(request, 'core/signin.html', {'form': form, 'msg': msg})
    else:
        form = AuthenticationForm()
        return render(request, 'core/signin.html', {'form': form})


def signout(request):
    logout(request)
    return redirect('/')
