<slide title="People Map">

<break lines="1" />
<blurb fontsize="6em">
Backend code for login and XSRF prevention
</blurb>

<example result="0" marginleft="1em" marginright="0.5em" fontsize="1.4"><![CDATA[<?php
$logged_in = session_check();

$token = null;
if(isset($_POST['token'])) $token = $_POST['token'];
else if(isset($_GET['token'])) $token = $_GET['token'];

function auth_check() {
  global $token, $server_secret;
  if(!$token || $_COOKIE['token'] != $token) {
    echo "Token mismatch";
    exit;
  }
  if(!$_COOKIE['auth'] || $_COOKIE['auth'] != sha1($server_secret.$_COOKIE['id'])) {
    echo "Auth mismatch";
    exit;
  }
}

function session_check() {
  global $server_secret;
  if($_COOKIE['auth'] && $_COOKIE['id'] && $_COOKIE['auth'] == 
     sha1($server_secret.$_COOKIE['id'])) {
    SetCookie('token', sha1($auth.rand()));
    return 1;
  }
  return 0;
}
?>]]></example>

<example result="0" marginleft="1em" marginright="0.5em" fontsize="1.4" type="javascript"><![CDATA[<?php
  case 'add':
    auth_check();
    $id = $people->insert($_REQUEST);
    $record = $people->load($id);
    echo json_encode(array('people'=>$record));
    break;

  case 'modify':
    auth_check();
    $people->modify($_REQUEST);
    echo json_encode(array('status'=>'Modified'));
    break;

  case 'login':
    if(!empty($users[$_POST['id']]) && $users[$_POST['id']]==sha1($_POST['pwd'])) {
      $auth = sha1($server_secret.$_POST['id']);
      $xsrf_token = sha1($auth.rand());
      echo json_encode(array('status'=>1, 'id'=>$_POST['id'], 'auth'=>$auth, 'token'=>$xsrf_token));
    } else {
      echo json_encode(array('status'=>0));
    }
    break;
?>]]></example>

</slide>
