S
S
Sergey Shevchenko2016-06-01 17:48:39
User identification
Sergey Shevchenko, 2016-06-01 17:48:39

Silex + token + cURL + https://github.com/gonzalo123/token How to mix?

Guys, please tell me what I'm doing wrong ...
Task: I need to be able to log in via cURL.
The project is written in Silex.
I'm trying to implement authorization through a token according to this manual
Token based authentication with Silex Applications
GitHub Repository gonzalo123/token
I'm trying to log in and writes that the requested page was not found.
f1fb4b14e374454688182bff9994b6b6.png
Here's how I'm trying to port to my project
public \ index.php
fbb237c05b6e4abfb1df4ce8f410048c.png

require_once __DIR__ . '/../vendor/autoload.php';

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$app = new Silex\Application();

$app->after(function (Request $request, Response $response) {
    $response->headers->set('Access-Control-Allow-Origin', '*');
});

require_once __DIR__ . '/../app/routes.php';
require_once __DIR__ . '/../app/providers.php';

$app['debug'] = true;
$app->run();

app\ routes.php
4b0fcfd5bfe34daaad44a79d42b471dc.png
/** @var $app \Silex\Application */
$app->get('/', 'App\\Controller\\BaseController::index');
$app->get('/login', 'App\\Controller\\AuthController::login');

$app->mount('/cabinet', new \App\Provider\Rater());
$app->mount('/api', new \App\Provider\API());
$app->mount('/auth', new \App\Provider\LoginControllerProvider());

$app->error(
    function (\Exception $e, $code) use ($app) {
        $jsonResponse = false;

        switch ($code) {
            case 404:
                $message = '1 Запрашиваемая вами страница не найдена.';

                break;
            case 500:
                $message = $e->getMessage();
                $jsonResponse = 429 === $e->getCode();

                break;
            default:
                $message = '2 Невозможно обработать запрос.';
        }

        return $jsonResponse
            ? $app->json(['message' => $message], $e->getCode())
            : $app['twig']->render('error-page.html.twig', ['message' => $message]);
    }
);

app\ providers.php
fbb5e0a7117c4214b854a3df7bd708e9.png
/** @var $app Silex\Application */
require_once __DIR__ . '/config/config.php';

$app->register(new Silex\Provider\TwigServiceProvider(), $configTwig);
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
$app->register(new Silex\Provider\SessionServiceProvider());
$app->register(new Silex\Provider\SecurityServiceProvider(), $configSecurity);
$app->register(new Silex\Provider\DoctrineServiceProvider(), $configDatabase);
$app->register(new Silex\Provider\ServiceControllerServiceProvider(), $configServiceControllerService);
$app->register(new Silex\Provider\SwiftmailerServiceProvider(), $configSwiftmailer);
$app->register(new App\Services\LoginServiceProvider());

$app['auth.validate.credentials'] = $app->protect(function ($user, $pass) {
    return new App\Services\LoginServiceProvider;//->validateCredentials($user, $pass);
});

$app['auth.validate.token'] = $app->protect(function ($token) {
    return new App\Services\LoginServiceProvider;//->validateToken($token);
});

$app['auth.new.token'] = $app->protect(function ($user) {
    return new App\Services\LoginServiceProvider;//->getNewTokenForUser($user);
});

App\Provider\ LoginControllerProvider.php
7077d4101ac64e64ba7a8fddc3c00ad8.png
namespace App\Provider;

use Silex\Application;
use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class LoginControllerProvider implements ControllerProviderInterface
{
    const VALIDATE_CREDENTIALS = '/validateCredentials';
    const TOKEN_HEADER_KEY = 'X-Token';
    const TOKEN_REQUEST_KEY = '_token';
    private $baseRoute;

    public function setBaseRoute($baseRoute) {
        $this->baseRoute = $baseRoute;

        return $this;
    }

    public function connect(Application $app) {
        $this->setUpMiddlewares($app);

        return $this->extractControllers($app);
    }

    private function setUpMiddlewares(Application $app) {
        $app->before(function (Request $request) use ($app) {
            if (!$this->isAuthRequiredForPath($request->getPathInfo())) {
                if (!$this->isValidTokenForApplication($app, $this->getTokenFromRequest($request))) {
                    throw new AccessDeniedHttpException('Access Denied');
                }
            }
        }
        );
    }

    private function isAuthRequiredForPath($path) {
        return in_array($path, [$this->baseRoute . self::VALIDATE_CREDENTIALS]);
    }

    private function isValidTokenForApplication(Application $app, $token) {
        return $app['auth.validate.credentials']($token);
    }

    private function getTokenFromRequest(Request $request) {
        return $request->headers->get(self::TOKEN_HEADER_KEY, $request->get(self::TOKEN_REQUEST_KEY));
    }

    private function extractControllers(Application $app) {
        $controllers = $app['controllers_factory'];
        $controllers->get(self::VALIDATE_CREDENTIALS, function (Request $request) use ($app) {
            $user = $request->get('user');
            $pass = $request->get('pass');
            $status = $app['auth.validate.token']($user, $pass);

            return $app->json([
                    'status' => $status,
                    'info' => $status ? ['token' => $app['auth.new.token']($user)] : []
                ]
            );
        }
        );

        return $controllers;
    }
}

App\Provider\ LoginServiceProvider.php
d9a723795a184ade99dfed54170c4bc1.png
namespace App\Services;

use Silex\Application;
use Silex\ServiceProviderInterface;

class LoginServiceProvider implements ServiceProviderInterface
{

    public function register(Application $app) {
        $app['auth.validate.credentials'] = $app->protect(function ($user, $pass) {
            return $this->validateCredentials($user, $pass);
        });

        $app['auth.validate.token'] = $app->protect(function ($token) {
            return $this->validateToken($token);
        });

        $app['auth.new.token'] = $app->protect(function ($user) {
            return $this->getNewTokenForUser($user);
        });

    }

    public function validateCredentials($user, $pass) {
        return $user == $pass;
    }

    public function validateToken($token) {
        return $token == 'a';
    }

    public function getNewTokenForUser($user) {
        return 'a';
    }

    public function boot(Application $app) {
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Shevchenko, 2016-06-01
@lancer_serega

If suddenly something helps, then I noticed one thing...
If in the App\Provider\LoginControllerProvider.php file in the private function setUpMiddlewares
before $app->before(...) you write exit(), then it will work, and if after that no

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question