#!/usr/bin/env python

from __future__ import print_function

from common import populate_html

import os
import cgi
import base64
import MySQLdb
import Cookie

from collections import namedtuple


def process_input():
    # Load email and password from cookie
    cookie = Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE"))

    email = cookie["email"].value if "email" in cookie else None
    password = cookie["password"].value if "password" in cookie else None

    generate_output(email, password)


def generate_output(email, password):
    if not email or not password:
        print("Location: signin.py")
        print()
        return

    db_connection = MySQLdb.connect(host="localhost", user="root",
                                    passwd="1234", db="yagra")
    db_cursor = db_connection.cursor()

    UserInformation = namedtuple("UserInformation",
                                 "email, password, no_image, email_hash")

    # Fetch user information from database
    db_cursor.execute("""SELECT email, password, ISNULL(image), email_hash
                         FROM users
                         WHERE email = %s""", (email,))
    record = db_cursor.fetchone()

    # Could not find this user
    if not record:
        print("Location: signin.py")
        print()
        return

    user_info = UserInformation._make(record)

    # Wrong password
    if password != user_info.password:
        print("Location: signin.py")
        print()
        return

    # Valid email and password
    if user_info.no_image:
        image_url = ""
    else:
        image_url = base64.b16encode(user_info.email_hash)

    print("Content-type: text/html")
    print()
    print(populate_html("home.html", dict(email=email, password=password,
                                          image_url=image_url)))


try:
    process_input()
except:
    cgi.print_exception()

@@ -110,16 +110,31 @@
 ort cgi%0A
+import hashlib%0A
 import b
@@ -857,16 +857,25 @@
 edtuple(
+%0A        
 %22UserInf
@@ -897,71 +897,94 @@
     
-                         %22email, password, no_image, email_hash
+%22%22%22email, email_hash, salt, password_hash, random_password_hash,%0A           no_image%22%22
 %22)%0A%0A
@@ -1065,24 +1065,97 @@
  email, 
-password
+email_hash, salt, passwd_hash,%0A                                random_passwd_hash
 , ISNULL
@@ -1161,28 +1161,16 @@
 L(image)
-, email_hash
 %0A       
@@ -1455,16 +1455,94 @@
 ecord)%0A%0A
+    input_password_hash = hashlib.sha256(user_info.salt + password).digest()%0A%0A
     # Wr
@@ -1561,24 +1561,31 @@
 %0A    if 
+(input_
 password
  != user
@@ -1576,16 +1576,21 @@
 password
+_hash
  != user
@@ -1595,32 +1595,108 @@
 er_info.password
+_hash and%0A            input_password_hash != user_info.random_password_hash)
 :%0A        print(

use salted password hashing for authentication