Botnary / wp-slim-framework

Slim framework as Wordpress plugin
73 stars 26 forks source link

How can I use middleware for authentication? #2

Closed Tropicalista closed 9 years ago

Tropicalista commented 9 years ago

I'm trying to use this plugin to convert an app made with slim to a wordpress plugin.

However I need a way to protect access to routes and I was using a middleware to check if user is logged in.

So I have added this line:

require_once 'Slim/Middleware/HttpBasicAuth.php';

But I got this error:

Fatal error: Class 'Slim\Middleware' not found in E:\wamp\www\Blog\wp-content\plugins\wp-slim-framework\Slim\Middleware\HttpBasicAuth.php on line 6

It seems that my middleware cannot extends parent class:

namespace Slim\Middleware;

class HttpBasicAuth extends \Slim\Middleware

COuld you help me? I should try another approach? What is the better way to check if user is authenticated to prevent access to routes?

Thanks

Botnary commented 9 years ago

If you use Slim Framework as a Wordpress plugin then in your routes you have access to Wordpress API. i would do something like this:

add_action('slim_mapping',function($app){
    $app->get('/slim/api/books',function(){
        //wordpress current user
        $user = wp_get_current_user(); // this function returns current user as a Wp_User object.
        if($user->ID > 0) { // it means that there is a user online
            //do something as logged in user.
        }
    });
});

and actually this is how i do it, and i don't use any middlewares. Also you should not access directly Slim files with include, but use composer autoloader. So in your code if you need any class from Slim just do this:

use \Slim\Middleware;
$auth = new HttpBasicAuth();

and autoloader will find the required file automatically for you.