from crypt import *
from base64 import b64encode,b64decode
from config import *
from time import sleep
import urllib
from flask import render_template


secret_msg =  {
        1337:"Welcome Back Administrator, Secret Key: %s" % (FLAGS['po2']),
        1000:"Superb!"
}

def validate_cookie_po1(cookie):
    print("validating cookie: %s" % cookie)
    msg = decrypt(b64decode(cookie))
    if msg == False:
        return '{"Error":"PaddingError"}'
    else:
        print('Debug: decryped cookie: %s' % msg)

        username,pwhash,ar,flag = msg.split(':')
        ar = int(ar)

        for user in app_users:
            if user.username == username and user.pwhash == pwhash:
                # the cookie got a valid username and password
                return render_template("welcome_ch1.html", username=username, rights=ar, secret=secret_msg.get(ar, "--- no message for you ---"))
        else:
            return "<h5>An Error occured.</h5>"


def validate_cookie_po2(cookie):
    print("validating cookie: %s" % cookie)
    msg = decrypt(b64decode(cookie))
    if msg == False:
        return '{"Error":"PaddingError"}'
    else:
        print('Debug: decryped cookie: %s' % msg)

        username,pwhash,ar,flag = msg.split(':')
        ar = int(ar)

        for user in app_users:
            if user.username == username and user.pwhash == pwhash:
                # the cookie got a valid username and password
                return render_template("welcome_ch2.html", username=username, rights=ar, secret=secret_msg.get(ar, "--- no message for you ---"))
        else:
            return "<h5>An Error occured.</h5>"

def validate_cookie_po3(cookie):
    msg = decrypt(b64decode(cookie))
    if msg == False:
        # just pretend to have a longer timing
        sleep(1)
        return ''
    else:
        print('Debug: decryped cookie: %s' % msg)
        username,pwhash,ar,flag = msg.split(':')
        ar = int(ar)

        for user in app_users:
            if user.username == username and user.pwhash == pwhash:
                # the cookie got a valid username and password
                return render_template("welcome_ch3.html", username=username, rights=ar, secret=secret_msg.get(ar, "--- no message for you ---"))
        else:
            return "<h5>An Error occured.</h5>"

def validate_cookie_po4(cookie):
    pass

def create_cookie_po1(user_obj):
    print('Debug: user_obj: %s' %user_obj)
    user_obj.flag = FLAGS['po1']

    cookie = b64encode(encr(str(user_obj))) return cookie
def create_cookie_po2(user_obj):
    print('Debug: user_obj: %s' %user_obj)
    user_obj.flag = "P{Its-not-that-easy!;)}"
    cookie = b64encode(encr(str(user_obj)))
    return cookie

def create_cookie_po3(user_obj):
    print('Debug: user_obj: %s' %user_obj)
    user_obj.flag = FLAGS['po3']
    cookie = b64encode(encr(str(user_obj)))
    return cookie