Skip to content

Commit

Permalink
add recaptcha and update page titles
Browse files Browse the repository at this point in the history
  • Loading branch information
chriskapp committed Nov 25, 2023
1 parent 5cdb023 commit 0ea094b
Show file tree
Hide file tree
Showing 14 changed files with 114 additions and 14 deletions.
12 changes: 7 additions & 5 deletions www/.env
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
APP_URL=http://127.0.0.1/projects/typeapi/www/public
APP_ENV=dev
APP_DEBUG=on
APP_CONNECTION=mysql://root:test1234@localhost/psx
APP_MAILER=native://default
APP_URL="http://127.0.0.1/projects/typeapi/www/public"
APP_ENV="prod"
APP_DEBUG="off"
APP_CONNECTION="mysql://root:test1234@localhost/psx"
APP_MAILER="native://default"
APP_RECAPTCHA_KEY=""
APP_RECAPTCHA_SECRET=""
3 changes: 3 additions & 0 deletions www/configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

return [

'recaptcha_key' => env('APP_RECAPTCHA_KEY')->string(),
'recaptcha_secret' => env('APP_RECAPTCHA_SECRET')->string(),

// The url to the psx public folder (i.e. http://api.acme.com or http://127.0.0.1/psx/public)
'psx_url' => env('APP_URL')->string(),

Expand Down
2 changes: 2 additions & 0 deletions www/resources/container.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,6 @@
$services->load('App\\Controller\\', __DIR__ . '/../src/Controller')
->public();

$services->load('App\\Service\\', __DIR__ . '/../src/Service');

};
12 changes: 9 additions & 3 deletions www/resources/template/generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@
<?php else: ?>
<div class="alert alert-info">This generator gives you access to our reference code generator implementation, you
can enter a TypeAPI specification and select a target output format to generate a fitting client. Please take a look
at the <a href="<?php echo $router->getAbsolutePath([\App\Controller\Ecosystem::class, 'show']); ?>">environment</a>
at the <a href="<?php echo $router->getAbsolutePath([\App\Controller\Ecosystem::class, 'show']); ?>">ecosystem</a>
page to see available code generator services.</div>
<?php endif; ?>
<div class="row">
<div class="col-12">
<form method="POST">
<form method="POST" id="generatorForm">
<div class="mb-3">
<label for="type" class="form-label">Format</label>
<select name="type" id="type" class="form-control">
Expand Down Expand Up @@ -55,7 +55,7 @@
}
}</textarea>
</div>
<input type="submit" class="btn btn-primary" value="Generate">
<button class="g-recaptcha btn btn-primary" data-sitekey="<?php echo $recaptcha_key; ?>" data-callback="onSubmit" data-action="submit">Generate</button>
</form>
</div>
</div>
Expand All @@ -65,4 +65,10 @@
</div>
</div>

<script>
function onSubmit(token) {
document.getElementById("generatorForm").submit();
}
</script>

<?php include __DIR__ . '/inc/footer.php'; ?>
6 changes: 5 additions & 1 deletion www/resources/template/inc/header.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="An OpenAPI alternative to describe REST APIs for type-safe code generation.">
<meta name="keywords" content="OpenAPI, TypeAPI, REST, API, Code-Generation">
<title>TypeAPI</title>
<title><?php echo $title ?? 'TypeAPI'; ?></title>
<link rel="preload" href="<?php echo $base; ?>/css/app.min.css" as="style" />
<link rel="preload" href="<?php echo $base; ?>/js/app.min.js" as="script" />
<link rel="stylesheet" href="<?php echo $base; ?>/css/app.min.css">
<link rel="canonical" href="<?php echo $router->getUrl($method); ?>">
<script async src="<?php echo $base; ?>/js/app.min.js"></script>
<script async src="https://www.googletagmanager.com/gtag/js?id=G-8CL7811MFT"></script>
<?php if (isset($js) && is_array($js)): ?>
<?php foreach ($js as $link): ?><script src="<?php echo $link; ?>"></script>
<?php endforeach; ?>
<?php endif; ?>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
Expand Down
2 changes: 1 addition & 1 deletion www/resources/template/index.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

