WIP: base64 upload

parent 3519458f
# Πρόγραμμα ελέγχου εγκυρότητας ψηφιακής υπογραφής
[Εφαρμογή διαδικτύου αναπτυγμένη σε SLIM framwork](./slim-app/)
/vendor/
/logs/*
!/logs/README.md
{
"name": "minedu-osteam/amka-api-slim-app",
"description": "A Slim Framework application for consuming the GUNET amka api",
"keywords": ["rest", "minedu"],
"homepage": "https://git.minedu.gov.gr/spapad/samples",
"license": "EUPL",
"authors": [
{
"name": "MINEDU OPEN SOURCE TEAM",
"email": "osteam@minedu.gov.gr",
"homepage": "http://ostmgmt.minedu.gov.gr/"
},
{
"name": "Stavros Papadakis",
"email": "spapad@gmail.com"
}
],
"require": {
"php": ">=5.5.0",
"slim/slim": "^3.1",
"slim/php-view": "^2.0",
"monolog/monolog": "^1.17"
},
"require-dev": {
"phpunit/phpunit": ">=4.8 < 6.0"
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"start": "php -S 0.0.0.0:8080 -t public public/index.php",
"test": "phpunit"
}
}
This diff is collapsed.
Your Slim Framework application's log files will be written to this directory.
<phpunit bootstrap="vendor/autoload.php">
<testsuites>
<testsuite name="SampleApp">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
\ No newline at end of file
RewriteEngine On
# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
<?php
if (PHP_SAPI == 'cli-server') {
// To help the built-in PHP dev server, check if the request was actually for
// something which should probably be served as a static file
$url = parse_url($_SERVER['REQUEST_URI']);
$file = __DIR__ . $url['path'];
if (is_file($file)) {
return false;
}
}
$autoloader = require __DIR__ . '/../vendor/autoload.php';
session_name('MineduOsteamApp');
session_start();
date_default_timezone_set('Europe/Athens');
// Instantiate the app
$settings_file = __DIR__ . '/../src/settings.php';
if (is_readable($settings_file)) {
$settings = require($settings_file);
} else {
$settings = [];
}
$app = new \Slim\App($settings);
$container = $app->getContainer();
// Set up dependencies
require __DIR__ . '/../src/dependencies.php';
//
// setup the app
//
$container['autoloader'] = $autoloader;
$autoloader->addPsr4('Gr\Gov\Minedu\Osteam\Slim\\', __DIR__ . '/../src/osteam');
$container['errorHandler'] = function ($c) {
return function ($request, $response, $exception) use ($c) {
return $c['response']->withJson([
'message' => 'Προέκυψε λάθος',
'in' => $exception->getMessage()
], intval($code = $exception->getCode()) > 0 ? $code : null
);
};
};
// Register routes
require __DIR__ . '/../src/routes.php';
// Register middleware
require __DIR__ . '/../src/middleware.php';
// Run app
$app->run();
<?php
// DIC configuration
$container = $app->getContainer();
// view renderer
$container['renderer'] = function ($c) {
$settings = $c->get('settings')['renderer'];
return new Slim\Views\PhpRenderer($settings['template_path']);
};
// monolog
$container['logger'] = function ($c) {
$settings = $c->get('settings')['logger'];
$logger = new Monolog\Logger($settings['name']);
$logger->pushProcessor(new Monolog\Processor\UidProcessor());
$logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
return $logger;
};
<?php
$settings = $app->getContainer()->get('settings');
$username = isset($settings['app']['secure_endpoint_username']) ? $settings['app']['secure_endpoint_username'] : '';
$password = isset($settings['app']['secure_endpoint_password']) ? $settings['app']['secure_endpoint_password'] : '';
// Application middleware
// e.g: $app->add(new \Slim\Csrf\Guard);
$app->getContainer()->get('router')
->getNamedRoute('validate')
->add(new Gr\Gov\Minedu\Osteam\Slim\AuthorizationGuard($username, $password));
<?php
namespace Gr\Gov\Minedu\Osteam\Slim;
use Interop\Container\ContainerInterface;
use Slim\Http\Body;
use Gr\Gov\Minedu\Osteam\Slim\Client;
/**
* Description of app
*
* @author spapad
*/
class App
{
protected $ci = null;
protected $logger = null;
protected $savePath;
public function __construct(ContainerInterface $ci)
{
$this->ci = $ci;
if (($logger = $this->ci->get('logger')) != null) {
$this->logger = $logger;
}
$settings = $this->ci->get('settings');
if (isset($settings['app'])) {
$this->savePath = (isset($settings['app']['save_path']) ? $settings['app']['save_path'] : 'tmp');
}
}
/**
* Χαιρετισμός - οδηγίες.
*
* @param Psr\Http\Message\ServerRequestInterface $req
* @param Psr\Http\Message\ResponseInterface $res
* @param $args
* @throws \Exception
* @return Response
*/
public function greet($req, $res, $args)
{
return $res->withJson([
'message' => 'Only POST is available'
], 401);
}
/**
* Έλεγχος.
*
* @param Psr\Http\Message\ServerRequestInterface $req
* @param Psr\Http\Message\ResponseInterface $res
* @throws \Exception
* @return Response
*/
public function validate($req, $res, $args)
{
// $body = $req->getBody();
// $contents = $body->getContents();
// $parsedBody = $req->getParsedBody();
$filename = $req->getParsedBodyParam('filename', null);
$content = $req->getParsedBodyParam('base64content', null);
if ($filename === null || $content === null) {
return $res->withJson(['message' => 'Filename and file content is mandatory'], 401);
}
if (($filecontent = base64_decode($content)) === false) {
return $res->withJson(['message' => 'File content is not valid base64 encoded'], 401);
}
if (!is_dir($this->savePath) || !is_writable($this->savePath)) {
return $res->withJson(['message' => 'File location does not exist or is not writeable'], 401);
}
// TODO check filename
$store_filename = $this->savePath . DIRECTORY_SEPARATOR . $filename;
if (($save = file_put_contents($store_filename, $filecontent)) === false) {
return $res->withJson(['message' => 'Cannot save file for processing'], 401);
}
$this->logger->info("validate::{$store_filename}");
return $res->withJson([
'ok' => 'done',
'file' => $store_filename,
// 'parsedBody' => $parsedBody,
// 'content' => $contents,
], 200);
}
public function setDebug($debug = true)
{
$this->client->setDebug($debug === true);
return;
}
/**
* Send a JSON formatted string as JSON response to the client.
*
* @param Response $res
* @param mixed $data The data
* @param int $status The HTTP status code.
* @return response
*/
public function withJsonReady($res, $data, $status = null)
{
$response = $res->withBody(new Body(fopen('php://temp', 'r+')));
$response->getBody()->write($data);
$jsonResponse = $response->withHeader('Content-Type', 'application/json;charset=utf-8');
if (isset($status)) {
return $jsonResponse->withStatus($status);
}
return $jsonResponse;
}
/**
* Send a text response string as text/plain response to the client.
*
* @param Response $res
* @param mixed $data The text
* @param int $status The HTTP status code.
* @return response
*/
public function withTextReady($res, $data, $status = null)
{
$response = $res->withBody(new Body(fopen('php://temp', 'r+')));
$response->getBody()->write($data);
$textResponse = $response->withHeader('Content-Type', 'text/plain');
if (isset($status)) {
return $textResponse->withStatus($status);
}
return $textResponse;
}
protected function log($msg)
{
if ($this->logger) {
$this->logger->info($msg);
}
}
}
<?php
namespace Gr\Gov\Minedu\Osteam\Slim;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
if (!function_exists('getallheaders'))
{
function getallheaders()
{
$headers = '';
foreach ($_SERVER as $name => $value)
{
if (substr($name, 0, 5) == 'HTTP_')
{
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
}
class AuthorizationGuard
{
private $_username;
private $_password;
public function __construct($username, $password)
{
$this->_username = $username;
$this->_password = $password;
}
/**
* Check for authorization basic token
*
* @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request
* @param \Psr\Http\Message\ResponseInterface $response PSR7 response
* @param callable $next Next middleware
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
$auth = true;
$headers = getallheaders();
if (array_key_exists('Authorization', $headers)) {
$header = $headers['Authorization'];
$auth_parts = [];
if (preg_match('/^Basic (.+)$/', $header, $auth_parts) === 1) {
if ($auth_parts[1] !== base64_encode("{$this->_username}:{$this->_password}")) {
$auth = [
"message" => "Error: Invalid Credentials"
];
}
} else {
$auth = [
"message" => "Error: Mallformed Authorization Header"
];
}
} else {
$auth = [
"message" => "Error: Missing Authorization Header"
];
}
if ($auth !== true) {
return $response->withJson($auth, 401);
} else {
return $next($request, $response);
}
}
}
<?php
/*
*
*/
namespace Gr\Gov\Minedu\Osteam\Slim;
use Exception;
/**
* Description of Client
*
* @author spapad
*/
class Client
{
private $_debug = false;
private $_settings = [
'base_uri' => '' // must set this
];
public function __construct($settings = [])
{
$this->_settings = array_merge($this->_settings, $settings);
}
protected function setCommonCurlOptions($ch, $uri, $headers)
{
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, "OSTEAM SLIM client");
if (isset($this->_settings['NO_SAFE_CURL']) && $this->_settings['NO_SAFE_CURL'] === true) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
if ($this->_debug === true) {
curl_setopt($ch, CURLOPT_VERBOSE, true);
}
}
public function put($uri, $payload, $headers = [])
{
$ch = curl_init();
$this->setCommonCurlOptions($ch, $uri, $headers);
// curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception("Λάθος κατά την κλήση του {$uri}. Curl error: " . curl_error($ch) . " Curl info: " . var_export(curl_getinfo($ch), true));
}
if (intval(($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) / 100) != 2) {
// πραγματοποιήθηκε κλήση αλλά δεν ήταν "επιτυχής"
throw new Exception("Αποτυχημένη κλήση. HTTP STATUS {$http_code}. Η απάντηση ήταν: {$result}", $http_code);
}
curl_close($ch);
return $result;
}
public function post($uri, $payload, $headers = [])
{
$ch = curl_init();
$this->setCommonCurlOptions($ch, $uri, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception("Λάθος κατά την κλήση του {$uri}. Curl error: " . curl_error($ch) . " Curl info: " . var_export(curl_getinfo($ch), true));
}
if (intval(($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) / 100) != 2) {
// πραγματοποιήθηκε κλήση αλλά δεν ήταν "επιτυχής"
throw new Exception("Αποτυχημένη κλήση. HTTP STATUS {$http_code}. Η απάντηση ήταν: {$result}", $http_code);
}
curl_close($ch);
return $result;
}
public function get($uri, $params = [], $headers = [])
{
$ch = curl_init();
if (is_array($params) && count($params) > 0) {
$qs = '?' . http_build_query($params);
} else {
$qs = '';
}
$this->setCommonCurlOptions($ch, "{$uri}{$qs}", $headers);
// curl_setopt($ch, CURLOPT_HTTPGET, true); // default
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception("Λάθος κατά την κλήση του {$uri}. Curl error: " . curl_error($ch) . " Curl info: " . var_export(curl_getinfo($ch), true));
}
if (intval(($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) / 100) != 2) {
// πραγματοποιήθηκε κλήση αλλά δεν ήταν "επιτυχής"
return [
'success' => false,
'http_status' => $http_code,
'response' => $result
];
// throw new Exception("Αποτυχημένη κλήση. HTTP STATUS {$http_code}. Η απάντηση ήταν: {$result}", $http_code);
}
curl_close($ch);
return [
'success' => true,
'http_status' => $http_code,
'response' => $result
];
}
public function setDebug($debug = true)
{
$this->_debug = ($debug === true);
return;
}
}
<?php
$app->get('/validate', '\Gr\Gov\Minedu\Osteam\Slim\App:greet');
$app->post('/validate', '\Gr\Gov\Minedu\Osteam\Slim\App:validate')
->setName('validate');
$app->any('/[{anythingelse}]', function ($request, $response, $args) {
$this->logger->info("Void response, no action route was enabled");
return $response->withJson([
'message' => 'Your request is not valid',
'in' => var_export($args, true)
], 404
);
});
<?php
return [
'settings' => [
'displayErrorDetails' => true, // set to false in production
'addContentLengthHeader' => false, // Allow the web server to send the content-length header
// Renderer settings
'renderer' => [
'template_path' => __DIR__ . '/../templates/',
],
// Monolog settings
'logger' => [
'name' => 'slim-app',
'path' => __DIR__ . '/../logs/app.log',
'level' => \Monolog\Logger::DEBUG,
],
//
// app custom settings
'app' => [
'save_path' => __DIR__ . '/../logs',
'secure_endpoint_username' => 'username-for-this-wrapper',
'secure_endpoint_password' => 'password-for-this-wrapper'
]
],
];
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Slim 3</title>
<link href='//fonts.googleapis.com/css?family=Lato:300' rel='stylesheet' type='text/css'>
<style>
body {
margin: 50px 0 0 0;
padding: 0;
width: 100%;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
text-align: center;
color: #aaa;
font-size: 18px;
}
h1 {
color: #719e40;
letter-spacing: -3px;
font-family: 'Lato', sans-serif;
font-size: 100px;
font-weight: 200;
margin-bottom: 0;
}
</style>
</head>
<body>
<h1>Slim</h1>
<div>a microframework for PHP</div>
<?php if (isset($name)) : ?>
<h2>Hello <?= htmlspecialchars($name); ?>!</h2>
<?php else: ?>
<p>Try <a href="http://www.slimframework.com">SlimFramework</a></p>
<?php endif; ?>
</body>
</html>
<?php
namespace Tests\Functional;
use Slim\App;
use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Http\Environment;
/**
* This is an example class that shows how you could set up a method that
* runs the application. Note that it doesn't cover all use-cases and is
* tuned to the specifics of this skeleton app, so if your needs are
* different, you'll need to change it.
*/
class BaseTestCase extends \PHPUnit_Framework_TestCase
{
/**
* Use middleware when running application?
*
* @var bool
*/
protected $withMiddleware = true;
/**
* Process the application given a request method and URI
*
* @param string $requestMethod the request method (e.g. GET, POST, etc.)
* @param string $requestUri the request URI
* @param array|object|null $requestData the request data
* @return \Slim\Http\Response
*/
public function runApp($requestMethod, $requestUri, $requestData = null)
{
// Create a mock environment for testing with
$environment = Environment::mock(
[
'REQUEST_METHOD' => $requestMethod,
'REQUEST_URI' => $requestUri
]
);
// Set up a request object based on the environment
$request = Request::createFromEnvironment($environment);
// Add request data, if it exists
if (isset($requestData)) {
$request = $request->withParsedBody($requestData);
}
// Set up a response object
$response = new Response();
// Use the application settings
$settings = require __DIR__ . '/../../src/settings.php';
// Instantiate the application
$app = new App($settings);
// Set up dependencies
require __DIR__ . '/../../src/dependencies.php';
// Register middleware
if ($this->withMiddleware) {
require __DIR__ . '/../../src/middleware.php';
}
// Register routes
require __DIR__ . '/../../src/routes.php';
// Process the application
$response = $app->process($request, $response);
// Return the response
return $response;
}
}
<?php
namespace Tests\Functional;
class HomepageTest extends BaseTestCase
{
/**
* Test that the index route returns a rendered response containing the text 'SlimFramework' but not a greeting
*/
public function testGetHomepageWithoutName()
{
$response = $this->runApp('GET', '/');
$this->assertEquals(200, $response->getStatusCode());
$this->assertContains('SlimFramework', (string)$response->getBody());
$this->assertNotContains('Hello', (string)$response->getBody());
}
/**
* Test that the index route with optional name argument returns a rendered greeting
*/