<?php
// Create an account and apply SSH key
$config = json_decode(file_get_contents("/var/www/usergen/secret/config.json", true));

function checkParameters($parameterArray){
    $error = false;
    foreach($parameterArray as $parameter){
        if(!isset($_POST[$parameter])){
            $error = true;
        }
    }
    return $error;
}

function apiResult($result){
    header('Content-type: application/json');
    echo json_encode($result);
    exit();
}

function success(){
    apiResult(array("status" => true));
}

function error($error){
    apiResult(array("status" => false, "error" => $error));
}

function validateUsername($username){
    return (preg_match("/^([a-zA-Z0-9_.]+)$/", $username) == 1);
}

function validatePublicKey($key){
    return (preg_match("/^(ssh-rsa AAAAB3NzaC1yc2|ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNT|ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzOD|ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1Mj|ssh-ed25519 AAAAC3NzaC1lZDI1NTE5|ssh-dss AAAAB3NzaC1kc3)[0-9A-Za-z+\/]+[=]{0,3}( .*)?$/", $key) == 1);
}

if (checkParameters(array("pubkey", "userId", "authToken"))){
    error("Missing parameters");
}

$userToken = $_POST["authToken"];
$userId = $_POST["userId"];
$pubkey = $_POST["pubkey"];

if(!validatePublicKey($pubkey)){
    error("Invalid public key");
}

$request = curl_init();
curl_setopt($request, CURLOPT_URL, "https://hackers.town/api/v1/accounts/verify_credentials");
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
    "Authorization: Bearer ".$userToken
));
$response = curl_exec($request);
curl_close($request);
$User = json_decode($response);
// Check User
if($User->id != $userId){
    error("User Mismatch");
}
if(!validateUsername($User->username)){
    error("Invalid Username");
}
// Create temporary pubkey holding file
$TempFileName = "/etc/ttyserver/tmp/".uniqid("ssh-", true).".pub";
if(!file_put_contents($TempFileName, $pubkey."\n")){
    error("Key Addition Failed: Temp");
}
// Run User Generation Tool
// TODO: Replace with custom Rust PHP Extension
$UserGenCode = shell_exec("/usr/bin/sudo /etc/ttyserver/bin/mkuser \"".$User->username."\" \"".$TempFileName."\" 2>&1; echo $?");
if($UserGenCode != "0"){
    error("Key Addition Failed: MK-".$UserGenCode);
}
success();

?>
