rluders / wn-jwtauth-plugin

JWTAuth Plugin for WinterCMS
GNU General Public License v3.0
29 stars 28 forks source link

Get user from token in my middleware #24

Closed venumdev closed 5 years ago

venumdev commented 5 years ago

Hi to all, I want to create my middleware which allow user to access api based on the group they belong to.

Is it possible to get user from token without provide user_id in the params call?

With JWT Auth API Plugin i can get current user with JWTAuth::parseToken()->authenticate(); But in this plugin is not possible.

Can you help me? Thanks.

rluders commented 5 years ago

Hi @venumdev,

Here, an example that shows how you can get the logged user:

https://github.com/rluders/oc-jwtauth-plugin/blob/master/http/controllers/GetUserController.php

If you need to get the user by the token, here another example:

https://github.com/rluders/oc-jwtauth-plugin/blob/master/http/controllers/RefreshTokenController.php

You also have the JWTAuth alias registered, so, maybe it's possible to use it. This plugin is an implementation of tymondesigns/jwt-auth and you can find the documentation here. Hopefully, most of the things should be the same.

venumdev commented 5 years ago

Thanks for reply. I want to use that code in middleware but __invoke magic method not work, It return error.

Middleware is like this:

class MyMiddleware{
    public function handle($request, \Closure $next)
    {
        ........
        return $next($request);
    }
}

How can i pass JWTAuth $auth parameter to the handle method?

Thanks

rluders commented 5 years ago

Hello, @venumdev.

So, actually, I can't use dependency injection into the middleware handle method. In this case you can inject the JWTAuth into the class constructor, and set it as a property. Try to do something like this:

class MyMiddleware
{
    protected $auth;

    public function __constructor(JWTAuth $auth)
    {
        $this->auth = $auth;
    }

    public function handle(Request $request, Closure $next)
    {
        $user = $this->auth->user();
        // check the permissions here
    }
}

Again, I didn't have time to test it, the code just came to my mind. Anyway, I think there's also other ways to do it, since the JWTAuth is registred as an alias and it's a Facade, you could probably just call JWTAuth::user() and it will give you the user, like this:

class MyMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $user = JWTAuth::user();
        // check the permissions here
    }
}

Please, let me know if it helps you.