define('SUCCESS_URL', 'http://foamicate.com');
define('FAIL_URL', 'http://foamicate.com/failure.php');
if (!isset($_SESSION['authenticating'])) {
    $_SESSION['authenticating'] = false;
}
// Check if the logged in session variable is set. If it's not initialize with false.
if (!isset($_SESSION['logged_in'])) {
    $_SESSION['logged_in'] = false;
}
if (!$_SESSION['authenticating']) {
    $_SESSION['authenticating'] = true;
    // First thing to do is grab the username out of the post variables.
    // TODO: change from GET to POST
    //$user = fetch_user_info($username);
    $user = array('public_key' => rawurldecode($_POST['public_key']), 'random' => $_POST['random']);
    $result = TrustAuth::get_challenge($user);
    $_SESSION['server'] = $result['server'];
    $_SESSION['user'] = $user;
    echo $result['json'];
} else {
    $user = $_SESSION['user'];
    $server = $_SESSION['server'];
    if (!isset($_POST['md5']) || !isset($_POST['sha'])) {
        $result = TrustAuth::wrong_stage();
    } else {
        $user['md5'] = $_POST['md5'];
        $user['sha'] = $_POST['sha'];
        $result = TrustAuth::authenticate($user, $server, SUCCESS_URL, FAIL_URL);
        if ($result['status']) {
            $_SESSION['logged_in'] = true;
            if (($db_user = fetch_user_info($user['public_key'])) == true) {
 /**
  * Outputs the fields required for a form to be authenticated with TrustAuth.
  *
  * @param {array} $options an array with option values to override the defaults
  * @return {string} string of HTML to output to the page.
  */
 public static function authenticate_form($options)
 {
     $options = array_merge(array('challenge_name' => 'ta-challenge', 'response_name' => 'ta-response', 'key_name' => 'ta-key'), $options);
     if (!isset($options['challenge'])) {
         $options['challenge'] = TrustAuth::get_challenge($_SERVER['SERVER_NAME']);
     }
     $str = "<input type=\"hidden\" id=\"trustauth-challenge\" name=\"" . htmlentities($options['challenge_name']) . "\" value=\"" . $options['challenge'] . "\"/>\n";
     $str .= "<input type=\"hidden\" id=\"trustauth-response\" name=\"" . htmlentities($options['response_name']) . "\"/>\n";
     $str .= "<input type=\"hidden\" id=\"trustauth-key\" name=\"" . htmlentities($options['key_name']) . "\"/>\n";
     return $str;
 }
/**
 * Adds the TrustAuth fields to the login form.
 */
function trustauth_login()
{
    $challenge = TrustAuth::get_challenge();
    setcookie(TRUSTAUTH_COOKIE_NAME, hash('sha256', $challenge . get_option(TRUSTAUTH_SALT_OPTION_NAME)), time() + TRUSTAUTH_COOKIE_EXPIRATION, COOKIEPATH, COOKIE_DOMAIN, false, true);
    echo TrustAuth::authenticate_form(array('challenge' => $challenge));
}