People forgive me for my English,
These last week I had to make a change from this oauth lucadegasperi / oauth2-server-laravel to the passport with the migration to laravel 5.6. However in my authentication the oauth always returns me access denied, my midddleware is like this.
use Closure;
use Illuminate\Http\Request;
use Response;
use Input;
use Hash;
use App\Usuarios;
use Lang;
use Auth;
use Laravel\Passport\TokenRepository;
use League\OAuth2\Server\ResourceServer;
use League\OAuth2\Server\Exception\OAuthServerException;
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
class OAuth2Middleware {
protected $server;
protected $tokens;
public function __construct(ResourceServer $server, TokenRepository $tokens) {
$this->server = $server;
$this->tokens = $tokens;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
try {
if( $this->validateToken( $request) === null ){
return $next($request);
}
}
catch (Exception\InvalidRequestException $e) { }
catch (Exception\AccessDeniedException $e) { }
$http_codigo = 499;
$retorno['tipo'] = 'erro';
$retorno['mensagem'] = Lang::get('webservice.acesso_negado');
return response( json_encode( $retorno ) , $http_codigo);
}
public function validateToken(Request $request, $localCall = false) {
try {
$psr = (new DiactorosFactory)->createRequest($request);
$psr = $this->server->validateAuthenticatedRequest($psr);
$token = $this->tokens->find(
$psr->getAttribute('oauth_access_token_id')
);
$currentDate = new DateTime();
$tokenExpireDate = new DateTime($token->expires_at);
$isAuthenticated = $tokenExpireDate > $currentDate ? true : false;
if($localCall) {
return $isAuthenticated;
}
else {
return json_encode(array('authenticated' => $isAuthenticated));
}
} catch (OAuthServerException $e) {
if($localCall) {
return false;
}
else {
return json_encode(array('error' => 'Algo ocorreu de errado com a autenticaĆ§Ć£o'));
}
}
}
}
but when you run this method validateAuthenticatedRequest() return not authorizate ever ! The request is right, with bearer and others informations ,What could be going wrong based on the posted code? Any help is welcome, I do not know what else to do..
Tks
Related
What's wrong with my code? I can't pass variable from my Auth middleware to controller. In controller, the attribute "null".
Index:
$c = new \Slim\Container($configuration);
$api = new \Slim\App($c);
$api->group('/', function () use ($api) {
$this->post('login', '\AuthController:login');
...
$this->post('getIngredientsCategories', '\IngredientsController:getIngredientsCategories');
})->add(new ApiAuthenticateController());
$api->run();
Middleware (ApiAuthenticateController)
use \Firebase\JWT\JWT;
class ApiAuthenticateController
{
public function __invoke($request, $response, $next)
{
$jwtDecoded = null;
$req = $request->getUri()->getPath();
$_req = RequestValidatorController::isRequestEnabled($req);
if ($_req !== false) {
if ($_req['login_required']) {
$jwt = filter_var($request->getHeaderLine('AUTHORIZATION'), FILTER_SANITIZE_STRING);
$jwt = explode(" ", $jwt)[1];
try {
$jwtDecoded = JWT::decode($jwt, JWT_SECRET, array('HS256'));
} catch (\Exception $e) {
return $this->deny_access($response);
}
}
$request = $request->withAttribute('foo', $jwtDecoded);
//HERE - attribute "foo" in $request exists - checked by var_dump()..
$response = $next($request, $response);
$response = $response->withHeader('Content-type', 'application/json');
return $response;
} else {
return $this->deny_access($response);
}
}
IngredientsController
class IngredientsController extends Controller
{
private $_ingredients;
public function __construct(\Interop\Container\ContainerInterface $container)
{
parent::__construct($container);
}
}
Controller
class Controller
{
private $request;
private $response;
protected $data;
protected $method;
protected $user;
public function __construct(Interop\Container\ContainerInterface $container)
{
$this->request = $container->get('request');
$this->response = $container->get('response');
$this->data = (object)Tools::stripInput($this->request->getParsedBody());
$this->method = $this->request->getUri()->getPath();
$this->user = $this->request->getAttribute('foo');
var_dump($this->user);
// returns NULL. if $this->request->getAttributes()... returns empty
}
}
Please note, that code is "cleaned" for this post and for better readability, some functions and conditions where deleted. Code is working - sorry for possible typos.
the problem is coming from here
in the middleware ApiAuthenticateController, you should change the code like this
$request = $request->withAttribute('foo', $jwtDecoded);
// you should return the $next here not to do anything else
return $next($request, $response);
and in your IngredientsController:getIngredientsCategories part of code you should return the
function getIngredientsCategories ($request, $response, $args){
//do your job...
$response = $response->withHeader('Content-type', 'application/json');
return $response;
}
and finally, in the constructor, you have don't have the actual $request after the middleware I think so you would have the $this->request->getAttributes() inside your getIngredientsCategories function
Hope it helps.
I am using a middleware to redirect to login page if session is not set.
$app->get('/dashboard', function (Request $request, Response $response, $args) {
include_once('employee-portal/dashboard.php');
return $response;})->add(new AuthMiddleware('counter', true, $app->getContainer()));
and my middleware:
class AuthMiddleware implements MiddlewareInterface{
private $min_role = 'counter';
private $redirect = true;
private $container = null;
public function __construct($role_required, $login_redirect, $container)
{
$this->min_role = $role_required;
$this->redirect = $login_redirect;
$this->container = $container;
}
public function __invoke($request, $response, $next)
{
if ($this->userIsAuthorised()) {
return $next($request, $response);
} else {
if ($this->redirect) {
/**
* #var \Slim\Router router`
*/
return $response->withRedirect(Details::getBaseUrl() . '/login' . '?ref=' . $request->getUri());
}
return $response->withStatus(401)->write("Sorry boss you are not authorised to see my secret");
}
}
private function userIsAuthorised()
{
if ($this->min_role == 'counter') {
return true;
} else if (SessionManager::isLoggedIn()) {
if ($_SESSION['user_type']=='counter') {
return true;
}
}
return false;
} }
but this doesn't works.
i can even see the dashboard page without login. and even after login i cannot access the $_SESSION['user_type'] session variable.
any help would be appriciated. thanks in advance.
You are passing 'counter' into your AuthMiddleware constructor, causing it to always return true in the first if() statement of userIsAuthorised() method.
if ($this->min_role == 'counter')
will always be true because you set $this->min = 'counter' in your constructor. Try rewriting the new AuthMiddleware() and constructor so that you just pass in the container. Before calling the new AuthMiddleware() you can do the following:
$container['min_role'] = 'counter' if you need it elsewhere in your app.
I'm developing an application with symfony3, in which I'm tracking routes and saving them into my db with a service. This service is saving also a null route when there is an exception ( 500 , 404 ... ) so I want to add something to avoid saving this.
This is my service:
<?php
namespace Alpha\VisitorTrackingBundle\EventListener;
use Alpha\VisitorTrackingBundle\Entity\Lifetime;
use Alpha\VisitorTrackingBundle\Entity\PageView;
use Alpha\VisitorTrackingBundle\Entity\Session;
use Doctrine\ORM\EntityManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class VisitorTrackingSubscriber
* #package Alpha\VisitorTrackingBundle\EventListener
*
* Tracks the source of a session and each pageview in that session. Primary use of this is to be able to see the path through our site each
*/
class VisitorTrackingSubscriber implements EventSubscriberInterface
{
/**
* #var \Doctrine\ORM\EntityManager
*/
protected $em;
/**
* #var Session
*/
protected $session;
/**
* #var Lifetime
*/
protected $lifetime;
protected $routesExclues;
protected $utmCodes = [
"utm_source",
"utm_medium",
"utm_campaign",
"utm_term",
"utm_content"
];
const COOKIE_LIFETIME = "lifetime";
const COOKIE_SESSION = "session";
public function __construct(EntityManager $em, $routesExclues)
{
$this->em = $em;
$this->routesExclues = $routesExclues;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (substr($request->get("_route"), 0, 1) == "_" ) {
//these are requests for assets/symfony toolbar etc. Not relevant for our tracking
return;
}
if ($request->cookies->has(self::COOKIE_SESSION) and !$this->requestHasUTMParameters($request)) {
$this->session = $this->em->getRepository("AlphaVisitorTrackingBundle:Session")->find($request->cookies->get(self::COOKIE_SESSION));
if ($this->session instanceof Session) {
$this->lifetime = $this->session->getLifetime();
} else {
$this->generateSessionAndLifetime($request);
}
} else {
$this->generateSessionAndLifetime($request);
}
}
public function onKernelResponse(FilterResponseEvent $event)
{
if (false === $this->session instanceof Session) {
return;
}
$request = $event->getRequest();
$response = $event->getResponse();
$exception = $event->getKernel()->handle($request)->getStatusCode();
if (substr($request->get("_route"), 0, 1) == "_" or ($response instanceof RedirectResponse) ) {
//these are requests for assets/symfony toolbar etc. Not relevant for our tracking
return;
}
$pageView = new PageView();
$route = $request->get('_route');
$pageView->setUrl($route);
if (strpos($request->getRequestUri(), $this->routesExclues) === false // && $response->getStatusCode() === '200'
)
$this->session->addPageView($pageView);
$this->em->flush($this->session);
if ($this->requestHasUTMParameters($request)) {
$this->setUTMSessionCookies($request, $response);
}
if (!$request->cookies->has(self::COOKIE_LIFETIME)) {
$response->headers->setCookie(new Cookie(self::COOKIE_LIFETIME, $this->lifetime->getId(), 0, "/", null, false, false));
}
//no session cookie set OR session cookie value != current session ID
if (!$request->cookies->has(self::COOKIE_SESSION) or ($request->cookies->get(self::COOKIE_SESSION) != $this->session->getId())) {
$response->headers->setCookie(new Cookie(self::COOKIE_SESSION, $this->session->getId(), 0, "/", null, false, false));
}
}
protected function requestHasUTMParameters(Request $request)
{
foreach ($this->utmCodes as $code) {
if ($request->query->has($code)) {
return true;
}
}
return false;
}
protected function setUTMSessionCookies(Request $request, Response $response)
{
foreach ($this->utmCodes as $code) {
$response->headers->clearCookie($code);
if ($request->query->has($code)) {
$response->headers->setCookie(new Cookie($code, $request->query->get($code), 0, "/", null, false, false));
}
}
}
/**
* #return Session
*/
public function getSession()
{
return $this->session;
}
/**
* #return Lifetime
*/
public function getLifetime()
{
return $this->lifetime;
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::RESPONSE => ['onKernelResponse', 1024],
KernelEvents::REQUEST => ["onKernelRequest", 16]
);
}
private function generateSessionAndLifetime(Request $request)
{
if (strpos($request->headers->get("User-Agent"), "bot") === false && $request->getClientIp() !== "::1"
) {
$lifetime = false;
if ($request->cookies->has(self::COOKIE_LIFETIME)) {
$lifetime = $this->em->getRepository("AlphaVisitorTrackingBundle:Lifetime")->find($request->cookies->get(self::COOKIE_LIFETIME));
}
if (!$lifetime) {
$lifetime = new Lifetime();
$this->em->persist($lifetime);
}
$session = new Session();
$session->setIp($request->getClientIp() ?: "");
$session->setReferrer($request->headers->get("Referer") ?: "");
$session->setUserAgent($request->headers->get("User-Agent") ?: "");
$session->setQueryString($request->getQueryString() ?: "");
$session->setLoanTerm($request->query->get("y") ?: "");
$session->setRepApr($request->query->has("r") ? hexdec($request->query->get("r")) / 100 : "");
$details = json_decode(file_get_contents("http://ipinfo.io/{$request->getClientIp()}/json"));
$names = json_decode(file_get_contents("http://country.io/names.json"), true);
$session->setPays($names[$details->country]);
foreach ($this->utmCodes as $code) {
$method = "set" . \Doctrine\Common\Inflector\Inflector::classify($code);
$session->$method($request->query->get($code) ?: "");
}
$lifetime->addSession($session);
$this->em->flush();
$this->session = $session;
$this->lifetime = $lifetime;
}
}
}
I have added something to get statusCode from response but it always
returns 200. ( if statusCode !== '200' it must not save route).
Anyone to help me to get an idea or a solution to my problem? Thanks
I have been giving myself a headache over this all day,
I've been learning Symfony over the past couple days and my problem is simple, I need to be able to log in with 3 parameters (username, password and company)
The same question has been asked here, however the asker never provided a solution:
Custom Login using a Third Parameter
I have tried to start by cloning Symfony's inbuilt login by implementing a Token, Listener, Provider and Factory but whenever I insert my key into security.yml and try to log in it takes me to /login (No route found for "GET /login")
Anyone care to make my day?
EDIT:
OK, I Just tried again and now I have this error:
Catchable Fatal Error: "Argument 1 passed to Test\SampleBundle\Security\Authentication\Provider\MyProvider::__construct() must be an instance of Symfony\Component\Security\Core\User\UserCheckerInterface, instance of Symfony\Bridge\Doctrine\Security\User\EntityUserProvider given"
Again all I'm trying to do is duplicate Symfonys current user/password login functionality
MyToken.php:
namespace Test\SampleBundle\Security\Authentication\Token;
use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
class MyToken extends AbstractToken
{
private $credentials;
private $providerKey;
public function __construct($user, $credentials, $providerKey, array $roles = array())
{
parent::__construct($roles);
if (empty($providerKey)) {
throw new \InvalidArgumentException('$providerKey must not be empty.');
}
$this->setUser($user);
$this->credentials = $credentials;
$this->providerKey = $providerKey;
parent::setAuthenticated(count($roles) > 0);
}
public function setAuthenticated($isAuthenticated)
{
if ($isAuthenticated) {
throw new \LogicException('Cannot set this token to trusted after instantiation.');
}
parent::setAuthenticated(false);
}
public function getCredentials()
{
return $this->credentials;
}
public function getProviderKey()
{
return $this->providerKey;
}
public function eraseCredentials()
{
parent::eraseCredentials();
$this->credentials = null;
}
public function serialize()
{
return serialize(array($this->credentials, $this->providerKey, parent::serialize()));
}
public function unserialize($serialized)
{
list($this->credentials, $this->providerKey, $parentStr) = unserialize($serialized);
parent::unserialize($parentStr);
}
}
MyListener.php:
<?php
namespace Test\SampleBundle\Security\Firewall;
use Symfony\Component\Security\Http\Firewall\AbstractAuthenticationListener;
use Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Test\SampleBundle\Security\Authentication\Token\MyToken;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class MyListener extends AbstractAuthenticationListener
{
private $csrfProvider;
public function __construct(SecurityContextInterface $securityContext, AuthenticationManagerInterface $authenticationManager, SessionAuthenticationStrategyInterface $sessionStrategy, HttpUtils $httpUtils, $providerKey, AuthenticationSuccessHandlerInterface $successHandler, AuthenticationFailureHandlerInterface $failureHandler, array $options = array(), LoggerInterface $logger = null, EventDispatcherInterface $dispatcher = null, CsrfProviderInterface $csrfProvider = null)
{
parent::__construct($securityContext, $authenticationManager, $sessionStrategy, $httpUtils, $providerKey, $successHandler, $failureHandler, array_merge(array(
'username_parameter' => '_username' . 'b',
'password_parameter' => '_password',
'csrf_parameter' => '_csrf_token',
'intention' => 'authenticate',
'post_only' => true,
), $options), $logger, $dispatcher);
$this->csrfProvider = $csrfProvider;
}
protected function requiresAuthentication(Request $request)
{
if ($this->options['post_only'] && !$request->isMethod('POST')) {
return false;
}
return parent::requiresAuthentication($request);
}
protected function attemptAuthentication(Request $request)
{
if (null !== $this->csrfProvider) {
$csrfToken = $request->get($this->options['csrf_parameter'], null, true);
if (false === $this->csrfProvider->isCsrfTokenValid($this->options['intention'], $csrfToken)) {
throw new InvalidCsrfTokenException('Invalid CSRF token.');
}
}
if ($this->options['post_only']) {
$username = trim($request->request->get($this->options['username_parameter'], null, true));
$password = $request->request->get($this->options['password_parameter'], null, true);
} else {
$username = trim($request->get($this->options['username_parameter'], null, true));
$password = $request->get($this->options['password_parameter'], null, true);
}
$request->getSession()->set(SecurityContextInterface::LAST_USERNAME, $username);
return $this->authenticationManager->authenticate(new MyToken($username, $password, $this->providerKey));
}
}
MyProivder.php:
namespace Test\SampleBundle\Security\Authentication\Provider;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\AuthenticationServiceException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Test\SampleBundle\Security\Authentication\Token\MyToken;
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
class MyProvider implements AuthenticationProviderInterface
{
private $hideUserNotFoundExceptions;
private $userChecker;
private $providerKey;
public function __construct(UserCheckerInterface $userChecker, $providerKey, $hideUserNotFoundExceptions = true)
{
if (empty($providerKey)) {
throw new \InvalidArgumentException('$providerKey must not be empty.');
}
$this->userChecker = $userChecker;
$this->providerKey = $providerKey;
$this->hideUserNotFoundExceptions = $hideUserNotFoundExceptions;
}
public function authenticate(TokenInterface $token)
{
if (!$this->supports($token)) {
return null;
}
$username = $token->getUsername();
if (empty($username)) {
$username = 'NONE_PROVIDED';
}
try {
$user = $this->retrieveUser($username, $token);
} catch (UsernameNotFoundException $notFound) {
if ($this->hideUserNotFoundExceptions) {
throw new BadCredentialsException('Bad credentials', 0, $notFound);
}
$notFound->setUsername($username);
throw $notFound;
}
if (!$user instanceof UserInterface) {
throw new AuthenticationServiceException('retrieveUser() must return a UserInterface.');
}
try {
$this->userChecker->checkPreAuth($user);
$this->checkAuthentication($user, $token);
$this->userChecker->checkPostAuth($user);
} catch (BadCredentialsException $e) {
if ($this->hideUserNotFoundExceptions) {
throw new BadCredentialsException('Bad credentials', 0, $e);
}
throw $e;
}
$authenticatedToken = new MyToken($user, $token->getCredentials(), $this->providerKey, $user->getRoles());
$authenticatedToken->setAttributes($token->getAttributes());
return $authenticatedToken;
}
public function supports(TokenInterface $token)
{
return $token instanceof MyToken && $this->providerKey === $token->getProviderKey();
}
/**
* {#inheritdoc}
*/
protected function checkAuthentication(UserInterface $user, MyToken $token)
{
$currentUser = $token->getUser();
if ($currentUser instanceof UserInterface) {
if ($currentUser->getPassword() !== $user->getPassword()) {
throw new BadCredentialsException('The credentials were changed from another session.');
}
} else {
if ("" === ($presentedPassword = $token->getCredentials())) {
throw new BadCredentialsException('The presented password cannot be empty.');
}
if (!$this->encoderFactory->getEncoder($user)->isPasswordValid($user->getPassword(), $presentedPassword, $user->getSalt())) {
throw new BadCredentialsException('The presented password is invalid.');
}
}
}
/**
* {#inheritdoc}
*/
protected function retrieveUser($username, MyToken $token)
{
$user = $token->getUser();
if ($user instanceof UserInterface) {
return $user;
}
try {
$user = $this->userProvider->loadUserByUsername($username);
if (!$user instanceof UserInterface) {
throw new AuthenticationServiceException('The user provider must return a UserInterface object.');
}
return $user;
} catch (UsernameNotFoundException $notFound) {
$notFound->setUsername($username);
throw $notFound;
} catch (\Exception $repositoryProblem) {
$ex = new AuthenticationServiceException($repositoryProblem->getMessage(), 0, $repositoryProblem);
$ex->setToken($token);
throw $ex;
}
}
}
MyFactory.php
<?php
namespace Test\SampleBundle\DependencyInjection\Security\Factory;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
class MyFactory implements SecurityFactoryInterface
{
public function __construct()
{
$this->addOption('username_parameter', '_username');
$this->addOption('password_parameter', '_password');
$this->addOption('csrf_parameter', '_csrf_token');
$this->addOption('intention', 'authenticate');
$this->addOption('post_only', true);
}
public function getPosition()
{
return 'pre_auth';
}
public function getKey()
{
return 'mylogin';
}
public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint)
{
$providerId = 'security.authentication.provider.mylogin.'.$id;
$container
->setDefinition($providerId, new DefinitionDecorator('mylogin.security.authentication.provider'))
->replaceArgument(0, new Reference($userProvider))
;
$listenerId = 'security.authentication.listener.mylogin.'.$id;
$listener = $container->setDefinition($listenerId, new DefinitionDecorator('mylogin.security.authentication.listener'));
return array($providerId, $listenerId, $defaultEntryPoint);
}
public function addConfiguration(NodeDefinition $node)
{
}
protected function createEntryPoint($container, $id, $config, $defaultEntryPoint)
{
$entryPointId = 'security.authentication.form_entry_point.'.$id;
$container
->setDefinition($entryPointId, new DefinitionDecorator('security.authentication.form_entry_point'))
->addArgument(new Reference('security.http_utils'))
->addArgument($config['login_path'])
->addArgument($config['use_forward'])
;
return $entryPointId;
}
final public function addOption($name, $default = null)
{
$this->options[$name] = $default;
}
}
Services.yml:
services:
mylogin.security.authentication.provider:
class: Test\SampleBundle\Security\Authentication\Provider\MyProvider
arguments: ['', %kernel.cache_dir%/security/nonces]
mylogin.security.authentication.listener:
class: Test\SampleBundle\Security\Firewall\MyListener
arguments: [#security.context, #security.authentication.manager]
And finally injector:
namespace Test\SampleBundle;
use Test\SampleBundle\DependencyInjection\Security\Factory\MyFactory;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class TestSampleBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$extension = $container->getExtension('security');
$extension->addSecurityListenerFactory(new MyFactory());
}
}
There may be a few errors in the above code as I have been playing around with stuff to get it working
I wanted to add a function to my Slim application but I'm not familiar enough with PHP to know the best way to structure something like this. This is not production ready code and I obviously will not be hard coding my username and password into the script. I made this simply to illustrate the concept.
$options = array(
'username' => 'admin',
'password' => 'password'
);
$app = new Slim(array(
'view' => new TwigView()
));
$app->config($ptions);
function authenticate($app, $username, $password) {
if($username==$app->config('username') && $password==$app->config('password')){
return true;
} else {
return false;
}
}
$app->get('/', function () use ($app) { // ... }
// ... other routes
$app->post('/login', function() use ($app) {
$username = $app->request()->post('username');
$password = $app->request()->post('password');
if(authenticate($app, $username,$password)) {
$app->redirect('/');
}
$app->redirect('/login');
});
$app->run();
Does it make sense to have to pass $app to authenticate() or is there a better way? authenticate() would not be middleware, but a function called in the POST route for pressing submit on a login form.
I suggest you use registry method.. ohbtw $app->config($ptions); should be $app->config($options);
as for "registry", I use the following class:
<?
class Registry {
private static $data;
/**
* Returns saved variable named $key
* #param string $key
* #return mixed
*/
public static function get($key) {
if(!empty(self::$data[$key])) {
return self::$data[$key];
}
return null;
}
/**
* Saves variable to registry with the name $key
* #param string $key
* #param mixed $value
* #return boolean
*/
public static function set($key, $value) {
if(!empty($value)) {
self::$data[$key] = $value;
return true;
}
return false;
}
}
?>
to save use
Registry::set('key', $value);
to retrieve use
Registry::get('key');