<?php include __DIR__ . '/inc/header.php'; ?>

<div class="jumbotron" style="background:url('<?php echo $base; ?>/img/header_bg.png');background-size:cover;background-repeat:no-repeat;background-position:top center;background-color:#222;">
<div class="jumbotron" style="background:url('<?php echo $base; ?>/img/header_bg.png');background-size:cover;background-repeat:no-repeat;background-position:top center;background-color:#222;border-radius:0">
<div class="container" style="text-align: center">
<h1 class="display-4 text-white">TypeAPI</h1>
<p class="lead text-white">An OpenAPI alternative to describe REST APIs for type-safe code generation.</p>
Expand Down
3 changes: 3 additions & 0 deletions www/resources/typeschema.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
},
"schema": {
"type": "string"
},
"g-recaptcha-response": {
"type": "string"
}
}
}
Expand Down
1 change: 1 addition & 0 deletions www/src/Controller/Developer.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public function show(): mixed
{
$data = [
'method' => explode('::', __METHOD__),
'title' => 'Developer | TypeAPI',
];

$templateFile = __DIR__ . '/../../resources/template/developer.php';
Expand Down
1 change: 1 addition & 0 deletions www/src/Controller/Ecosystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public function show(): mixed
{
$data = [
'method' => explode('::', __METHOD__),
'title' => 'Ecosystem | TypeAPI',
];

$templateFile = __DIR__ . '/../../resources/template/ecosystem.php';
Expand Down
25 changes: 21 additions & 4 deletions www/src/Controller/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,20 @@
namespace App\Controller;

use App\Model;
use App\Service\CaptchaVerifier;
use PSX\Api\ApiManagerInterface;
use PSX\Api\Attribute\Get;
use PSX\Api\Attribute\Path;
use PSX\Api\Attribute\Post;
use PSX\Api\GeneratorFactory;
use PSX\Api\Parser\TypeAPI;
use PSX\Framework\Config\ConfigInterface;
use PSX\Framework\Config\Directory;
use PSX\Framework\Controller\ControllerAbstract;
use PSX\Framework\Http\Writer\Template;
use PSX\Framework\Loader\ReverseRouter;
use PSX\Http\Environment\HttpResponse;
use PSX\Http\Exception\BadRequestException;
use PSX\Http\Writer\File;
use PSX\Schema\Generator\Code\Chunks;
use PSX\Schema\SchemaManagerInterface;
Expand All @@ -24,13 +27,17 @@ class Generator extends ControllerAbstract
private Directory $directory;
private GeneratorFactory $generatorFactory;
private SchemaManagerInterface $schemaManager;
private CaptchaVerifier $captchaVerifier;
private ConfigInterface $config;

public function __construct(ReverseRouter $reverseRouter, Directory $directory, GeneratorFactory $generatorFactory, SchemaManagerInterface $schemaManager)
public function __construct(ReverseRouter $reverseRouter, Directory $directory, GeneratorFactory $generatorFactory, SchemaManagerInterface $schemaManager, CaptchaVerifier $captchaVerifier, ConfigInterface $config)
{
$this->reverseRouter = $reverseRouter;
$this->directory = $directory;
$this->generatorFactory = $generatorFactory;
$this->schemaManager = $schemaManager;
$this->captchaVerifier = $captchaVerifier;
$this->config = $config;
}

#[Get]
Expand All @@ -40,6 +47,9 @@ public function show(): mixed
$data = [
'types' => $this->generatorFactory->factory()->getPossibleTypes(),
'method' => explode('::', __METHOD__),
'title' => 'SDK Code Generator | TypeAPI',
'js' => ['https://www.google.com/recaptcha/api.js'],
'recaptcha_key' => $this->config->get('recaptcha_key')
];

$templateFile = __DIR__ . '/../../resources/template/generator.php';
Expand All @@ -53,8 +63,12 @@ public function generate(Model\Generate $payload): mixed
$repository = $this->generatorFactory->factory();

try {
$type = $payload->getType() ?? throw new \RuntimeException('Provided no type');
$schema = $payload->getSchema() ?? throw new \RuntimeException('Provided no schema');
if (!$this->captchaVerifier->verify($payload->getGRecaptchaResponse())) {
throw new BadRequestException('Invalid captcha');
}

$type = $payload->getType() ?? throw new BadRequestException('Provided no type');
$schema = $payload->getSchema() ?? throw new BadRequestException('Provided no schema');

$specification = (new TypeAPI($this->schemaManager))->parse($schema);

Expand All @@ -76,7 +90,10 @@ public function generate(Model\Generate $payload): mixed
$data = [
'types' => $repository->getPossibleTypes(),
'method' => explode('::', __METHOD__),
'error' => $e->getMessage()
'title' => 'SDK Code Generator | TypeAPI',
'js' => ['https://www.google.com/recaptcha/api.js'],
'recaptcha_key' => $this->config->get('recaptcha_key'),
'error' => $e->getMessage(),
];

$templateFile = __DIR__ . '/../../resources/template/generator.php';
Expand Down
1 change: 1 addition & 0 deletions www/src/Controller/Index.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public function show(): mixed

$data = [
'method' => explode('::', __METHOD__),
'title' => 'OpenAPI alternative for type-safe code generation | TypeAPI',
'examples' => $examples
];

Expand Down
1 change: 1 addition & 0 deletions www/src/Controller/Specification.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public function show(): mixed
{
$data = [
'method' => explode('::', __METHOD__),
'title' => 'Specification | TypeAPI',
];

$templateFile = __DIR__ . '/../../resources/template/specification.php';
Expand Down
12 changes: 12 additions & 0 deletions www/src/Model/Generate.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@

namespace App\Model;

use PSX\Schema\Attribute\Key;

class Generate implements \JsonSerializable, \PSX\Record\RecordableInterface
{
protected ?string $type = null;
protected ?string $schema = null;
#[Key('g-recaptcha-response')]
protected ?string $gRecaptchaResponse = null;
public function setType(?string $type) : void
{
$this->type = $type;
Expand All @@ -25,12 +28,21 @@ public function getSchema() : ?string
{
return $this->schema;
}
public function setGRecaptchaResponse(?string $gRecaptchaResponse) : void
{
$this->gRecaptchaResponse = $gRecaptchaResponse;
}
public function getGRecaptchaResponse() : ?string
{
return $this->gRecaptchaResponse;
}
public function toRecord() : \PSX\Record\RecordInterface
{
/** @var \PSX\Record\Record<mixed> $record */
$record = new \PSX\Record\Record();
$record->put('type', $this->type);
$record->put('schema', $this->schema);
$record->put('g-recaptcha-response', $this->gRecaptchaResponse);
return $record;
}
public function jsonSerialize() : object
Expand Down
47 changes: 47 additions & 0 deletions www/src/Service/CaptchaVerifier.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace App\Service;

use GuzzleHttp\Client;
use PSX\Framework\Config\ConfigInterface;
use PSX\Json;

class CaptchaVerifier
{
private Client $httpClient;
private string $secret;

public function __construct(ConfigInterface $config)
{
$this->httpClient = new Client();
$this->secret = $config->get('recaptcha_secret');
}

public function verify(?string $recaptchaResponse): bool
{
if (empty($recaptchaResponse)) {
return false;
}

$response = $this->httpClient->post('https://www.google.com/recaptcha/api/siteverify', [
'headers' => [
'User-Agent' => 'typeapi.org'
],
'form_params' => [
'secret' => $this->secret,
'response' => $recaptchaResponse,
'remoteip' => $_SERVER['REMOTE_ADDR'] ?? '',
],
'verify' => false
]);

if ($response->getStatusCode() == 200) {
$data = Json\Parser::decode((string) $response->getBody());
if (isset($data->success) && $data->success === true) {
return true;
}
}

return false;
}
}

0 comments on commit 0ea094b

Please sign in to comment.