* zf3 version bump

* SSO auth added to the site
This commit is contained in:
Dávid Danyi 2018-07-25 18:20:45 +02:00
parent 4c0badd7bc
commit 0d5299c7b7
15 changed files with 1647 additions and 864 deletions

View File

@ -7,27 +7,42 @@
"config": { "config": {
"sort-packages": true "sort-packages": true
}, },
"minimum-stability": "dev",
"prefer-stable": true,
"extra": {
"zf": {
"component-whitelist": [
"zendframework/zend-expressive",
"zendframework/zend-expressive-helpers",
"zendframework/zend-expressive-router",
"zendframework/zend-httphandlerrunner",
"zendframework/zend-expressive-fastroute"
]
}
},
"require": { "require": {
"php": "^7.1", "php": "^7.1",
"doctrine/common": "2.9.x-dev", "doctrine/common": "^2.9",
"guzzlehttp/guzzle": "6.3.0", "guzzlehttp/guzzle": "^6.3",
"http-interop/http-middleware": "^0.4.1", "los/loslog": "^3.1",
"roave/security-advisories": "dev-master", "ramsey/uuid": "^3.8",
"zendframework/zend-component-installer": "^1.0", "zendframework/zend-component-installer": "^2.1.1",
"zendframework/zend-config-aggregator": "^1.0", "zendframework/zend-config-aggregator": "^1.0",
"zendframework/zend-dom": "2.6.0", "zendframework/zend-diactoros": "^1.7.1",
"zendframework/zend-expressive": "^2.0.5", "zendframework/zend-dom": "^2.6.0",
"zendframework/zend-expressive-fastroute": "^2.0", "zendframework/zend-expressive": "^3.0.1",
"zendframework/zend-expressive-helpers": "^4.0", "zendframework/zend-expressive-fastroute": "^3.0",
"zendframework/zend-json": "3.0.0", "zendframework/zend-expressive-helpers": "^5.0",
"zendframework/zend-json": "^3.1",
"zendframework/zend-servicemanager": "^3.3", "zendframework/zend-servicemanager": "^3.3",
"zendframework/zend-stdlib": "^3.1" "zendframework/zend-stdlib": "^3.1"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^6.0.8 || ^5.7.15", "phpunit/phpunit": "^7.0.1",
"squizlabs/php_codesniffer": "^2.8.1", "roave/security-advisories": "dev-master",
"squizlabs/php_codesniffer": "^2.9.1",
"zfcampus/zf-development-mode": "^3.1", "zfcampus/zf-development-mode": "^3.1",
"filp/whoops": "^2.1.7" "filp/whoops": "^2.1.12"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {

2037
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,6 @@
<?php <?php
use Zend\Expressive\Application; declare(strict_types=1);
use Zend\Expressive\Container;
use Zend\Expressive\Delegate;
use Zend\Expressive\Helper;
use Zend\Expressive\Middleware;
return [ return [
// Provides application-wide services. // Provides application-wide services.
@ -13,27 +9,15 @@ return [
'dependencies' => [ 'dependencies' => [
// Use 'aliases' to alias a service name to another service. The // Use 'aliases' to alias a service name to another service. The
// key is the alias name, the value is the service to which it points. // key is the alias name, the value is the service to which it points.
'aliases' => [ 'aliases' => [],
'Zend\Expressive\Delegate\DefaultDelegate' => Delegate\NotFoundDelegate::class,
],
// Use 'invokables' for constructor-less services, or services that do // Use 'invokables' for constructor-less services, or services that do
// not require arguments to the constructor. Map a service name to the // not require arguments to the constructor. Map a service name to the
// class name. // class name.
'invokables' => [ 'invokables' => [
// Fully\Qualified\InterfaceName::class => Fully\Qualified\ClassName::class, // Fully\Qualified\InterfaceName::class => Fully\Qualified\ClassName::class,
Helper\ServerUrlHelper::class => Helper\ServerUrlHelper::class,
], ],
// Use 'factories' for services provided by callbacks/factory classes. // Use 'factories' for services provided by callbacks/factory classes.
'factories' => [ 'factories' => [
Application::class => Container\ApplicationFactory::class,
Delegate\NotFoundDelegate::class => Container\NotFoundDelegateFactory::class,
Helper\ServerUrlMiddleware::class => Helper\ServerUrlMiddlewareFactory::class,
Helper\UrlHelper::class => Helper\UrlHelperFactory::class,
Helper\UrlHelperMiddleware::class => Helper\UrlHelperMiddlewareFactory::class,
Zend\Stratigility\Middleware\ErrorHandler::class => Container\ErrorHandlerFactory::class,
Middleware\ErrorResponseGenerator::class => Container\ErrorResponseGeneratorFactory::class,
Middleware\NotFoundHandler::class => Container\NotFoundHandlerFactory::class,
], ],
], ],
]; ];

View File

@ -0,0 +1,28 @@
<?php
use Zend\Stratigility\Middleware\ErrorHandler;
return [
'dependencies' => [
'factories' => [
LosMiddleware\LosLog\LosLog::class => LosMiddleware\LosLog\LosLogFactory::class,
LosMiddleware\LosLog\HttpLog::class => LosMiddleware\LosLog\HttpLogFactory::class,
Psr\Log\LoggerInterface::class => LosMiddleware\LosLog\LoggerFactory::class,
],
'delegators' => [
ErrorHandler::class => [
LosMiddleware\LosLog\ErrorHandlerListenerDelegatorFactory::class,
],
],
],
'loslog' => [
'log_dir' => 'data/logs',
'error_logger_file' => 'error.log',
'exception_logger_file' => 'exception.log',
'static_logger_file' => 'static.log',
'http_logger_file' => 'http.log',
'log_request' => false,
'log_response' => false,
'full' => false,
],
];

View File

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
use Zend\ConfigAggregator\ArrayProvider; use Zend\ConfigAggregator\ArrayProvider;
use Zend\ConfigAggregator\ConfigAggregator; use Zend\ConfigAggregator\ConfigAggregator;
use Zend\ConfigAggregator\PhpFileProvider; use Zend\ConfigAggregator\PhpFileProvider;
@ -11,9 +13,15 @@ $cacheConfig = [
]; ];
$aggregator = new ConfigAggregator([ $aggregator = new ConfigAggregator([
\Zend\Log\ConfigProvider::class,
\Zend\HttpHandlerRunner\ConfigProvider::class,
// Include cache configuration // Include cache configuration
new ArrayProvider($cacheConfig), new ArrayProvider($cacheConfig),
\Zend\Expressive\Helper\ConfigProvider::class,
\Zend\Expressive\ConfigProvider::class,
\Zend\Expressive\Router\ConfigProvider::class,
// Default App module config // Default App module config
App\ConfigProvider::class, App\ConfigProvider::class,

View File

@ -1,16 +1,14 @@
<?php <?php
use Zend\ServiceManager\Config; declare(strict_types=1);
use Zend\ServiceManager\ServiceManager; use Zend\ServiceManager\ServiceManager;
// Load configuration // Load configuration
$config = require __DIR__ . '/config.php'; $config = require __DIR__ . '/config.php';
$dependencies = $config['dependencies'];
$dependencies['services']['config'] = $config;
// Build container // Build container
$container = new ServiceManager(); return new ServiceManager($dependencies);
(new Config($config['dependencies']))->configureServiceManager($container);
// Inject config
$container->setService('config', $config);
return $container;

View File

@ -1,55 +1,78 @@
<?php <?php
declare(strict_types=1);
use Psr\Container\ContainerInterface;
use Zend\Expressive\Application;
use Zend\Expressive\Handler\NotFoundHandler;
use Zend\Expressive\Helper\ServerUrlMiddleware; use Zend\Expressive\Helper\ServerUrlMiddleware;
use Zend\Expressive\Helper\UrlHelperMiddleware; use Zend\Expressive\Helper\UrlHelperMiddleware;
use Zend\Expressive\Middleware\ImplicitHeadMiddleware; use Zend\Expressive\MiddlewareFactory;
use Zend\Expressive\Middleware\ImplicitOptionsMiddleware; use Zend\Expressive\Router\Middleware\DispatchMiddleware;
use Zend\Expressive\Middleware\NotFoundHandler; use Zend\Expressive\Router\Middleware\ImplicitHeadMiddleware;
use Zend\Expressive\Router\Middleware\ImplicitOptionsMiddleware;
use Zend\Expressive\Router\Middleware\MethodNotAllowedMiddleware;
use Zend\Expressive\Router\Middleware\RouteMiddleware;
use Zend\Stratigility\Middleware\ErrorHandler; use Zend\Stratigility\Middleware\ErrorHandler;
/** /**
* Setup middleware pipeline: * Setup middleware pipeline:
*/ */
return function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void {
// The error handler should be the first (most outer) middleware to catch
// all Exceptions.
$app->pipe(ErrorHandler::class);
// $app->pipe(App\Middleware\PreFlightMiddleware::class);
// $app->pipe(App\Middleware\EventSubscriberMiddleware::class);
$app->pipe(ServerUrlMiddleware::class);
// The error handler should be the first (most outer) middleware to catch // Pipe more middleware here that you want to execute on every request:
// all Exceptions. // - bootstrapping
$app->pipe(ErrorHandler::class); // - pre-conditions
$app->pipe(ServerUrlMiddleware::class); // - modifications to outgoing responses
//
// Piped Middleware may be either callables or service names. Middleware may
// also be passed as an array; each item in the array must resolve to
// middleware eventually (i.e., callable or service name).
//
// Middleware can be attached to specific paths, allowing you to mix and match
// applications under a common domain. The handlers in each middleware
// attached this way will see a URI with the matched path segment removed.
//
// i.e., path of "/api/member/profile" only passes "/member/profile" to $apiMiddleware
// - $app->pipe('/api', $apiMiddleware);
// - $app->pipe('/docs', $apiDocMiddleware);
// - $app->pipe('/files', $filesMiddleware);
// Pipe more middleware here that you want to execute on every request: // Register the routing middleware in the middleware pipeline.
// - bootstrapping // This middleware registers the Zend\Expressive\Router\RouteResult request attribute.
// - pre-conditions $app->pipe(RouteMiddleware::class);
// - modifications to outgoing responses
//
// Piped Middleware may be either callables or service names. Middleware may
// also be passed as an array; each item in the array must resolve to
// middleware eventually (i.e., callable or service name).
//
// Middleware can be attached to specific paths, allowing you to mix and match
// applications under a common domain. The handlers in each middleware
// attached this way will see a URI with the MATCHED PATH SEGMENT REMOVED!!!
//
// - $app->pipe('/api', $apiMiddleware);
// - $app->pipe('/docs', $apiDocMiddleware);
// - $app->pipe('/files', $filesMiddleware);
// Register the routing middleware in the middleware pipeline // The following handle routing failures for common conditions:
$app->pipeRoutingMiddleware(); // - HEAD request but no routes answer that method
$app->pipe(ImplicitHeadMiddleware::class); // - OPTIONS request but no routes answer that method
$app->pipe(ImplicitOptionsMiddleware::class); // - method not allowed
$app->pipe(UrlHelperMiddleware::class); // Order here matters; the MethodNotAllowedMiddleware should be placed
// after the Implicit*Middleware.
$app->pipe(ImplicitHeadMiddleware::class);
$app->pipe(ImplicitOptionsMiddleware::class);
$app->pipe(MethodNotAllowedMiddleware::class);
// Add more middleware here that needs to introspect the routing results; this // Seed the UrlHelper with the routing results:
// might include: $app->pipe(UrlHelperMiddleware::class);
//
// - route-based authentication
// - route-based validation
// - etc.
// Register the dispatch middleware in the middleware pipeline // Add more middleware here that needs to introspect the routing results; this
$app->pipeDispatchMiddleware(); // might include:
//
// - route-based authentication
// - route-based validation
// - etc.
// At this point, if no Response is return by any middleware, the // Register the dispatch middleware in the middleware pipeline
// NotFoundHandler kicks in; alternately, you can provide other fallback $app->pipe(DispatchMiddleware::class);
// middleware to execute.
$app->pipe(NotFoundHandler::class); // At this point, if no Response is returned by any middleware, the
// NotFoundHandler kicks in; alternately, you can provide other fallback
// middleware to execute.
$app->pipe(NotFoundHandler::class);
};

View File

@ -1,34 +1,42 @@
<?php <?php
declare(strict_types=1);
use Psr\Container\ContainerInterface;
use Zend\Expressive\Application;
use Zend\Expressive\MiddlewareFactory;
/** /**
* Setup routes with a single request method: * Setup routes with a single request method:
* *
* $app->get('/', App\Action\HomePageAction::class, 'home'); * $app->get('/', App\Handler\HomePageHandler::class, 'home');
* $app->post('/album', App\Action\AlbumCreateAction::class, 'album.create'); * $app->post('/album', App\Handler\AlbumCreateHandler::class, 'album.create');
* $app->put('/album/:id', App\Action\AlbumUpdateAction::class, 'album.put'); * $app->put('/album/:id', App\Handler\AlbumUpdateHandler::class, 'album.put');
* $app->patch('/album/:id', App\Action\AlbumUpdateAction::class, 'album.patch'); * $app->patch('/album/:id', App\Handler\AlbumUpdateHandler::class, 'album.patch');
* $app->delete('/album/:id', App\Action\AlbumDeleteAction::class, 'album.delete'); * $app->delete('/album/:id', App\Handler\AlbumDeleteHandler::class, 'album.delete');
* *
* Or with multiple request methods: * Or with multiple request methods:
* *
* $app->route('/contact', App\Action\ContactAction::class, ['GET', 'POST', ...], 'contact'); * $app->route('/contact', App\Handler\ContactHandler::class, ['GET', 'POST', ...], 'contact');
* *
* Or handling all request methods: * Or handling all request methods:
* *
* $app->route('/contact', App\Action\ContactAction::class)->setName('contact'); * $app->route('/contact', App\Handler\ContactHandler::class)->setName('contact');
* *
* or: * or:
* *
* $app->route( * $app->route(
* '/contact', * '/contact',
* App\Action\ContactAction::class, * App\Handler\ContactHandler::class,
* Zend\Expressive\Router\Route::HTTP_METHOD_ANY, * Zend\Expressive\Router\Route::HTTP_METHOD_ANY,
* 'contact' * 'contact'
* ); * );
*/ */
return function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void {
$app->get('/', App\Action\HomePageAction::class, 'home');
$app->get('/api/ping', App\Action\PingAction::class, 'api.ping');
$app->get('/', App\Action\HomePageAction::class, 'home'); $app->get('/api/activity[/{id:\d+}]', App\Action\ActivityAction::class, 'api.activity.get');
$app->get('/api/ping', App\Action\PingAction::class, 'api.ping'); $app->get('/api/activity/signup/{id:\d+}', App\Action\ActivitySignupAction::class, 'api.activity.signup');
$app->get('/api/activity/signoff/{id:\d+}', App\Action\ActivitySignoffAction::class, 'api.activity.signoff');
$app->get('/api/activity[/{id:\d+}]', App\Action\ActivityAction::class, 'api.activity.get'); };
$app->get('/api/activity/signup/{id:\d+}', App\Action\ActivitySignupAction::class, 'api.activity.signup');
$app->get('/api/activity/signoff/{id:\d+}', App\Action\ActivitySignoffAction::class, 'api.activity.signoff');

View File

@ -1,9 +1,9 @@
<?php <?php
declare(strict_types=1);
// Delegate static file requests back to the PHP built-in webserver // Delegate static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server' if (PHP_SAPI === 'cli-server' && $_SERVER['SCRIPT_FILENAME'] !== __FILE__) {
&& is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))
) {
return false; return false;
} }
@ -13,17 +13,18 @@ require 'vendor/autoload.php';
/** /**
* Self-called anonymous function that creates its own scope and keep the global namespace clean. * Self-called anonymous function that creates its own scope and keep the global namespace clean.
*/ */
call_user_func(function () { (function () {
/** @var \Interop\Container\ContainerInterface $container */ /** @var \Psr\Container\ContainerInterface $container */
$container = require 'config/container.php'; $container = require 'config/container.php';
/** @var \Zend\Expressive\Application $app */ /** @var \Zend\Expressive\Application $app */
$app = $container->get(\Zend\Expressive\Application::class); $app = $container->get(\Zend\Expressive\Application::class);
$factory = $container->get(\Zend\Expressive\MiddlewareFactory::class);
// Import programmatic/declarative middleware pipeline and routing // Execute programmatic/declarative middleware pipeline and routing
// configuration statements // configuration statements
require 'config/pipeline.php'; (require 'config/pipeline.php')($app, $factory, $container);
require 'config/routes.php'; (require 'config/routes.php')($app, $factory, $container);
$app->run(); $app->run();
}); })();

View File

@ -2,17 +2,17 @@
namespace App\Action; namespace App\Action;
use Interop\Http\ServerMiddleware\DelegateInterface; use Psr\Http\Message\ResponseInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface as ServerMiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\JsonResponse; use Zend\Diactoros\Response\JsonResponse;
use Zend\Json\Json; use Zend\Json\Json;
abstract class AbstractAction implements ServerMiddlewareInterface abstract class AbstractAction implements RequestHandlerInterface
{ {
const IDENTIFIER_NAME = 'id'; const IDENTIFIER_NAME = 'id';
public function process(ServerRequestInterface $request, DelegateInterface $delegate) public function handle(ServerRequestInterface $request) : ResponseInterface
{ {
$requestMethod = strtoupper($request->getMethod()); $requestMethod = strtoupper($request->getMethod());
$id = $request->getAttribute(static::IDENTIFIER_NAME); $id = $request->getAttribute(static::IDENTIFIER_NAME);
@ -20,73 +20,73 @@ abstract class AbstractAction implements ServerMiddlewareInterface
switch ($requestMethod) { switch ($requestMethod) {
case 'GET': case 'GET':
return isset($id) return isset($id)
? $this->get($request, $delegate) ? $this->get($request)
: $this->getList($request, $delegate); : $this->getList($request);
case 'POST': case 'POST':
return $this->create($request, $delegate); return $this->create($request);
case 'PUT': case 'PUT':
return $this->update($request, $delegate); return $this->update($request);
case 'DELETE': case 'DELETE':
return isset($id) return isset($id)
? $this->delete($request, $delegate) ? $this->delete($request)
: $this->deleteList($request, $delegate); : $this->deleteList($request);
case 'HEAD': case 'HEAD':
return $this->head($request, $delegate); return $this->head($request);
case 'OPTIONS': case 'OPTIONS':
return $this->options($request, $delegate); return $this->options($request);
case 'PATCH': case 'PATCH':
return $this->patch($request, $delegate); return $this->patch($request);
default: default:
return $delegate->process($request); die(500);
} }
} }
public function get(ServerRequestInterface $request, DelegateInterface $delegate) public function get(ServerRequestInterface $request) : ResponseInterface
{ {
return $this->createResponse(['content' => 'Method not allowed'], 405); return $this->createResponse(['content' => 'Method not allowed'], 405);
} }
public function getList(ServerRequestInterface $request, DelegateInterface $delegate) public function getList(ServerRequestInterface $request) : ResponseInterface
{ {
return $this->createResponse(['content' => 'Method not allowed'], 405); return $this->createResponse(['content' => 'Method not allowed'], 405);
} }
public function create(ServerRequestInterface $request, DelegateInterface $delegate) public function create(ServerRequestInterface $request) : ResponseInterface
{ {
return $this->createResponse(['content' => 'Method not allowed'], 405); return $this->createResponse(['content' => 'Method not allowed'], 405);
} }
public function update(ServerRequestInterface $request, DelegateInterface $delegate) public function update(ServerRequestInterface $request) : ResponseInterface
{ {
return $this->createResponse(['content' => 'Method not allowed'], 405); return $this->createResponse(['content' => 'Method not allowed'], 405);
} }
public function delete(ServerRequestInterface $request, DelegateInterface $delegate) public function delete(ServerRequestInterface $request) : ResponseInterface
{ {
return $this->createResponse(['content' => 'Method not allowed'], 405); return $this->createResponse(['content' => 'Method not allowed'], 405);
} }
public function deleteList(ServerRequestInterface $request, DelegateInterface $delegate) public function deleteList(ServerRequestInterface $request) : ResponseInterface
{ {
return $this->createResponse(['content' => 'Method not allowed'], 405); return $this->createResponse(['content' => 'Method not allowed'], 405);
} }
public function head(ServerRequestInterface $request, DelegateInterface $delegate) public function head(ServerRequestInterface $request) : ResponseInterface
{ {
return $this->createResponse(['content' => 'Method not allowed'], 405); return $this->createResponse(['content' => 'Method not allowed'], 405);
} }
public function options(ServerRequestInterface $request, DelegateInterface $delegate) public function options(ServerRequestInterface $request) : ResponseInterface
{ {
return $this->createResponse(['content' => 'Method not allowed'], 405); return $this->createResponse(['content' => 'Method not allowed'], 405);
} }
public function patch(ServerRequestInterface $request, DelegateInterface $delegate) public function patch(ServerRequestInterface $request) : ResponseInterface
{ {
return $this->createResponse(['content' => 'Method not allowed'], 405); return $this->createResponse(['content' => 'Method not allowed'], 405);
} }
final protected function createResponse($data, $status = 200) final protected function createResponse($data, $status = 200) : ResponseInterface
{ {
return new JsonResponse($data, $status); return new JsonResponse($data, $status);
} }

View File

@ -1,12 +1,14 @@
<?php <?php
declare(strict_types=1);
namespace App\Action; namespace App\Action;
use App\Service\SkiesClientService; use App\Service\SkiesClientService;
use Interop\Http\ServerMiddleware\DelegateInterface; use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\JsonResponse; use Zend\Diactoros\Response\JsonResponse;
use Zend\Diactoros\Response\TextResponse;
class ActivityAction extends AbstractAction class ActivityAction extends AbstractAction
{ {
@ -20,13 +22,23 @@ class ActivityAction extends AbstractAction
$this->skiesClient = $skiesClient; $this->skiesClient = $skiesClient;
} }
public function getList(ServerRequestInterface $request, DelegateInterface $delegate) /**
* @param ServerRequestInterface $request
* @return ResponseInterface
* @throws GuzzleException
*/
public function getList(ServerRequestInterface $request) : ResponseInterface
{ {
$authHeader = $request->getHeaderLine("x-passthru-auth"); $authHeader = $request->getHeaderLine("x-passthru-auth");
return new JsonResponse($this->skiesClient->setAuthHeader($authHeader)->getActivities()); return new JsonResponse($this->skiesClient->setAuthHeader($authHeader)->getActivities());
} }
public function get(ServerRequestInterface $request, DelegateInterface $delegate) /**
* @param ServerRequestInterface $request
* @return ResponseInterface
* @throws GuzzleException
*/
public function get(ServerRequestInterface $request) : ResponseInterface
{ {
$id = $request->getAttribute(self::IDENTIFIER_NAME); $id = $request->getAttribute(self::IDENTIFIER_NAME);
$authHeader = $request->getHeaderLine("x-passthru-auth"); $authHeader = $request->getHeaderLine("x-passthru-auth");

View File

@ -3,12 +3,12 @@
namespace App\Action; namespace App\Action;
use App\Service\SkiesClientService; use App\Service\SkiesClientService;
use Interop\Http\ServerMiddleware\DelegateInterface; use Psr\Http\Message\ResponseInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface as ServerMiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\JsonResponse; use Zend\Diactoros\Response\JsonResponse;
class ActivitySignoffAction implements ServerMiddlewareInterface class ActivitySignoffAction implements RequestHandlerInterface
{ {
/** /**
* @var SkiesClientService * @var SkiesClientService
@ -20,7 +20,12 @@ class ActivitySignoffAction implements ServerMiddlewareInterface
$this->skiesClient = $skiesClient; $this->skiesClient = $skiesClient;
} }
public function process(ServerRequestInterface $request, DelegateInterface $delegate) /**
* @param ServerRequestInterface $request
* @return ResponseInterface
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function handle(ServerRequestInterface $request) : ResponseInterface
{ {
$authHeader = $request->getHeaderLine("x-passthru-auth"); $authHeader = $request->getHeaderLine("x-passthru-auth");
$id = $request->getAttribute("id"); $id = $request->getAttribute("id");

View File

@ -3,12 +3,12 @@
namespace App\Action; namespace App\Action;
use App\Service\SkiesClientService; use App\Service\SkiesClientService;
use Interop\Http\ServerMiddleware\DelegateInterface; use Psr\Http\Message\ResponseInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface as ServerMiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\JsonResponse; use Zend\Diactoros\Response\JsonResponse;
class ActivitySignupAction implements ServerMiddlewareInterface class ActivitySignupAction implements RequestHandlerInterface
{ {
/** /**
* @var SkiesClientService * @var SkiesClientService
@ -20,7 +20,12 @@ class ActivitySignupAction implements ServerMiddlewareInterface
$this->skiesClient = $skiesClient; $this->skiesClient = $skiesClient;
} }
public function process(ServerRequestInterface $request, DelegateInterface $delegate) /**
* @param ServerRequestInterface $request
* @return ResponseInterface
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function handle(ServerRequestInterface $request) : ResponseInterface
{ {
$authHeader = $request->getHeaderLine("x-passthru-auth"); $authHeader = $request->getHeaderLine("x-passthru-auth");
$id = $request->getAttribute("id"); $id = $request->getAttribute("id");

View File

@ -6,12 +6,21 @@ use App\Entity\Activity;
use App\Entity\Comment; use App\Entity\Comment;
use App\Entity\User; use App\Entity\User;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJarInterface;
use GuzzleHttp\Cookie\FileCookieJar;
use function GuzzleHttp\Psr7\parse_query;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
use Ramsey\Uuid\Uuid;
use Zend\Diactoros\Uri;
use Zend\Dom\Document; use Zend\Dom\Document;
use Zend\Expressive\Exception\MissingDependencyException; use Zend\Expressive\Exception\MissingDependencyException;
class SkiesClientService class SkiesClientService
{ {
const APP_REALM = '7302c625-70ba-e311-80c0-00155da22c45';
const ADFS_AUTH_URL = "https://fs.sigmatechnology.se/adfs/ls";
const SKIES_BASE_URL = 'https://skies.sigmatechnology.se/';
const SKIES_MAIN_URL = "https://skies.sigmatechnology.se/main.asp"; const SKIES_MAIN_URL = "https://skies.sigmatechnology.se/main.asp";
const SKIES_PROFILE_URL = "https://skies.sigmatechnology.se/main.asp?rID=1&alt=2&username=%s"; const SKIES_PROFILE_URL = "https://skies.sigmatechnology.se/main.asp?rID=1&alt=2&username=%s";
const SKIES_ACTIVITIES_URL = "https://skies.sigmatechnology.se/main.asp?rID=2"; const SKIES_ACTIVITIES_URL = "https://skies.sigmatechnology.se/main.asp?rID=2";
@ -19,31 +28,81 @@ class SkiesClientService
const SKIES_ACTIVITY_SIGNUP_URL = "https://skies.sigmatechnology.se/main.asp?rID=2&alt=1&aktID=%s&doJoin=1"; const SKIES_ACTIVITY_SIGNUP_URL = "https://skies.sigmatechnology.se/main.asp?rID=2&alt=1&aktID=%s&doJoin=1";
const SKIES_ACTIVITY_SIGNOFF_URL = "https://skies.sigmatechnology.se/main.asp?rID=2&alt=1&aktID=%s&doCancel=1&user=%s"; const SKIES_ACTIVITY_SIGNOFF_URL = "https://skies.sigmatechnology.se/main.asp?rID=2&alt=1&aktID=%s&doCancel=1&user=%s";
/** /** @var Client */
* @var Client
*/
private $client; private $client;
/** /** @var string */
* @var string private $authUser = null;
*/
private $authHeader = null;
/** @var string */
private $authPass = null;
/** @var CookieJarInterface */
private $cookieJar = null;
private $counter = 0;
/**
* SkiesClientService constructor.
* @param Client $client
*/
public function __construct(Client $client) public function __construct(Client $client)
{ {
$this->client = $client; $this->client = $client;
} }
/**
* @throws \Exception
*/
private function getAuthCookies()
{
if ($this->authUser == null) {
throw new MissingDependencyException("X-Passthru-Auth header is missing");
}
// try to fetch the main page, only renew auth cookie if we can't
$testRequest = $this->client->get(self::SKIES_MAIN_URL, [
'cookies' => $this->cookieJar,
'allow_redirects' => false,
]);
if (200 == $testRequest->getStatusCode()) {
return;
}
$this->client->post(self::ADFS_AUTH_URL, [
'cookies' => $this->cookieJar,
'allow_redirects' => true,
'query' => [
'version' => '1.0',
'action' => 'signin',
'realm' => 'urn:AppProxy:com',
'appRealm' => self::APP_REALM,
'returnUrl' => self::SKIES_BASE_URL,
'client-request-id' => Uuid::uuid1(),
],
'form_params' => [
'UserName' => $this->authUser,
'Password' => $this->authPass,
'AuthMethod' => 'FormsAuthentication',
]
]);
}
/** /**
* @param string $authHeader * @param string $authHeader
* @return SkiesClientService * @return SkiesClientService
*/ */
public function setAuthHeader(string $authHeader): SkiesClientService public function setAuthHeader(string $authHeader): SkiesClientService
{ {
$this->authHeader = $authHeader; list($this->authUser, $this->authPass) = explode(':', base64_decode($authHeader));
$this->cookieJar = new FileCookieJar("data/cache/".$this->authUser, true);
return $this; return $this;
} }
/**
* @return bool
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function getNews() public function getNews()
{ {
$response = $this->doSkiesRequest('GET', self::SKIES_MAIN_URL); $response = $this->doSkiesRequest('GET', self::SKIES_MAIN_URL);
@ -53,6 +112,7 @@ class SkiesClientService
/** /**
* @return Activity[] * @return Activity[]
* @throws \GuzzleHttp\Exception\GuzzleException
*/ */
public function getActivities() public function getActivities()
{ {
@ -64,6 +124,7 @@ class SkiesClientService
/** /**
* @param string $htmlBody * @param string $htmlBody
* @return Activity[] * @return Activity[]
* @throws \GuzzleHttp\Exception\GuzzleException
*/ */
private function parseActivitiesPage(string $htmlBody) private function parseActivitiesPage(string $htmlBody)
{ {
@ -97,6 +158,7 @@ class SkiesClientService
/** /**
* @param int $id * @param int $id
* @return Activity * @return Activity
* @throws \GuzzleHttp\Exception\GuzzleException
*/ */
public function getActivity(int $id): Activity public function getActivity(int $id): Activity
{ {
@ -108,6 +170,7 @@ class SkiesClientService
/** /**
* @param int $id * @param int $id
* @return Activity * @return Activity
* @throws \GuzzleHttp\Exception\GuzzleException
*/ */
public function signUpActivity(int $id): Activity public function signUpActivity(int $id): Activity
{ {
@ -122,6 +185,7 @@ class SkiesClientService
/** /**
* @param int $id * @param int $id
* @return Activity * @return Activity
* @throws \GuzzleHttp\Exception\GuzzleException
*/ */
public function signOffActivity(int $id): Activity public function signOffActivity(int $id): Activity
{ {
@ -134,6 +198,7 @@ class SkiesClientService
* @param string $htmlBody * @param string $htmlBody
* @param int $id * @param int $id
* @return Activity * @return Activity
* @throws \GuzzleHttp\Exception\GuzzleException
*/ */
private function parseActivityPage(string $htmlBody, int $id): Activity private function parseActivityPage(string $htmlBody, int $id): Activity
{ {
@ -333,6 +398,11 @@ class SkiesClientService
return false; return false;
} }
/**
* @param string $username
* @return string
* @throws \GuzzleHttp\Exception\GuzzleException
*/
private function getDisplayName(string $username): string private function getDisplayName(string $username): string
{ {
$response = $this->doSkiesRequest("GET", sprintf(self::SKIES_PROFILE_URL, $username)); $response = $this->doSkiesRequest("GET", sprintf(self::SKIES_PROFILE_URL, $username));
@ -368,18 +438,19 @@ class SkiesClientService
* @param string $url * @param string $url
* @param array $options * @param array $options
* @return ResponseInterface * @return ResponseInterface
* @throws \GuzzleHttp\Exception\GuzzleException
* @throws \Exception
*/ */
private function doSkiesRequest(string $method, string $url, $options = []): ResponseInterface private function doSkiesRequest(string $method, string $url, $options = []): ResponseInterface
{ {
if ($this->authHeader == null) { $this->getAuthCookies();
throw new MissingDependencyException("X-Passthru-Auth header is missing"); $this->counter += 1;
} $response = $this->client
return $this->client
->request($method, $url, [ ->request($method, $url, [
'headers' => [ 'cookies' => $this->cookieJar,
'Authorization' => "Basic {$this->authHeader}", 'allow_redirects' => true,
]
] + $options); ] + $options);
return $response;
} }
/** /**
@ -387,11 +458,7 @@ class SkiesClientService
*/ */
private function getUsername(): string private function getUsername(): string
{ {
if (null == $this->authHeader) { list(,$signum) = explode("\\", $this->authUser);
throw new MissingDependencyException("X-Passthru-Auth header is missing"); return $signum;
}
$decodedHeader = base64_decode($this->authHeader);
list($username) = explode(":", $decodedHeader);
return $username;
} }
} }

View File

@ -10,7 +10,7 @@ class SkiesClientServiceFactory
public function __invoke(ContainerInterface $container) public function __invoke(ContainerInterface $container)
{ {
$httpClient = new Client([ $httpClient = new Client([
'cookies' => true, 'allow_redirects' => true,
]); ]);
return new SkiesClientService($httpClient); return new SkiesClientService($httpClient);
} }