<?php

require __DIR__ . '/config/config.php';

function print_error_and_exit($error) {
    // delete data content
    $data = array();
    include('idcard.php');
    exit();
}

// load keys
$private_key = file_get_contents('keys/private_key.bin');
$public_key  = file_get_contents('keys/public_key.bin');
$keypair = sodium_crypto_box_keypair_from_secretkey_and_publickey(
               sodium_crypto_sign_ed25519_sk_to_curve25519($private_key),
               sodium_crypto_sign_ed25519_pk_to_curve25519($public_key));

if ( !isset($_GET['v']) || $_GET['v'] === '0.1') {
    $message_json = $_GET['d'];
    $message = json_decode($message_json, true);
    $message['signature'] = sodium_base642bin($message['signature'], SODIUM_BASE64_VARIANT_URLSAFE);
    if (! sodium_crypto_sign_verify_detached($message['signature'], $message['verify'] . $message['data'], $public_key )) {
	$verified = false;
	print_error_and_exit('signature invalid');
    }
    if (! $message['data'] = sodium_crypto_box_seal_open(sodium_base642bin($message['data'], SODIUM_BASE64_VARIANT_URLSAFE), $keypair)) {
	$error = true;
	print_error_and_exit('unable to decrypt');
    };
    $data = json_decode($message['data'],true);
} elseif ($_GET['v'] === '0.2') {
    $message_encoded = $_GET['d'];
    try {
        $message_signed = sodium_base642bin($message_encoded, SODIUM_BASE64_VARIANT_URLSAFE);
    } catch (Exception) {
        $error = false;
	print_error_and_exit('encoding invalid');
    }
    if (! $message_encrypted = sodium_crypto_sign_open($message_signed, $public_key )) {
        $verified = false;
	print_error_and_exit('signature invalid');
    }
    if (! $message = sodium_crypto_box_seal_open($message_encrypted, $keypair)) {
	$error = true;
	print_error_and_exit('unable to decrypt');
    };
    $data = json_decode($message,true);
}

$verified = true;
$ldap_conn = ldap_connect($CONFIG['ldap']['url']);
if (!$ldap_conn) {
    die('Could not conntect to ldap server');
}
if (!ldap_bind($ldap_conn, $CONFIG['ldap']['bind_user'], $CONFIG['ldap']['bind_passwd'])) {
    die("Could not bind to LDAP server.");
}
if ($data['id'] && $data['id'] != '---') {
    $filter = sprintf($CONFIG['ldap']['filter_id'], ldap_escape($data['id'],null, LDAP_ESCAPE_FILTER));
} else {
    $filter = sprintf($CONFIG['ldap']['filter_name'], 
        ldap_escape($data['firstname'],null, LDAP_ESCAPE_FILTER),
        ldap_escape($data['lastname'],null, LDAP_ESCAPE_FILTER),
        ldap_escape($data['birthdate'],null, LDAP_ESCAPE_FILTER));
}
$search_result = ldap_search($ldap_conn, $CONFIG['ldap']['base_dn'], $filter);
if (!$search_result) {
    die("LDAP search failed.");
}
$entries = ldap_get_entries($ldap_conn, $search_result);
if ($entries['count']) {
    $valid = true;
} else {
    $valid = false;
    // delete data content
    $data = array();
}

include('idcard.php');
?>