Repositories | Polyback | Log in to see private repositories


polyback-website / bcef206a2944792d992fb4d0f10cb8969bd17386 / api/studio/redeem.php

1,699 bytes | parent directory

<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';

// Studio, opened from the website's Edit button, trades its one-time code for a Studio token.
//   POST {"code":".."} -> {"success":true,"token":"..","user":{"id","name"},"placeId":N}

use pizzaboxer\ProjectPolygon\API;
use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Studio;

header("content-type: application/json");
header("Cache-Control: no-store");
if ($_SERVER["REQUEST_METHOD"] !== "POST") API::respond(405, false, "Method Not Allowed");

$body = json_decode(file_get_contents("php://input", false, null, 0, 4096), true);
$code = is_array($body) ? (string) ($body["code"] ?? "") : "";
if (!preg_match('/^[0-9a-f]{64}$/', $code)) API::respond(400, false, "Invalid code");

$hash = hash("sha256", $code);
$row = Database::singleton()->run(
	"SELECT c.*, u.username, u.Banned FROM StudioLaunchCodes c JOIN users u ON u.id = c.UserID
	 WHERE c.CodeHash = :h AND c.Used = 0 AND c.Expires > UNIX_TIMESTAMP()",
	[":h" => $hash]
)->fetch(PDO::FETCH_OBJ);
if (!$row || !empty($row->Banned)) API::respond(401, false, "This link has expired. Click Edit on the website again.");
// single use: only the request that flips Used gets a token
$claimed = Database::singleton()->run("UPDATE StudioLaunchCodes SET Used = 1 WHERE CodeHash = :h AND Used = 0", [":h" => $hash])->rowCount();
if ($claimed !== 1) API::respond(401, false, "This link has already been used");

$token = Studio::CreateToken($row->UserID, "Polyback Studio (website)");
API::respondCustom(["status" => 200, "success" => true, "token" => $token,
	"user" => ["id" => (int) $row->UserID, "name" => $row->username], "placeId" => (int) $row->PlaceID]);