Code Monkey home page Code Monkey logo

Comments (2)

sudofox avatar sudofox commented on June 14, 2024

I've gotten back to digging into this and I think it might be possible to use a rule or something, since the __invoke method required by the RuleInterface actually takes ServerRequestInterface ...? It seems like undocumented functionality though

This all seems rather flimsy to me though -- still unclear how I would first authenticate the user and then get the API method to check against their permissions. Maybe I'll have to drop this library or something but I feel like there's an obvious answer I'm missing here since being able to check if a user has permissions to access a particular route beyond a hardcoded set of credentials/paths should be elementary.

from slim-basic-auth.

sudofox avatar sudofox commented on June 14, 2024

I figured out an easier way to do it without using this library (sorry!)

I'm putting it here to save anyone else the time.

Here's a stripped down version that checks for basic auth and such, Slim 4 of course.

<?php

use YourApp\AuthMiddleware;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Routing\RouteContext;

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;


class AuthMiddleware implements MiddlewareInterface {
    /**
     * @var ResponseFactoryInterface
     */
    private $responseFactory;

    /**
     * @param ResponseFactoryInterface $responseFactory
     */
    public function __construct(ResponseFactoryInterface $responseFactory) {
        $this->responseFactory = $responseFactory;
    }

    /**
     * @inheritDoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {

        $failure = $this->responseFactory->createResponse();
        $failure->getBody()->write('Authorization denied');
        $failure = $failure->withStatus(401);


        if (!isset($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) {
            // auth not provided
            return $failure->withAddedHeader("X-Debug", "auth not provided");
        }

        $username = $_SERVER["PHP_AUTH_USER"];
        $password = $_SERVER["PHP_AUTH_PW"];

        // do your auth stuff here

        $auth_condition_that_should_be_true = true;

        $user = [ "id" => 1 ]; // whatever data or object you need

        if (!$auth_condition_that_should_be_true) {
            // user doesn't exist
            return $failure->withAddedHeader("X-Debug", "user doesn't exist");
        }

        // now we can check that the user has permission
        $routeContext = RouteContext::fromRequest($request);
        $route = $routeContext->getRoute();
        $the_route  = $route->getPattern(); // /foo/bar/baz    

        $the_user_has_permission_for_route = true;

        if (!$the_user_has_permission_for_route) {
            // user doesn't have permission
            return $failure->withAddedHeader("X-Debug", "no permission for action");
        }

        // load the user so it's accessible in the request handler
        $newRequest = $request->withAttribute("user", $user);

        // Keep processing middleware queue as normal
        return $handler->handle($newRequest);
    }
}

And you can then do this:

<?php

// ... composer and whatever else ...

use YourApp\AuthMiddleware;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Slim\Psr7\Response;

$app = AppFactory::create();

$app->addMiddleware(new AuthMiddleware($app->getResponseFactory()));
$app->addRoutingMiddleware();

$app->get('/your/api/path', function (Request $request, Response $response, $args) {

    // you can get your user stuff here
    $user = $request->getAttribute("user");
    
    $result["user"] = [
        "id"             => $user->getId(),
        "username"       => $user->getUsername(),
    ];

    $response->getBody()->write(json_encode($result, JSON_PRETTY_PRINT));
    return $response;
});

$app->run();

from slim-basic-auth.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.