This commit is contained in:
Marcel Pociot
2020-04-24 12:37:31 +02:00
parent 018d778e5f
commit 9ce19f975e
28 changed files with 1160 additions and 91 deletions

2
.gitignore vendored
View File

@@ -3,3 +3,5 @@
/.vscode /.vscode
/.vagrant /.vagrant
.phpunit.result.cache .phpunit.result.cache
expose.php
database/expose.db

View File

@@ -3,6 +3,7 @@
namespace App\Client; namespace App\Client;
use App\Client\Connections\ControlConnection; use App\Client\Connections\ControlConnection;
use App\Logger\CliRequestLogger;
use Ratchet\Client\WebSocket; use Ratchet\Client\WebSocket;
use React\EventLoop\LoopInterface; use React\EventLoop\LoopInterface;
use function Ratchet\Client\connect; use function Ratchet\Client\connect;
@@ -15,16 +16,22 @@ class Client
/** @var Configuration */ /** @var Configuration */
protected $configuration; protected $configuration;
/** @var CliRequestLogger */
protected $logger;
public static $subdomains = []; public static $subdomains = [];
public function __construct(LoopInterface $loop, Configuration $configuration) public function __construct(LoopInterface $loop, Configuration $configuration, CliRequestLogger $logger)
{ {
$this->loop = $loop; $this->loop = $loop;
$this->configuration = $configuration; $this->configuration = $configuration;
$this->logger = $logger;
} }
public function share(string $sharedUrl, array $subdomains = []) public function share(string $sharedUrl, array $subdomains = [])
{ {
$this->logger->info("Sharing http://{$sharedUrl}");
foreach ($subdomains as $subdomain) { foreach ($subdomains as $subdomain) {
$this->connectToServer($sharedUrl, $subdomain); $this->connectToServer($sharedUrl, $subdomain);
} }
@@ -32,7 +39,7 @@ class Client
protected function connectToServer(string $sharedUrl, $subdomain) protected function connectToServer(string $sharedUrl, $subdomain)
{ {
connect("ws://{$this->configuration->host()}:{$this->configuration->port()}/__expose_control__", [], [ connect("ws://{$this->configuration->host()}:{$this->configuration->port()}/__expose_control__?authToken={$this->configuration->authToken()}", [], [
'X-Expose-Control' => 'enabled', 'X-Expose-Control' => 'enabled',
], $this->loop) ], $this->loop)
->then(function (WebSocket $clientConnection) use ($sharedUrl, $subdomain) { ->then(function (WebSocket $clientConnection) use ($sharedUrl, $subdomain) {
@@ -40,8 +47,14 @@ class Client
$connection->authenticate($sharedUrl, $subdomain); $connection->authenticate($sharedUrl, $subdomain);
$connection->on('authenticationFailed', function ($data) {
$this->logger->error("Authentication failed. Please check your authentication token and try again.");
exit(1);
});
$connection->on('authenticated', function ($data) { $connection->on('authenticated', function ($data) {
dump("Connected to http://$data->subdomain.{$this->configuration->host()}:{$this->configuration->port()}"); $this->logger->info("Connected to http://$data->subdomain.{$this->configuration->host()}:{$this->configuration->port()}");
static::$subdomains[] = "$data->subdomain.{$this->configuration->host()}:{$this->configuration->port()}"; static::$subdomains[] = "$data->subdomain.{$this->configuration->host()}:{$this->configuration->port()}";
}); });

View File

@@ -13,13 +13,18 @@ class Configuration
/** @var string|null */ /** @var string|null */
protected $auth; protected $auth;
public function __construct(string $host, int $port, ?string $auth = null) /** @var string|null */
protected $authToken;
public function __construct(string $host, int $port, ?string $auth = null, string $authToken = null)
{ {
$this->host = $host; $this->host = $host;
$this->port = $port; $this->port = $port;
$this->auth = $auth; $this->auth = $auth;
$this->authToken = $authToken;
} }
public function host(): string public function host(): string
@@ -36,4 +41,9 @@ class Configuration
{ {
return $this->port; return $this->port;
} }
public function authToken()
{
return $this->authToken;
}
} }

View File

@@ -34,9 +34,8 @@ class ControlConnection
$this->socket->on('message', function (Message $message) { $this->socket->on('message', function (Message $message) {
$decodedEntry = json_decode($message); $decodedEntry = json_decode($message);
$this->emit($decodedEntry->event ?? '', [$decodedEntry]);
if (method_exists($this, $decodedEntry->event ?? '')) { if (method_exists($this, $decodedEntry->event ?? '')) {
$this->emit($decodedEntry->event, [$decodedEntry]);
call_user_func([$this, $decodedEntry->event], $decodedEntry); call_user_func([$this, $decodedEntry->event], $decodedEntry);
} }
}); });

View File

@@ -27,6 +27,9 @@ class Factory
/** @var string */ /** @var string */
protected $auth = ''; protected $auth = '';
/** @var string */
protected $authToken = '';
/** @var \React\EventLoop\LoopInterface */ /** @var \React\EventLoop\LoopInterface */
protected $loop; protected $loop;
@@ -52,13 +55,20 @@ class Factory
return $this; return $this;
} }
public function setAuth(string $auth) public function setAuth(?string $auth)
{ {
$this->auth = $auth; $this->auth = $auth;
return $this; return $this;
} }
public function setAuthToken(?string $authToken)
{
$this->authToken = $authToken;
return $this;
}
public function setLoop(LoopInterface $loop) public function setLoop(LoopInterface $loop)
{ {
$this->loop = $loop; $this->loop = $loop;
@@ -69,7 +79,7 @@ class Factory
protected function bindConfiguration() protected function bindConfiguration()
{ {
app()->singleton(Configuration::class, function ($app) { app()->singleton(Configuration::class, function ($app) {
return new Configuration($this->host, $this->port, $this->auth); return new Configuration($this->host, $this->port, $this->auth, $this->authToken);
}); });
} }

View File

@@ -47,8 +47,6 @@ class HttpClient
$request = $this->passRequestThroughModifiers(parse_request($requestData), $proxyConnection); $request = $this->passRequestThroughModifiers(parse_request($requestData), $proxyConnection);
dump($this->request->getMethod() . ' ' . $this->request->getUri()->getPath());
transform($request, function ($request) use ($proxyConnection) { transform($request, function ($request) use ($proxyConnection) {
$this->sendRequestToApplication($request, $proxyConnection); $this->sendRequestToApplication($request, $proxyConnection);
}); });

View File

@@ -8,7 +8,7 @@ use React\EventLoop\LoopInterface;
class ServeCommand extends Command class ServeCommand extends Command
{ {
protected $signature = 'serve {host=0.0.0.0} {hostname=localhost}'; protected $signature = 'serve {host=0.0.0.0} {hostname=localhost} {--validateAuthTokens}';
protected $description = 'Start the shaft server'; protected $description = 'Start the shaft server';
@@ -18,6 +18,7 @@ class ServeCommand extends Command
->setLoop(app(LoopInterface::class)) ->setLoop(app(LoopInterface::class))
->setHost($this->argument('host')) ->setHost($this->argument('host'))
->setHostname($this->argument('hostname')) ->setHostname($this->argument('hostname'))
->validateAuthTokens($this->option('validateAuthTokens'))
->createServer() ->createServer()
->run(); ->run();
} }

View File

@@ -3,23 +3,37 @@
namespace App\Commands; namespace App\Commands;
use App\Client\Factory; use App\Client\Factory;
use App\Logger\CliRequestLogger;
use Illuminate\Console\Scheduling\Schedule; use Illuminate\Console\Scheduling\Schedule;
use LaravelZero\Framework\Commands\Command; use LaravelZero\Framework\Commands\Command;
use React\EventLoop\LoopInterface; use React\EventLoop\LoopInterface;
use Symfony\Component\Console\Output\ConsoleOutput;
class ShareCommand extends Command class ShareCommand extends Command
{ {
protected $signature = 'share {host} {--subdomain=} {--auth=}'; protected $signature = 'share {host} {--subdomain=} {--auth=} {--token=}';
protected $description = 'Share a local url with a remote shaft server'; protected $description = 'Share a local url with a remote shaft server';
protected function configureConnectionLogger()
{
app()->bind(CliRequestLogger::class, function () {
return new CliRequestLogger(new ConsoleOutput());
});
return $this;
}
public function handle() public function handle()
{ {
$this->configureConnectionLogger();
(new Factory()) (new Factory())
->setLoop(app(LoopInterface::class)) ->setLoop(app(LoopInterface::class))
// ->setHost('beyond.sh') // TODO: Read from (local/global) config file // ->setHost('beyond.sh') // TODO: Read from (local/global) config file
// ->setPort(8080) // TODO: Read from (local/global) config file // ->setPort(8080) // TODO: Read from (local/global) config file
->setAuth($this->option('auth')) ->setAuth($this->option('auth'))
->setAuthToken($this->option('token'))
->createClient($this->argument('host'), explode(',', $this->option('subdomain'))) ->createClient($this->argument('host'), explode(',', $this->option('subdomain')))
->createHttpServer() ->createHttpServer()
->run(); ->run();

View File

@@ -0,0 +1,17 @@
<?php
namespace App\Commands;
use Illuminate\Console\Command;
class ShareCurrentWorkingDirectoryCommand extends ShareCommand
{
protected $signature = 'share-cwd {host?} {--subdomain=} {--auth=}';
public function handle()
{
$this->input->setArgument('host', basename(getcwd()).'.test');
parent::handle();
}
}

View File

@@ -68,13 +68,21 @@ abstract class PostController extends Controller
protected function createLaravelRequest(ConnectionInterface $connection): Request protected function createLaravelRequest(ConnectionInterface $connection): Request
{ {
try {
parse_str($connection->requestBuffer, $bodyParameters);
} catch (\Throwable $e) {
$bodyParameters = [];
}
$serverRequest = (new ServerRequest( $serverRequest = (new ServerRequest(
$connection->request->getMethod(), $connection->request->getMethod(),
$connection->request->getUri(), $connection->request->getUri(),
$connection->request->getHeaders(), $connection->request->getHeaders(),
$connection->requestBuffer, $connection->requestBuffer,
$connection->request->getProtocolVersion() $connection->request->getProtocolVersion()
))->withQueryParams(QueryParameters::create($connection->request)->all()); ))
->withQueryParams(QueryParameters::create($connection->request)->all())
->withParsedBody($bodyParameters);
return Request::createFromBase((new HttpFoundationFactory)->createRequest($serverRequest)); return Request::createFromBase((new HttpFoundationFactory)->createRequest($serverRequest));
} }

View File

@@ -0,0 +1,55 @@
<?php
namespace App\Logger;
use Illuminate\Console\OutputStyle;
use Illuminate\Support\Collection;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
class CliRequestLogger extends Logger
{
/** @var Table */
protected $table;
/** @var Collection */
protected $requests;
/** @var \Symfony\Component\Console\Output\ConsoleSectionOutput */
protected $section;
public function __construct(ConsoleOutputInterface $consoleOutput)
{
parent::__construct($consoleOutput);
$this->section = $this->output->section();
$this->table = new Table($this->section);
$this->table->setHeaders(['Method', 'URI', 'Response', 'Duration']);
$this->requests = new Collection();
}
public function logRequest(LoggedRequest $loggedRequest)
{
if ($this->requests->has($loggedRequest->id())) {
$this->requests[$loggedRequest->id()] = $loggedRequest;
} else {
$this->requests->prepend($loggedRequest, $loggedRequest->id());
}
$this->requests = $this->requests->slice(0, 10);
$this->section->clear();
$this->table->setRows($this->requests->map(function (LoggedRequest $loggedRequest) {
return [
$loggedRequest->getRequest()->getMethod(),
$loggedRequest->getRequest()->getUri(),
optional($loggedRequest->getResponse())->getStatusCode() . ' ' . optional($loggedRequest->getResponse())->getReasonPhrase(),
$loggedRequest->getDuration().'ms'
];
})->toArray());
$this->table->render();
}
}

View File

@@ -56,7 +56,7 @@ class LoggedRequest implements \JsonSerializable
$data = [ $data = [
'id' => $this->id, 'id' => $this->id,
'performed_at' => $this->startTime->toDateTimeString(), 'performed_at' => $this->startTime->toDateTimeString(),
'duration' => $this->startTime->diffInMilliseconds($this->stopTime, false), 'duration' => $this->getDuration(),
'subdomain' => $this->detectSubdomain(), 'subdomain' => $this->detectSubdomain(),
'request' => [ 'request' => [
'raw' => $this->isBinary($this->rawRequest) ? 'BINARY' : $this->rawRequest, 'raw' => $this->isBinary($this->rawRequest) ? 'BINARY' : $this->rawRequest,
@@ -132,6 +132,11 @@ class LoggedRequest implements \JsonSerializable
return $this->rawRequest; return $this->rawRequest;
} }
public function getResponse()
{
return $this->parsedResponse;
}
protected function getResponseBody() protected function getResponseBody()
{ {
return \Laminas\Http\Response::fromString($this->rawResponse)->getBody(); return \Laminas\Http\Response::fromString($this->rawResponse)->getBody();
@@ -198,4 +203,9 @@ class LoggedRequest implements \JsonSerializable
{ {
return Arr::get($this->parsedRequest->getHeaders()->toArray(), 'X-Expose-Request-ID', (string)Str::uuid()); return Arr::get($this->parsedRequest->getHeaders()->toArray(), 'X-Expose-Request-ID', (string)Str::uuid());
} }
public function getDuration()
{
return $this->startTime->diffInMilliseconds($this->stopTime, false);
}
} }

View File

@@ -2,64 +2,21 @@
namespace App\Logger; namespace App\Logger;
use Illuminate\Console\Concerns\InteractsWithIO;
use Illuminate\Console\OutputStyle;
use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
class Logger class Logger
{ {
/** @var \Symfony\Component\Console\Output\OutputInterface */ use InteractsWithIO;
protected $consoleOutput;
/** @var bool */ /** @var ConsoleOutputInterface */
protected $enabled = false; protected $output;
/** @var bool */ public function __construct(ConsoleOutputInterface $consoleOutput)
protected $verbose = false;
public function __construct(OutputInterface $consoleOutput)
{ {
$this->consoleOutput = $consoleOutput; $this->output = $consoleOutput;
}
public function enable($enabled = true)
{
$this->enabled = $enabled;
return $this;
}
public function verbose($verbose = false)
{
$this->verbose = $verbose;
return $this;
}
protected function info(string $message)
{
$this->line($message, 'info');
}
protected function warn(string $message)
{
if (! $this->consoleOutput->getFormatter()->hasStyle('warning')) {
$style = new OutputFormatterStyle('yellow');
$this->consoleOutput->getFormatter()->setStyle('warning', $style);
}
$this->line($message, 'warning');
}
protected function error(string $message)
{
$this->line($message, 'error');
}
protected function line(string $message, string $style)
{
$styled = $style ? "<$style>$message</$style>" : $message;
$this->consoleOutput->writeln($styled);
} }
} }

View File

@@ -10,12 +10,19 @@ use function GuzzleHttp\Psr7\stream_for;
class RequestLogger class RequestLogger
{ {
/** @var array */
protected $requests = []; protected $requests = [];
/** @var array */
protected $responses = []; protected $responses = [];
public function __construct(Browser $browser) /** @var CliRequestLogger */
protected $cliRequestLogger;
public function __construct(Browser $browser, CliRequestLogger $cliRequestLogger)
{ {
$this->client = $browser; $this->client = $browser;
$this->cliRequestLogger = $cliRequestLogger;
} }
public function findLoggedRequest(string $id): ?LoggedRequest public function findLoggedRequest(string $id): ?LoggedRequest
@@ -27,10 +34,14 @@ class RequestLogger
public function logRequest(string $rawRequest, Request $request) public function logRequest(string $rawRequest, Request $request)
{ {
array_unshift($this->requests, new LoggedRequest($rawRequest, $request)); $loggedRequest = new LoggedRequest($rawRequest, $request);
array_unshift($this->requests, $loggedRequest);
$this->requests = array_slice($this->requests, 0, 10); $this->requests = array_slice($this->requests, 0, 10);
$this->cliRequestLogger->logRequest($loggedRequest);
$this->pushLogs(); $this->pushLogs();
} }
@@ -42,6 +53,8 @@ class RequestLogger
if ($loggedRequest) { if ($loggedRequest) {
$loggedRequest->setResponse($rawResponse, Response::fromString($rawResponse)); $loggedRequest->setResponse($rawResponse, Response::fromString($rawResponse));
$this->cliRequestLogger->logRequest($loggedRequest);
$this->pushLogs(); $this->pushLogs();
} }
} }

View File

@@ -2,6 +2,7 @@
namespace App\Providers; namespace App\Providers;
use App\Logger\CliRequestLogger;
use App\Logger\RequestLogger; use App\Logger\RequestLogger;
use Clue\React\Buzz\Browser; use Clue\React\Buzz\Browser;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
@@ -21,10 +22,8 @@ class AppServiceProvider extends ServiceProvider
return LoopFactory::create(); return LoopFactory::create();
}); });
$this->app->singleton(RequestLogger::class, function () { $this->app->singleton(RequestLogger::class, function ($app) {
$browser = new Browser(app(LoopInterface::class)); return new RequestLogger($app->make(Browser::class), $app->make(CliRequestLogger::class));
return new RequestLogger($browser);
}); });
} }
} }

View File

@@ -6,15 +6,21 @@ use App\Contracts\ConnectionManager as ConnectionManagerContract;
use App\Contracts\SubdomainGenerator; use App\Contracts\SubdomainGenerator;
use App\HttpServer\HttpServer; use App\HttpServer\HttpServer;
use App\Server\Connections\ConnectionManager; use App\Server\Connections\ConnectionManager;
use App\Server\Http\Controllers\Admin\DeleteUsersController;
use App\Server\Http\Controllers\Admin\ListUsersController;
use App\Server\Http\Controllers\Admin\StoreUsersController;
use App\Server\Http\Controllers\ControlMessageController; use App\Server\Http\Controllers\ControlMessageController;
use App\Server\Http\Controllers\TunnelMessageController; use App\Server\Http\Controllers\TunnelMessageController;
use App\Server\SubdomainGenerator\RandomSubdomainGenerator; use App\Server\SubdomainGenerator\RandomSubdomainGenerator;
use Clue\React\SQLite\DatabaseInterface;
use Ratchet\Http\Router; use Ratchet\Http\Router;
use Ratchet\Server\IoServer; use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer; use Ratchet\WebSocket\WsServer;
use React\Socket\Server; use React\Socket\Server;
use React\EventLoop\LoopInterface; use React\EventLoop\LoopInterface;
use React\EventLoop\Factory as LoopFactory; use React\EventLoop\Factory as LoopFactory;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route; use Symfony\Component\Routing\Route;
@@ -34,9 +40,13 @@ class Factory
/** @var \React\EventLoop\LoopInterface */ /** @var \React\EventLoop\LoopInterface */
protected $loop; protected $loop;
/** @var RouteCollection */
protected $routes;
public function __construct() public function __construct()
{ {
$this->loop = LoopFactory::create(); $this->loop = LoopFactory::create();
$this->routes = new RouteCollection();
} }
public function setHost(string $host) public function setHost(string $host)
@@ -67,25 +77,42 @@ class Factory
return $this; return $this;
} }
protected function getRoutes(): RouteCollection protected function addExposeRoutes()
{ {
$routes = new RouteCollection(); $this->routes->add('control',
$routes->add('control',
new Route('/__expose_control__', [ new Route('/__expose_control__', [
'_controller' => new WsServer(app(ControlMessageController::class)) '_controller' => new WsServer(app(ControlMessageController::class))
], [], [], null, [], [] ], [], [], null, [], []
) )
); );
$routes->add('tunnel', $this->routes->add('tunnel',
new Route('/{__catchall__}', [ new Route('/{__catchall__}', [
'_controller' => app(TunnelMessageController::class), '_controller' => app(TunnelMessageController::class),
], [ ], [
'__catchall__' => '.*' '__catchall__' => '.*'
])); ]));
}
return $routes; protected function addAdminRoutes()
{
$this->routes->add('admin.users.index',
new Route('/expose/users', [
'_controller' => app(ListUsersController::class),
], [], [], null, [], ['GET'])
);
$this->routes->add('admin.users.store',
new Route('/expose/users', [
'_controller' => app(StoreUsersController::class),
], [], [], null, [], ['POST'])
);
$this->routes->add('admin.users.delete',
new Route('/expose/users/delete/{id}', [
'_controller' => app(DeleteUsersController::class),
], [], [], null, [], ['DELETE'])
);
} }
protected function bindConfiguration() protected function bindConfiguration()
@@ -117,9 +144,17 @@ class Factory
$this->bindSubdomainGenerator(); $this->bindSubdomainGenerator();
$this->bindDatabase();
$this->ensureDatabaseIsInitialized();
$this->bindConnectionManager(); $this->bindConnectionManager();
$urlMatcher = new UrlMatcher($this->getRoutes(), new RequestContext); $this->addAdminRoutes();
$this->addExposeRoutes();
$urlMatcher = new UrlMatcher($this->routes, new RequestContext);
$router = new Router($urlMatcher); $router = new Router($urlMatcher);
@@ -128,4 +163,36 @@ class Factory
return new IoServer($http, $socket, $this->loop); return new IoServer($http, $socket, $this->loop);
} }
protected function bindDatabase()
{
app()->singleton(DatabaseInterface::class, function() {
$factory = new \Clue\React\SQLite\Factory($this->loop);
return $factory->openLazy(base_path('database/expose.db'));
});
}
protected function ensureDatabaseIsInitialized()
{
/** @var DatabaseInterface $db */
$db = app(DatabaseInterface::class);
$migrations = (new Finder())
->files()
->ignoreDotFiles(true)
->in(database_path('migrations'))
->name('*.sql');
/** @var SplFileInfo $migration */
foreach ($migrations as $migration) {
$db->exec($migration->getContents());
}
}
public function validateAuthTokens(bool $validate)
{
dump($validate);
return $this;
}
} }

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Server\Http\Controllers\Admin;
use App\HttpServer\Controllers\PostController;
use Clue\React\SQLite\DatabaseInterface;
use Clue\React\SQLite\Result;
use GuzzleHttp\Psr7\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Ratchet\ConnectionInterface;
use Twig\Environment;
use Twig\Loader\ArrayLoader;
use function GuzzleHttp\Psr7\str;
use function GuzzleHttp\Psr7\stream_for;
class DeleteUsersController extends PostController
{
protected $keepConnectionOpen = true;
/** @var DatabaseInterface */
protected $database;
public function __construct(DatabaseInterface $database)
{
$this->database = $database;
}
public function handle(Request $request, ConnectionInterface $httpConnection)
{
$this->database->query("DELETE FROM users WHERE id = :id", ['id' => $request->id])
->then(function (Result $result) use ($httpConnection) {
$httpConnection->send(respond_json(['deleted' => true], 200));
$httpConnection->close();
});
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace App\Server\Http\Controllers\Admin;
use App\HttpServer\Controllers\PostController;
use Clue\React\SQLite\DatabaseInterface;
use Clue\React\SQLite\Result;
use GuzzleHttp\Psr7\Response;
use Illuminate\Http\Request;
use Ratchet\ConnectionInterface;
use Twig\Environment;
use Twig\Loader\ArrayLoader;
use function GuzzleHttp\Psr7\str;
use function GuzzleHttp\Psr7\stream_for;
class ListUsersController extends PostController
{
protected $keepConnectionOpen = true;
/** @var DatabaseInterface */
protected $database;
public function __construct(DatabaseInterface $database)
{
$this->database = $database;
}
public function handle(Request $request, ConnectionInterface $httpConnection)
{
$this->database->query('SELECT * FROM users ORDER by created_at DESC')->then(function (Result $result) use ($httpConnection) {
$httpConnection->send(
respond_html($this->getView(['users' => $result->rows]))
);
$httpConnection->close();
}, function (\Exception $exception) use ($httpConnection) {
$httpConnection->send(respond_html('Something went wrong: '.$exception->getMessage(), 500));
$httpConnection->close();
});
}
protected function getView(array $data)
{
$twig = new Environment(
new ArrayLoader([
'template' => file_get_contents(base_path('resources/views/admin/users/index.twig')),
])
);
return stream_for($twig->render('template', $data));
}
}

View File

@@ -0,0 +1,62 @@
<?php
namespace App\Server\Http\Controllers\Admin;
use App\HttpServer\Controllers\PostController;
use Clue\React\SQLite\DatabaseInterface;
use Clue\React\SQLite\Result;
use GuzzleHttp\Psr7\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Ratchet\ConnectionInterface;
use Twig\Environment;
use Twig\Loader\ArrayLoader;
use function GuzzleHttp\Psr7\str;
use function GuzzleHttp\Psr7\stream_for;
class StoreUsersController extends PostController
{
protected $keepConnectionOpen = true;
/** @var DatabaseInterface */
protected $database;
public function __construct(DatabaseInterface $database)
{
$this->database = $database;
}
public function handle(Request $request, ConnectionInterface $httpConnection)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
], [
'required' => 'The :attribute field is required.',
]);
if ($validator->fails()) {
$httpConnection->send(respond_json(['errors' => $validator->getMessageBag()], 401));
$httpConnection->close();
return;
}
$insertData = [
'name' => $request->get('name'),
'auth_token' => (string)Str::uuid()
];
$this->database->query("
INSERT INTO users (name, auth_token, created_at)
VALUES (:name, :auth_token, DATETIME('now'))
", $insertData)
->then(function (Result $result) use ($httpConnection) {
$this->database->query("SELECT * FROM users WHERE id = :id", ['id' => $result->insertId])
->then(function (Result $result) use ($httpConnection) {
$httpConnection->send(respond_json(['user' => $result->rows[0]], 200));
$httpConnection->close();
});
});
}
}

