#!/usr/bin/python2
import json
from flask import Flask
from flask import request
from flask import redirect
from flask import make_response
from flask import send_from_directory
from flask import send_file
from base64 import b64encode,b64decode

from config import *
from cookie_handler import *
from crypt import *

app = Flask(__name__)

challs = {
        'po1':validate_cookie_po1,
        'po2':validate_cookie_po2,
        'po3':validate_cookie_po3
}


'''
    This displays the dashboard of the crypto challanges.
    Used to redirect to the actual challanges
'''
@app.route("/")
def index():
    return send_file('dashboard/po.html')



'''
    Login Mask for all challanges, responds with the login mask and return the appropriate cookie validation function (for the challange)
'''
@app.route("/<path>")
def login_mask(path):

    # check if there is already a cookie
    cookie = request.cookies.get("auth", False)
    if not cookie or path not in challs.keys():
        return send_from_directory('static', 'login.html')

    # if cookie - validate the cookie with the appropr. function
    return challs.get(path, notfound)(cookie)

def notfound():
    return "404"


'''
    Authentication function, takes username and password and generates the cookie.
'''
@app.route("/authenticate", methods=["POST"])
def authenticate():
    referrer = request.referrer[-3:]
    username = request.form["user"]
    password = request.form["pass"]

    for user in app_users:
        if user.username == username and user.pwhash == hashlib.sha256(password + user.SALT).hexdigest():
            # correct username/password combination
            print('Debug: Got correct username/password combination')
            resp = make_response()
            resp.headers.add("Location", request.referrer)
            resp.status_code=302
            # crafting the user object, which will get decrypted as the auth cookie
            #user_obj = {"username":username, "access":app_users.get(username), 'secret':FLAGS[referrer]}
            #user_obj = str(user)
            user_obj = user
            break
    else:
        # wrong username/password combination, Error
        print('Debug: Wrong username/password combination, throwing error')
        resp = make_response("{\"Error\":\"Login failed\"}")
        resp.headers.add("Location", request.referrer)
        resp.status_code=302
        return resp

    # Challange selector
    if referrer == 'po1':
        cookie = create_cookie_po1(user_obj)
    elif referrer == 'po2':
        cookie = create_cookie_po2(user_obj)
    elif referrer == 'po3':
        print('itse le referer')
        cookie = create_cookie_po3(user_obj)
    else:
        return resp
    print('Debug: generated cookie for (%s): %s' %(referrer, cookie))

    # Setting the auth cookie and returning the response
    resp.set_cookie("auth", cookie)
    return resp




@app.route("/logout")
def logout():
    res = make_response()
    res.set_cookie("auth", "", expires=0)
    res.headers.add("Location", request.referrer)
    res.status_code=302
    return res

app.run(debug=False)
