Now that we’ve seen the use of JWT and GraphQL, let’s see how they work together.

A profound

Create myProfile query


      
/** * User: yemeISHU * Date: 2018/4/21 * Time: 8:55 am */

namespace App\GraphQL\Query;

use App\User;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Rebing\GraphQL\Support\Query;
use Rebing\GraphQL\Support\SelectFields;
use Tymon\JWTAuth\Facades\JWTAuth;

class MyProfileQuery extends Query {
    private $auth;

    protected $attributes = [
        'name'= >'My Profile Query'.'description'= >'My Profile Information'
    ];

    public function authorize(array $args) {
        try {
            $this->auth = JWTAuth::parseToken()->authenticate();
        } catch (\Exception $e) {
            $this->auth = null;
        }

        return (boolean) $this->auth;
    }

    public function type(a) {
        return GraphQL::type('myprofile');
    }

    public function resolve($root, $args, SelectFields $fields) {
        $user = User::with(array_keys($fields->getRelations()))
            ->where('id'.$this->auth->id)
            ->select($fields->getSelect())->first();

        return$user; }}Copy the code

Create a Type


      
/** * User: yemeISHU * Date: 2018/4/21 * Time: 3:59 PM */

namespace App\GraphQL\Type;

use App\User;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Rebing\GraphQL\Support\Type as GraphQLType;

class MyProfileType extends GraphQLType
{
    protected $attributes = [
        'name'= >'myprofile'.'description'= >'A type'.'model' => User::class, // define model for users type
    ];

    // define field of type
    public function fields(a)
    {
        return [
            'id'= > ['type' => Type::nonNull(Type::int()),
                'description'= >'The id of the user'].'email'= > ['type' => Type::string(),
                'description'= >'The email of user'].'name'= > ['type' => Type::string(),
                'description'= >'The name of the user']]. }protected function resolveEmailField($root, $args)
    {
        returnstrtolower($root->email); }}Copy the code

Registered GraphQL config

Of course, to obtain a JWT token, you need a login method:


      

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\JWTAuth;

class AuthenticateController extends Controller {
    private $jwt;

    public function __construct(JWTAuth $jwt) {
        $this->jwt = $jwt;
    }

    public function authenticate(Request $request) {
        // grab credentials from the request
        $credentials = $request->only('email'.'password');
        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = $this->jwt->attempt($credentials)) {
                return response()->json(['error'= >'invalid_credentials'].401); }}catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response()->json(['error'= >'could_not_create_token'].500);
        }
        // all good so return the token
        return response()->json(compact('token')); }}Copy the code

Register route:

Route::post('/login'.'AuthenticateController@authenticate');
Copy the code

Get token value using email and password first:

Then use token to obtain user information:

Get an Xpath List

In an RSS system, we also want to create our own RSS Feeds for each user. So change the xpath attribution first.

php artisan make:migration add_user_id_to_xpaths_table --table=xpaths
Copy the code
public function up(a) {
    Schema::table('xpaths'.function (Blueprint $table) {
        $table->integer('user_id')->unsigned();
    });
}
Copy the code

Admin adds an xpath attributing operation

Add the select box for user_id to the XpathController form function:

$form->select('user_id')->options(function ($id) {
    $user = User::find($id);
    if ($user) {
        return [$user->id => $user->name];
    }
})->ajax('/admin/users');
Copy the code

Add admin/ Users route and Controller


      

namespace App\Admin\Controllers;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller {

    public function users(Request $request) {
        $q = $request->get('q');
        return User::where('name'.'like'."%$q%")
            ->paginate(null['id'.'name as text']); }}Copy the code

This allows you to select the attribution of this xpath based on the user name entered.

Let the xpath list show the user_id value.

First add one-to-one association:


      

namespace App;

use Illuminate\Database\Eloquent\Model;

class Xpath extends Model
{
    public function user(a) {
        return $this->belongsTo(User::class); }}Copy the code

Add user’s name to XpathController’s Grid () :

$grid->column('user.name'.'Attribution');
Copy the code

Display effect:

Get the list of xPaths using GraphQL

1. Create a Query


      
/** * User: yemeISHU * Date: 2018/4/21 * Time: 11:16 PM */

namespace App\GraphQL\Query;

use App\Xpath;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Rebing\GraphQL\Support\Query;
use Rebing\GraphQL\Support\SelectFields;
use Tymon\JWTAuth\Facades\JWTAuth;

class MyXpathsQuery extends Query {
    private $auth;

    protected $attributes = [
        'name'= >'My Xpaths Query'.'description'= >'My Xpaths Information'
    ];

    public function authorize(array $args) {
        try {
            $this->auth = JWTAuth::parseToken()->authenticate();
        } catch (\Exception $e) {
            $this->auth = null;
        }

        return (boolean) $this->auth;
    }

    public function type(a) {
        return Type::listOf(GraphQL::type('myxpath'));
    }

    public function resolve($root, $args, SelectFields $fields) {
        $xpaths = Xpath::with(array_keys($fields->getRelations()))
            ->where('user_id'.$this->auth->id)
            ->select($fields->getSelect())
            ->get();

        return$xpaths; }}Copy the code

Get the user’s ID using the JWT token, and then query the list of xPaths that belong to that user

2. Define the returned Type


      
/** * User: yemeISHU * Date: 2018/4/21 * Time: 3:59 PM */

namespace App\GraphQL\Type;

use App\User;
use App\Xpath;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Rebing\GraphQL\Support\Type as GraphQLType;

class MyXpathType extends GraphQLType
{
   protected $attributes = [
       'name'= >'myxpath'.'description'= >'A type'.'model' => Xpath::class, // define model for xpath type
   ];

   // define field of type
   public function fields(a)
   {
       return [
           'id'= > ['type' => Type::nonNull(Type::int()),
               'description'= >'The id of the user'].'url'= > ['type' => Type::string(),
               'description'= >'The url of xpath'].'urldesc'= > ['type' => Type::string(),
               'description'= >'The desc of the xpath']]. }}Copy the code

3. Register GraphQL Config

4. Test

The results are obvious:

conclusion

It’s go to a “lu an RSS generator 2 hours” mp.weixin.qq.com/s/mRjoKgkq1… , mainly intended to use JWT and GraphQL as the interface layer to provide data basis for future front-end development.

Main reference:

  • Learn Lumen user authentication (2) — use jwt-Auth plugin mp.weixin.qq.com/s/k1v-mji7Y…
  • Recommend a Laravel admin backstage management plug-in mp.weixin.qq.com/s/PnAj0j2X3…
  • Combined with preliminary study GraphQL Laravel mp.weixin.qq.com/s/Uvv4X9hXT…

The source code

github.com/fanly/lrss

“To be continued”