View File

@@ -3,6 +3,9 @@
namespace App\Server\Http\Controllers; namespace App\Server\Http\Controllers;
use App\Contracts\ConnectionManager; use App\Contracts\ConnectionManager;
use App\HttpServer\QueryParameters;
use Clue\React\SQLite\DatabaseInterface;
use Clue\React\SQLite\Result;
use stdClass; use stdClass;
use Ratchet\ConnectionInterface; use Ratchet\ConnectionInterface;
use Ratchet\MessageComponentInterface; use Ratchet\MessageComponentInterface;
@@ -13,9 +16,21 @@ class ControlMessageController implements MessageComponentInterface
/** @var ConnectionManager */ /** @var ConnectionManager */
protected $connectionManager; protected $connectionManager;
public function __construct(ConnectionManager $connectionManager) /** @var DatabaseInterface */
protected $database;
public function __construct(ConnectionManager $connectionManager, DatabaseInterface $database)
{ {
$this->connectionManager = $connectionManager; $this->connectionManager = $connectionManager;
$this->database = $database;
}
/**
* @inheritDoc
*/
function onOpen(ConnectionInterface $connection)
{
$this->verifyAuthToken($connection);
} }
/** /**
@@ -80,14 +95,6 @@ class ControlMessageController implements MessageComponentInterface
]); ]);
} }
/**
* @inheritDoc
*/
function onOpen(ConnectionInterface $conn)
{
//
}
/** /**
* @inheritDoc * @inheritDoc
*/ */
@@ -95,4 +102,21 @@ class ControlMessageController implements MessageComponentInterface
{ {
// //
} }
protected function verifyAuthToken(ConnectionInterface $connection)
{
$authToken = QueryParameters::create($connection->httpRequest)->get('authToken');
$this->database
->query("SELECT * FROM users WHERE auth_token = :token", ['token' => $authToken])
->then(function (Result $result) use ($connection) {
if (count($result->rows) === 0) {
$connection->send(json_encode([
'event' => 'authenticationFailed',
'data' => []
]));
$connection->close();
}
});
}
} }

