<?php
$config = json_decode(file_get_contents("/var/www/usergen/config.json", true));

if (isset($_REQUEST["act"])){
    // internal functions such as id request
    switch($_REQUEST["act"]){
        case "id":
            // return OAUTH app ID
            header('Content-type: application/json');
            echo json_encode(array("id" => $config->oauth->key));
            exit();
            break;
        default:
            break;
    }
}else if (isset($_REQUEST["code"])){
    // Mastodon callback
    $MastCode = $_REQUEST["code"];
}
?>
<HTML lang="en">
    <Head>
        <Title>HackersTown Server Access</Title>
        <meta charset="utf-8">
        <base href="/auth"/>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- Javascript -->
        <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
        <script src="https://code.jquery.com/color/jquery.color.plus-names-2.1.2.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/jszip@3.9.1/dist/jszip.min.js" integrity="sha256-aSPPIlJfSHQ5T7wunbPcp7tM0rlq5dHoUGeN8O5odMg=" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.10/dist/sweetalert2.all.min.js" integrity="sha256-YX0M+vWkN+Xjq3t0RBoP6rENNiYm4CN2k33WefMkn+E=" crossorigin="anonymous"></script>
        <script src="/base64url.js"></script>
        <script src="/ssh-util.js"></script>
        <script src="/keygen.js"></script>
        <script src="/fittext.js"></script>
        <script src="/index.js"></script>
        <!-- Stylesheets -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
        <link href="/style.css" rel="stylesheet"/>
    </Head>
    <Body>
        <div class="row">
            <div class="desktopOnly col-4"></div>
            <div id="content" class="col-4 center">
                <div class="row">
                    <a href="https://tty.hackers.town">
                        <img src="/Assets/HTown.png" class="logo self-align-center mx-auto d-block" alt="Hacker Town logo in ASCII art. Rendered as image to force correct visualization."/>
                    </a>
                </div>
                <?php 
                    // Query /oauth/token
                    $AuthToken = "";
                    $UserName = "";
                    $ErrorDesc = "";
                    $UserId = "";
                    $request = curl_init();
                    curl_setopt($request, CURLOPT_POST, 1);
                    curl_setopt($request, CURLOPT_URL, "https://hackers.town/oauth/token");
                    curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
                    $reqirectUri = "https://tty.hackers.town/auth";
                    $options = "grant_type=authorization_code&code=".$MastCode."&client_id=".$config->oauth->key."&client_secret=".$config->oauth->secret."&scope=read:accounts&redirect_uri=".$reqirectUri;
                    curl_setopt($request, CURLOPT_POSTFIELDS, $options);
                    $response = curl_exec($request);
                    curl_close($request);
                    $Auth = json_decode($response);
                    if(isset($Auth->token_type)){
                        // Valid Auth?
                        $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: ".$Auth->token_type." ".$Auth->access_token
                        ));
                        $response = curl_exec($request);
                        curl_close($request);
                        $User = json_decode($response);

                        if (isset($User->id)){
                            // Congrats!
                            $AuthToken = $Auth->access_token;
                            $UserName = $User->display_name;
                            $UserId = $User->id;
                        }else{
                            // invalid auth
                            $AuthToken = "BadUser";
                            $ErrorDesc = "User Not Found";
                        }
                    }else{
                        // invalid auth
                        if(isset($_COOKIE["oa_retries"])){
                            $retries = $_COOKIE["oa_retries"];
                            if($retries >= 3){
                                $AuthToken = "BadUser";
                                $ErrorDesc = "Invalid OAuth";
                                setcookie("oa_retries", 0, time()+3600);
                            }else{
                                $retries++;
                                setcookie("oa_retries", $retries, time()+3600);
                                $AuthToken = "BadOauthRetry";
                                $ErrorDesc = "Invalid OAuth Retry";
                            }
                        }else{
                            $AuthToken = "BadOauth";
                            $ErrorDesc = "Invalid OAuth Retry";
                            setcookie("oa_retries", 1, time()+3600);
                        }
                    }

                    // revoke token after usage
                ?>
                <div id="usertoken" hidden><?php echo $AuthToken; ?></div>
                <div class="row"<?php if(strpos($AuthToken, "Bad") === false){
                    echo "hidden";
                }?>>
                    <!-- Select to upload public key or generate a new one locally -->
                    <span>
                        Invalid
                    </span>
                    <span>
                        try again
                    </span>
                    <div id="ErrorResult" class="message">
                        <?php echo $ErrorDesc; ?>
                    </div>
                </div><div class="row button"<?php if(strpos($AuthToken, "Bad") === false){
                    echo "hidden";
                }?>>
                    <!-- Select to upload public key or generate a new one locally -->
                    <button class="col keyButton" onclick="beginOauth()">Retry</button>
                </div>
                <div class="row"<?php if(strpos($AuthToken, "Bad") !== false){
                    echo "hidden";
                }?>>
                    <!-- Select to upload public key or generate a new one locally -->
                    <span>
                        <?php 
                            $Welcomes = array("Welcome", "Dobrodošli", "Vitejte", "Welkom", "Tervetuloa", "Willkommen", "Fáilte", "Benvenuto", "Bienvenidos", "Välkommen", "ようこそ");
                            echo $Welcomes[array_rand($Welcomes)];
                        ?>
                    </span>
                    <span id="resizer">
                        <?php echo $UserName; ?>
                    </span>
                    <div class="message">
                        Setup an account SSH key
                    </div>
                </div>
                <div class="row button" <?php if(strpos($AuthToken, "Bad") !== false){
                    echo "hidden";
                }?>>
                    <button class="col keyButton" onclick="generateSSH('<?php echo $UserName; ?>', '<?php echo $UserId; ?>', '<?php echo $AuthToken; ?>')">Generate</button>
                    <button class="col keyButton" onclick="uploadSSH('<?php echo $UserId; ?>', '<?php echo $AuthToken; ?>' )">Upload</button>
                    <button class="col keyButton debug" onclick="testSwal()">Test Popup</button>
                    <form id="uploadForm" enctype="multipart/form-data">
                        <input id="keyfile" type="file" style="display: none;"/>
                    </form>
                </div>
                <div class="row copyright">
                    <?php 
                        if (file_exists("/etc/ttyserver/canary")){
                            echo "Canary";
                        }
                    ?>
                    <br>
                    <a href="https://git.corrupt.link/liz/tilde-oauth">View Source on Git</a>
                </div>
            </div>
            <div class="desktopOnly col-4"></div>
        </div>
    </Body>
</HTML>