api.emotionhero.com/www/index.php

184 lines
5.7 KiB
PHP

<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
require __DIR__ . '/../bootstrap.php';
$eh = EmotionHero\Application::getInstance();
$app = new Silex\Application([
'debug' => $eh->getConfig()['debug']
]);
// disable when going in production.
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(ini_get('max_file_uploads') < 50) {
throw new Exception("php directive 'max_file_uploads' should be >= 50");
}
// $http_origin = $_SERVER['HTTP_ORIGIN'];
// if ($http_origin == "https://emotionhero.com" || $http_origin == "http://emotionhero.com")
// {
// header("Access-Control-Allow-Origin: $http_origin");
// // header("Access-Control-Allow-Origin: https://emotionhero.com");
// header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
// header("Access-Control-Allow-Headers: X-PINGOTHER");
// header("Access-Control-Max-Age: 1728000");
// }
/*
* JWT setup
*/
define('USER_ID_FIELD', 'id');
$app['entity.manager'] = function() {
return EmotionHero\Application::getInstance()->getEm();
};
$app['file.path'] = realpath(__DIR__ . "/../files");
$app['security.jwt'] = [
'secret_key' => $eh->getConfig()['secret_key'],
'life_time' => $eh->getConfig()['jwt_lifetime'],
'options' => [
'username_claim' => USER_ID_FIELD, // default name, option specifying claim containing username
'header_name' => 'X-Access-Token', // default null, option for usage normal oauth2 header
'token_prefix' => 'Bearer',
]
];
$app['users'] = function () use ($eh) {
return $eh->getEm()->getRepository(EmotionHero\Models\User::class);
};
$app['serializer'] = function () use ($eh) {
return JMS\Serializer\SerializerBuilder::create()->build();
};
$app['serializer.json'] = function () use ($app) {
return function($data) use ($app) {
return $app['serializer']->serialize($data, 'json');
};
};
$app['security.firewalls'] = array(
'login' => [
'pattern' => 'login|register|oauth|token|interface|stats',
'anonymous' => true,
],
'secured' => array(
'pattern' => '^.*$',
'logout' => array('logout_path' => '/logout'),
'users' => $app['users'],
'jwt' => array(
'use_forward' => true,
'require_previous_session' => false,
'stateless' => true,
)
),
);
$app->register(new Silex\Provider\SecurityServiceProvider());
$app->register(new Silex\Provider\SecurityJWTServiceProvider());
$app->get('/sysinfo', function(Request $request) use ($app){
phpinfo();
return new Response(200);
});
/**
* Get token for user
*/
$app->post('/api/register', function(Request $request) use ($app, $eh){
// return $app['serializer']->serialize($eh->getEm()->getRepository(EmotionHero\Models\User::class)->findAll(), 'json');
// validate user with... NOTING!!!
$user = new EmotionHero\Models\User();
$eh->getEm()->persist($user);
$eh->getEm()->flush();
return $app['serializer']->serialize($user, 'json');
});
/**
* Get token for user with UUID
* As it is already a generated token.. don't use password
*/
$app->post('/api/token', function(Request $request) use ($app){
$vars = json_decode($request->getContent(), true);
try {
if (empty($vars['userid'])) {
throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $vars['userid']));
}
/**
* @var $user EmotionHero\Models\User
*/
$user = $app['users']->loadUserByUsername($vars['userid']);
if (! $user) {
// if (! $app['security.encoder.digest']->isPasswordValid($user->getPassword(), $vars['password'], '')) { // no password set
throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $vars['userid']));
} else {
$response = [
'success' => true,
'token' => $app['security.jwt.encoder']->encode([USER_ID_FIELD => $user->getUsername()]),
];
}
} catch (UsernameNotFoundException $e) {
$response = [
'success' => false,
'error' => 'Invalid credentials',
];
}
return $app->json($response, ($response['success'] == true ? Response::HTTP_OK : Response::HTTP_BAD_REQUEST));
})
;
/* EXAMPLE
$app->get('/api/protected_resource', function() use ($app){
$token = $app['security.token_storage']->getToken();
$jwt = 'no';
$token = $app['security.token_storage']->getToken();
if ($token instanceof Silex\Component\Security\Http\Token\JWTToken) {
$jwt = 'yes';
}
$granted = 'no';
if($app['security.authorization_checker']->isGranted('ROLE_ADMIN')) {
$granted = 'yes';
}
$granted_user = 'no';
if($app['security.authorization_checker']->isGranted('ROLE_USER')) {
$granted_user = 'yes';
}
$granted_super = 'no';
if($app['security.authorization_checker']->isGranted('ROLE_SUPER_ADMIN')) {
$granted_super = 'yes';
}
$user = $token->getUser();
return $app->json([
'hello' => $token->getUsername(),
'username' => $user->getUsername(),
'auth' => $jwt,
'granted' => $granted,
'granted_user' => $granted_user,
'granted_super' => $granted_super,
]);
});*/
$app->mount('/', new EmotionHero\Api\ScoreControllerProvider());
$app->mount('/interface', new EmotionHero\Api\InterfaceControllerProvider());
$app->mount('/stats', new EmotionHero\Api\StatsControllerProvider());
// middlewares
$appStack = new EmotionHero\Api\ThrottleMiddleware($app, ['pdo'=>$eh->getEm()->getConnection()->getWrappedConnection()] );
$appStack->handle(Request::createFromGlobals())->send();