27
app/helpers.php Normal file
View File

@@ -0,0 +1,27 @@
<?php
use GuzzleHttp\Psr7\Response;
use function GuzzleHttp\Psr7\str;
function expose_view_path(string $path = '')
{
return base_path('resources/views/' . $path);
}
function respond_json($responseData, int $statusCode = 200)
{
return str(new Response(
$statusCode,
['Content-Type' => 'application/json'],
json_encode($responseData)
));
}
function respond_html(string $html, int $statusCode = 200)
{
return str(new Response(
$statusCode,
['Content-Type' => 'text/html'],
$html
));
}

View File

@@ -21,10 +21,12 @@
"bfunky/http-parser": "^2.2", "bfunky/http-parser": "^2.2",
"cboden/ratchet": "^0.4.2", "cboden/ratchet": "^0.4.2",
"clue/buzz-react": "^2.7", "clue/buzz-react": "^2.7",
"clue/reactphp-sqlite": "^1.0",
"guzzlehttp/guzzle": "^6.5", "guzzlehttp/guzzle": "^6.5",
"guzzlehttp/psr7": "dev-master as 1.6.1", "guzzlehttp/psr7": "dev-master as 1.6.1",
"illuminate/http": "5.8.*|^6.0|^7.0", "illuminate/http": "5.8.*|^6.0|^7.0",
"illuminate/pipeline": "^7.6", "illuminate/pipeline": "^7.6",
"illuminate/validation": "^7.7",
"laminas/laminas-http": "^2.11", "laminas/laminas-http": "^2.11",
"laravel-zero/framework": "^7.0", "laravel-zero/framework": "^7.0",
"namshi/cuzzle": "^2.0", "namshi/cuzzle": "^2.0",
@@ -34,7 +36,8 @@
"riverline/multipart-parser": "^2.0", "riverline/multipart-parser": "^2.0",
"symfony/expression-language": "^5.0", "symfony/expression-language": "^5.0",
"symfony/http-kernel": "^4.0|^5.0", "symfony/http-kernel": "^4.0|^5.0",
"symfony/psr-http-message-bridge": "^2.0" "symfony/psr-http-message-bridge": "^2.0",
"twig/twig": "^3.0"
}, },
"require-dev": { "require-dev": {
"mockery/mockery": "^1.3.1", "mockery/mockery": "^1.3.1",
@@ -43,7 +46,10 @@
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"App\\": "app/" "App\\": "app/"
} },
"files": [
"app/helpers.php"
]
}, },
"autoload-dev": { "autoload-dev": {
"psr-4": { "psr-4": {

428
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "fdb4509b6b8b8d83aeaef0e26caa1837", "content-hash": "eb16eacae0b922bc590c0093325a423f",
"packages": [ "packages": [
{ {
"name": "bfunky/http-parser", "name": "bfunky/http-parser",
@@ -167,6 +167,108 @@
], ],
"time": "2020-02-26T12:05:32+00:00" "time": "2020-02-26T12:05:32+00:00"
}, },
{
"name": "clue/ndjson-react",
"version": "v1.1.0",
"source": {
"type": "git",
"url": "https://github.com/clue/reactphp-ndjson.git",
"reference": "767ec9543945802b5766fab0da4520bf20626f66"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/clue/reactphp-ndjson/zipball/767ec9543945802b5766fab0da4520bf20626f66",
"reference": "767ec9543945802b5766fab0da4520bf20626f66",
"shasum": ""
},
"require": {
"php": ">=5.3",
"react/stream": "^1.0 || ^0.7 || ^0.6"
},
"require-dev": {
"phpunit/phpunit": "^7.0 || ^6.0 || ^5.7 || ^4.8.35",
"react/event-loop": "^1.0 || ^0.5 || ^0.4 || ^0.3"
},
"type": "library",
"autoload": {
"psr-4": {
"Clue\\React\\NDJson\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Christian Lück",
"email": "christian@clue.engineering"
}
],
"description": "Streaming newline-delimited JSON (NDJSON) parser and encoder for ReactPHP.",
"homepage": "https://github.com/clue/reactphp-ndjson",
"keywords": [
"NDJSON",
"json",
"jsonlines",
"newline",
"reactphp",
"streaming"
],
"time": "2020-02-04T11:48:52+00:00"
},
{
"name": "clue/reactphp-sqlite",
"version": "v1.0.1",
"source": {
"type": "git",
"url": "https://github.com/clue/reactphp-sqlite.git",
"reference": "8c7b89db764129275e22dc883b95c1e8c726332d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/clue/reactphp-sqlite/zipball/8c7b89db764129275e22dc883b95c1e8c726332d",
"reference": "8c7b89db764129275e22dc883b95c1e8c726332d",
"shasum": ""
},
"require": {
"clue/ndjson-react": "^1.0",
"ext-sqlite3": "*",
"php": ">=5.4",
"react/child-process": "^0.6",
"react/event-loop": "^1.0 || ^0.5 || ^0.4 || ^0.3",
"react/promise": "^2.7 || ^1.2.1"
},
"require-dev": {
"phpunit/phpunit": "^7.0 || ^6.0 || ^5.7 || ^4.8.35"
},
"type": "library",
"autoload": {
"psr-4": {
"Clue\\React\\SQLite\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Christian Lück",
"email": "christian@lueck.tv"
}
],
"description": "Async SQLite database, lightweight non-blocking process wrapper around file-based database extension (ext-sqlite3), built on top of ReactPHP.",
"homepage": "https://github.com/clue/reactphp-sqlite",
"keywords": [
"async",
"database",
"non-blocking",
"reactphp",
"sqlite"
],
"time": "2019-05-17T11:02:20+00:00"
},
{ {
"name": "container-interop/container-interop", "name": "container-interop/container-interop",
"version": "1.2.0", "version": "1.2.0",
@@ -266,6 +368,68 @@
], ],
"time": "2019-10-30T19:59:35+00:00" "time": "2019-10-30T19:59:35+00:00"
}, },
{
"name": "doctrine/lexer",
"version": "1.2.0",
"source": {
"type": "git",
"url": "https://github.com/doctrine/lexer.git",
"reference": "5242d66dbeb21a30dd8a3e66bf7a73b66e05e1f6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/lexer/zipball/5242d66dbeb21a30dd8a3e66bf7a73b66e05e1f6",
"reference": "5242d66dbeb21a30dd8a3e66bf7a73b66e05e1f6",
"shasum": ""
},
"require": {
"php": "^7.2"
},
"require-dev": {
"doctrine/coding-standard": "^6.0",
"phpstan/phpstan": "^0.11.8",
"phpunit/phpunit": "^8.2"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.2.x-dev"
}
},
"autoload": {
"psr-4": {
"Doctrine\\Common\\Lexer\\": "lib/Doctrine/Common/Lexer"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Guilherme Blanco",
"email": "guilhermeblanco@gmail.com"
},
{
"name": "Roman Borschel",
"email": "roman@code-factory.org"
},
{
"name": "Johannes Schmitt",
"email": "schmittjoh@gmail.com"
}
],
"description": "PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.",
"homepage": "https://www.doctrine-project.org/projects/lexer.html",
"keywords": [
"annotations",
"docblock",
"lexer",
"parser",
"php"
],
"time": "2019-10-30T14:39:59+00:00"
},
{ {
"name": "dragonmantank/cron-expression", "name": "dragonmantank/cron-expression",
"version": "v2.3.0", "version": "v2.3.0",
@@ -320,6 +484,64 @@
], ],
"time": "2019-03-31T00:38:28+00:00" "time": "2019-03-31T00:38:28+00:00"
}, },
{
"name": "egulias/email-validator",
"version": "2.1.17",
"source": {
"type": "git",
"url": "https://github.com/egulias/EmailValidator.git",
"reference": "ade6887fd9bd74177769645ab5c474824f8a418a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/egulias/EmailValidator/zipball/ade6887fd9bd74177769645ab5c474824f8a418a",
"reference": "ade6887fd9bd74177769645ab5c474824f8a418a",
"shasum": ""
},
"require": {
"doctrine/lexer": "^1.0.1",
"php": ">=5.5",
"symfony/polyfill-intl-idn": "^1.10"
},
"require-dev": {
"dominicsayers/isemail": "^3.0.7",
"phpunit/phpunit": "^4.8.36|^7.5.15",
"satooshi/php-coveralls": "^1.0.1"
},
"suggest": {
"ext-intl": "PHP Internationalization Libraries are required to use the SpoofChecking validation"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.1.x-dev"
}
},
"autoload": {
"psr-4": {
"Egulias\\EmailValidator\\": "EmailValidator"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Eduardo Gulias Davis"
}
],
"description": "A library for validating emails against several RFCs",
"homepage": "https://github.com/egulias/EmailValidator",
"keywords": [
"email",
"emailvalidation",
"emailvalidator",
"validation",
"validator"
],
"time": "2020-02-13T22:36:52+00:00"
},
{ {
"name": "evenement/evenement", "name": "evenement/evenement",
"version": "v3.0.1", "version": "v3.0.1",
@@ -1260,6 +1482,105 @@
"homepage": "https://laravel.com", "homepage": "https://laravel.com",
"time": "2020-04-16T17:12:54+00:00" "time": "2020-04-16T17:12:54+00:00"
}, },
{
"name": "illuminate/translation",
"version": "v7.7.1",
"source": {
"type": "git",
"url": "https://github.com/illuminate/translation.git",
"reference": "74c6c0c15efc2a3e1a7e8b893dcbe68007467ea6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/illuminate/translation/zipball/74c6c0c15efc2a3e1a7e8b893dcbe68007467ea6",
"reference": "74c6c0c15efc2a3e1a7e8b893dcbe68007467ea6",
"shasum": ""
},
"require": {
"ext-json": "*",
"illuminate/contracts": "^7.0",
"illuminate/filesystem": "^7.0",
"illuminate/support": "^7.0",
"php": "^7.2.5"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "7.x-dev"
}
},
"autoload": {
"psr-4": {
"Illuminate\\Translation\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"description": "The Illuminate Translation package.",
"homepage": "https://laravel.com",
"time": "2020-04-15T20:57:47+00:00"
},
{
"name": "illuminate/validation",
"version": "v7.7.1",
"source": {
"type": "git",
"url": "https://github.com/illuminate/validation.git",
"reference": "99377aec3b5a2c2184d99de3dd7c8fb675e5a4ef"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/illuminate/validation/zipball/99377aec3b5a2c2184d99de3dd7c8fb675e5a4ef",
"reference": "99377aec3b5a2c2184d99de3dd7c8fb675e5a4ef",
"shasum": ""
},
"require": {
"egulias/email-validator": "^2.1.10",
"ext-json": "*",
"illuminate/container": "^7.0",
"illuminate/contracts": "^7.0",
"illuminate/support": "^7.0",
"illuminate/translation": "^7.0",
"php": "^7.2.5",
"symfony/http-foundation": "^5.0",
"symfony/mime": "^5.0"
},
"suggest": {
"illuminate/database": "Required to use the database presence verifier (^7.0)."
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "7.x-dev"
}
},
"autoload": {
"psr-4": {
"Illuminate\\Validation\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"description": "The Illuminate Validation package.",
"homepage": "https://laravel.com",
"time": "2020-04-19T19:55:49+00:00"
},
{ {
"name": "jolicode/jolinotif", "name": "jolicode/jolinotif",
"version": "v2.1.0", "version": "v2.1.0",
@@ -3101,6 +3422,49 @@
], ],
"time": "2019-07-11T13:45:28+00:00" "time": "2019-07-11T13:45:28+00:00"
}, },
{
"name": "react/child-process",
"version": "v0.6.1",
"source": {
"type": "git",
"url": "https://github.com/reactphp/child-process.git",
"reference": "6895afa583d51dc10a4b9e93cd3bce17b3b77ac3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/reactphp/child-process/zipball/6895afa583d51dc10a4b9e93cd3bce17b3b77ac3",
"reference": "6895afa583d51dc10a4b9e93cd3bce17b3b77ac3",
"shasum": ""
},
"require": {
"evenement/evenement": "^3.0 || ^2.0 || ^1.0",
"php": ">=5.3.0",
"react/event-loop": "^1.0 || ^0.5 || ^0.4 || ^0.3.5",
"react/stream": "^1.0 || ^0.7.6"
},
"require-dev": {
"phpunit/phpunit": "^7.0 || ^6.4 || ^5.7 || ^4.8.35",
"react/socket": "^1.0",
"sebastian/environment": "^3.0 || ^2.0 || ^1.0"
},
"type": "library",
"autoload": {
"psr-4": {
"React\\ChildProcess\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "Event-driven library for executing child processes with ReactPHP.",
"keywords": [
"event-driven",
"process",
"reactphp"
],
"time": "2019-02-15T13:48:16+00:00"
},
{ {
"name": "react/dns", "name": "react/dns",
"version": "v1.2.0", "version": "v1.2.0",
@@ -5107,6 +5471,68 @@
], ],
"time": "2020-03-27T16:56:45+00:00" "time": "2020-03-27T16:56:45+00:00"
}, },
{
"name": "twig/twig",
"version": "v3.0.3",
"source": {
"type": "git",
"url": "https://github.com/twigphp/Twig.git",
"reference": "3b88ccd180a6b61ebb517aea3b1a8906762a1dc2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/twigphp/Twig/zipball/3b88ccd180a6b61ebb517aea3b1a8906762a1dc2",
"reference": "3b88ccd180a6b61ebb517aea3b1a8906762a1dc2",
"shasum": ""
},
"require": {
"php": "^7.2.5",
"symfony/polyfill-ctype": "^1.8",
"symfony/polyfill-mbstring": "^1.3"
},
"require-dev": {
"psr/container": "^1.0",
"symfony/phpunit-bridge": "^4.4|^5.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
}
},
"autoload": {
"psr-4": {
"Twig\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com",
"homepage": "http://fabien.potencier.org",
"role": "Lead Developer"
},
{
"name": "Twig Team",
"role": "Contributors"
},
{
"name": "Armin Ronacher",
"email": "armin.ronacher@active-4.com",
"role": "Project Founder"
}
],
"description": "Twig, the flexible, fast, and secure template language for PHP",
"homepage": "https://twig.symfony.com",
"keywords": [
"templating"
],
"time": "2020-02-11T15:33:47+00:00"
},
{ {
"name": "vlucas/phpdotenv", "name": "vlucas/phpdotenv",
"version": "v4.1.4", "version": "v4.1.4",

View File

@@ -55,6 +55,8 @@ return [
'providers' => [ 'providers' => [
App\Providers\AppServiceProvider::class, App\Providers\AppServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
], ],
]; ];

View File

@@ -13,7 +13,7 @@ return [
| |
*/ */
'default' => NunoMaduro\LaravelConsoleSummary\SummaryCommand::class, 'default' => \App\Commands\ShareCurrentWorkingDirectoryCommand::class,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@@ -60,6 +60,7 @@ return [
Illuminate\Console\Scheduling\ScheduleRunCommand::class, Illuminate\Console\Scheduling\ScheduleRunCommand::class,
Illuminate\Console\Scheduling\ScheduleFinishCommand::class, Illuminate\Console\Scheduling\ScheduleFinishCommand::class,
Illuminate\Foundation\Console\VendorPublishCommand::class, Illuminate\Foundation\Console\VendorPublishCommand::class,
\App\Commands\ShareCurrentWorkingDirectoryCommand::class,
], ],
/* /*

View File

@@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name STRING NOT NULL,
auth_token STRING,
created_at DATETIME,
updated_at DATETIME
)

12
nodemon.json Normal file
View File

@@ -0,0 +1,12 @@
{
"verbose": false,
"ignore": [
".git",
".idea"
],
"execMap": {
"php": "php"
},
"restartable": "r",
"ext": "php"
}

View File

@@ -0,0 +1,238 @@
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tailwindcss/ui@latest/dist/tailwind-ui.min.css">
</head>
<body>
<div class="min-h-screen bg-white" id="app">
<nav class="bg-white border-b border-gray-200">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex">
<div class="flex-shrink-0 flex items-center font-bold">
Expose
</div>
<div class="hidden sm:-my-px sm:ml-6 sm:flex">
<a href="#"
class="inline-flex items-center px-1 pt-1 border-b-2 border-indigo-500 text-sm font-medium leading-5 text-gray-900 focus:outline-none focus:border-indigo-700 transition duration-150 ease-in-out">
Users
</a>
<a href="#"
class="ml-8 inline-flex items-center px-1 pt-1 border-b-2 border-transparent text-sm font-medium leading-5 text-gray-500 hover:text-gray-700 hover:border-gray-300 focus:outline-none focus:text-gray-700 focus:border-gray-300 transition duration-150 ease-in-out">
Shared sites
</a>
<a href="#"
class="ml-8 inline-flex items-center px-1 pt-1 border-b-2 border-transparent text-sm font-medium leading-5 text-gray-500 hover:text-gray-700 hover:border-gray-300 focus:outline-none focus:text-gray-700 focus:border-gray-300 transition duration-150 ease-in-out">
Settings
</a>
</div>
</div>
<div class="-mr-2 flex items-center sm:hidden">
<!-- Mobile menu button -->
<button
class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-500 transition duration-150 ease-in-out">
<!-- Menu open: "hidden", Menu closed: "block" -->
<svg class="block h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 6h16M4 12h16M4 18h16"/>
</svg>
<!-- Menu open: "block", Menu closed: "hidden" -->
<svg class="hidden h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M6 18L18 6M6 6l12 12"/>
</svg>
</button>
</div>
</div>
</div>
<!--
Mobile menu, toggle classes based on menu state.
Open: "block", closed: "hidden"
-->
<div class="hidden sm:hidden">
<div class="pt-2 pb-3">
<a href="#"
class="block pl-3 pr-4 py-2 border-l-4 border-indigo-500 text-base font-medium text-indigo-700 bg-indigo-50 focus:outline-none focus:text-indigo-800 focus:bg-indigo-100 focus:border-indigo-700 transition duration-150 ease-in-out">Dashboard</a>
<a href="#"
class="mt-1 block pl-3 pr-4 py-2 border-l-4 border-transparent text-base font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-50 hover:border-gray-300 focus:outline-none focus:text-gray-800 focus:bg-gray-50 focus:border-gray-300 transition duration-150 ease-in-out">Team</a>
<a href="#"
class="mt-1 block pl-3 pr-4 py-2 border-l-4 border-transparent text-base font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-50 hover:border-gray-300 focus:outline-none focus:text-gray-800 focus:bg-gray-50 focus:border-gray-300 transition duration-150 ease-in-out">Projects</a>
<a href="#"
class="mt-1 block pl-3 pr-4 py-2 border-l-4 border-transparent text-base font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-50 hover:border-gray-300 focus:outline-none focus:text-gray-800 focus:bg-gray-50 focus:border-gray-300 transition duration-150 ease-in-out">Calendar</a>
</div>
<div class="pt-4 pb-3 border-t border-gray-200">
<div class="flex items-center px-4">
<div class="flex-shrink-0">
<img class="h-10 w-10 rounded-full"
src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80"
alt=""/>
</div>
<div class="ml-3">
<div class="text-base font-medium leading-6 text-gray-800">Tom Cook</div>
<div class="text-sm font-medium leading-5 text-gray-500">tom@example.com</div>
</div>
</div>
<div class="mt-3" role="menu" aria-orientation="vertical" aria-labelledby="user-menu">
<a href="#"
class="block px-4 py-2 text-base font-medium text-gray-500 hover:text-gray-800 hover:bg-gray-100 focus:outline-none focus:text-gray-800 focus:bg-gray-100 transition duration-150 ease-in-out"
role="menuitem">Your Profile</a>
<a href="#"
class="mt-1 block px-4 py-2 text-base font-medium text-gray-500 hover:text-gray-800 hover:bg-gray-100 focus:outline-none focus:text-gray-800 focus:bg-gray-100 transition duration-150 ease-in-out"
role="menuitem">Settings</a>
<a href="#"
class="mt-1 block px-4 py-2 text-base font-medium text-gray-500 hover:text-gray-800 hover:bg-gray-100 focus:outline-none focus:text-gray-800 focus:bg-gray-100 transition duration-150 ease-in-out"
role="menuitem">Sign out</a>
</div>
</div>
</div>
</nav>
<div class="py-10">
<header>
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<h1 class="text-3xl font-bold leading-tight text-gray-900">
Users
</h1>
</div>
</header>
<main>
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<form>
<div>
<div>
<div class="mt-6 sm:mt-5">
<div
class="sm:grid sm:grid-cols-3 sm:gap-4 sm:items-start sm:pt-5">
<label for="exposeUserName"
class="block text-sm font-medium leading-5 text-gray-700 sm:mt-px sm:pt-2">
Name
</label>
<div class="mt-1 sm:mt-0 sm:col-span-2">
<div class="max-w-xs rounded-md shadow-sm">
<span v-if="userForm.errors.name" class="inline-block text-red-600 pb-2">
@{ userForm.errors.name[0] }
</span>
<input id="exposeUserName"
autocomplete="no"
v-model="userForm.name"
:class="{'border border-red-600': userForm.errors.name}"
class="form-input block w-full transition duration-150 ease-in-out sm:text-sm sm:leading-5"/>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="mt-8 border-t border-gray-200 pt-5">
<div class="flex justify-end">
<span class="inline-flex rounded-md shadow-sm">
<button type="button"
class="py-2 px-4 border border-gray-300 rounded-md text-sm leading-5 font-medium text-gray-700 hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue active:bg-gray-50 active:text-gray-800 transition duration-150 ease-in-out">
Cancel
</button>
</span>
<span class="ml-3 inline-flex rounded-md shadow-sm">
<button type="submit"
@click.prevent="saveUser"
class="inline-flex justify-center py-2 px-4 border border-transparent text-sm leading-5 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-500 focus:outline-none focus:border-indigo-700 focus:shadow-outline-indigo active:bg-indigo-700 transition duration-150 ease-in-out">
Add User
</button>
</span>
</div>
</div>
</form>
<div class="flex flex-col py-8">
<div class="-my-2 py-2 overflow-x-auto sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8">
<div
class="align-middle inline-block min-w-full shadow overflow-hidden sm:rounded-lg border-b border-gray-200">
<table class="min-w-full">
<thead>
<tr>
<th class="px-6 py-3 border-b border-gray-200 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
Name
</th>
<th class="px-6 py-3 border-b border-gray-200 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
Auth-Token
</th>
<th class="px-6 py-3 border-b border-gray-200 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
Created At
</th>
<th class="px-6 py-3 border-b border-gray-200 bg-gray-50"></th>
</tr>
</thead>
<tbody class="bg-white">
<tr v-for="user in users">
<td class="px-6 py-4 whitespace-no-wrap border-b border-gray-200 text-sm leading-5 font-medium text-gray-900">
@{ user.name }
</td>
<td class="px-6 py-4 whitespace-no-wrap border-b border-gray-200 text-sm leading-5 text-gray-500">
@{ user.auth_token }
</td>
<td class="px-6 py-4 whitespace-no-wrap border-b border-gray-200 text-sm leading-5 text-gray-500">
@{ user.created_at }
</td>
<td class="px-6 py-4 whitespace-no-wrap text-right border-b border-gray-200 text-sm leading-5 font-medium">
<a href="#" class="text-indigo-600 hover:text-indigo-900">Edit</a>
<a href="#" @click.prevent="deleteUser(user)"
class="pl-4 text-red-600 hover:text-red-900">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
<script>
new Vue({
el: '#app',
delimiters: ['@{', '}'],
data: {
userForm: {
name: '',
errors: {},
},
users: {{ users|json_encode|raw }}
},
methods: {
deleteUser(user) {
fetch('/expose/users/delete/'+user.id, {
method: 'DELETE',
}).then((response) => {
return response.json();
}).then((data) => {
this.users = this.users.filter(u => u.id !== user.id);
});
},
saveUser() {
fetch('/expose/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.userForm)
}).then((response) => {
return response.json();
}).then((data) => {
if (data.user) {
this.userForm.errors = {};
this.users.unshift(data.user);
}
if (data.errors) {
this.userForm.errors = data.errors;
}
});
}
}
})
</script>
</body>
</html>