GraphQL 配合 JWT 使用 —— Laravel RSS (二)
我们了解了 jwt
和 GraphQL
的使用,那接下来看看他们如何结合使用。
小试牛刀
创建 myProfile query
<?php
/*** User: yemeishu* Date: 2018/4/21* Time: 上午8:55*/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() {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;}}
复制代码
创建 Type
<?php
/*** User: yemeishu* Date: 2018/4/21* Time: 下午3:59*/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 typepublic function fields(){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){return strtolower($root->email);}
}
复制代码
注册 GraphQL config
当然要获取 jwt token
,需要有一个 login
方法:
<?phpnamespace 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 userif (! $token = $this->jwt->attempt($credentials)) {return response()->json(['error' => 'invalid_credentials'], 401);}} catch (JWTException $e) {// something went wrong whilst attempting to encode the tokenreturn response()->json(['error' => 'could_not_create_token'], 500);}// all good so return the tokenreturn response()->json(compact('token'));}
}
复制代码
注册路由:
Route::post('/login', 'AuthenticateController@authenticate');
复制代码
先利用 email 和 password 获得 token 值:
然后利用 token 获取用户信息:
获取 Xpath List
在 RSS 系统中,我们也希望给每个用户创建自己的 RSS Feeds。所以先修改 xpath 的归属。
php artisan make:migration add_user_id_to_xpaths_table --table=xpaths
复制代码
public function up() {Schema::table('xpaths', function (Blueprint $table) {$table->integer('user_id')->unsigned();});
}
复制代码
admin 添加 xpath 归属操作
在 XpathController
的 form
函数增加 user_id
的选择框:
$form->select('user_id')->options(function ($id) {$user = User::find($id);if ($user) {return [$user->id => $user->name];}
})->ajax('/admin/users');
复制代码
添加 admin/users
route 和 controller
<?phpnamespace 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']);}
}
复制代码
这样就可以根据输入的 user name
来选择这个 xpath 的归属。
让 xpath
列表显示 user_id
值.
首先增加 一对一
关联:
<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Xpath extends Model
{public function user() {return $this->belongsTo(User::class);}
}
复制代码
再在 XpathController
的 grid()
直接增加 user's name
:
$grid->column('user.name', '归属人');
复制代码
显示效果:
利用 GraphQL 获取 Xpath 列表
1. 创建 Query
<?php
/*** User: yemeishu* Date: 2018/4/21* Time: 下午11:16*/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() {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;}
}
复制代码
利用 jwt token
获取 user's id
,然后再查询属于该用户的 xpath 列表
2. 定义返回的 Type
<?php
/**
* User: yemeishu
* Date: 2018/4/21
* Time: 下午3:59
*/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 typepublic function fields(){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']];}
}
复制代码
3. 注册 GraphQL config
4. 测试
结果自然显而易见:
总结
这是继续上一篇《花 2 小时撸一个 RSS 生成器》mp.weixin.qq.com/s/mRjoKgkq1…,主要是想利用 jwt
和 GraphQL
作为接口层,为之后的前端开发,提供数据基础。
主要参考:
- 学习 Lumen 用户认证 (二) —— 使用 jwt-auth 插件 mp.weixin.qq.com/s/k1v-mji7Y…
- 推荐一个 Laravel admin 后台管理插件 mp.weixin.qq.com/s/PnAj0j2X3…
- 结合 Laravel 初步学习 GraphQL mp.weixin.qq.com/s/Uvv4X9hXT…
源代码
github.com/fanly/lrss
「未完待续」
GraphQL 配合 JWT 使用 —— Laravel RSS (二)相关推荐
- Laravel 生成二维码的方法
(本实例laravel 版本 >=5.6, PHP版本 >=7.0)1.首先,添加 QrCode 包添加到你的 composer.json 文件的 require 里:"requ ...
- Class 'QrCode' not found ? 和 laravel 生成二维码接口(Simple QrCod)
一.控制器上面要加 use QrCode; calss里面是如下下法: $data = QrCode::size(100)->color(255,0,255)->backgroundCol ...
- PHP laravel 生成二维码
php laravel框架生成二维码_51CTO博客_php laravel框架 参考 一.配置 1.在项目根目录输入命令 composer require simplesoftwareio/sim ...
- Laravel基础二之Migrations和验证
一.Migration创建数据表与Seeder数据库填充数据 数据库迁移就像是数据库的版本控制,可以让你的团队轻松修改并共享应用程序的数据库结构 1.1 创建迁移 php artisan make:m ...
- laravel(二):laravel基本入门 看到Hello Laravel
1.Hello World 首先,我们来添加一些文字,在页面中显示.为了能访问网页,要启动程序服务器. $ php artisan serve 上述命令会启动 PHP 内建的开发服务器,要查看程序,请 ...
- Laravel OAuth2 (二) ---配置与数据库设计
前言 使用 OAuth2 进行第三方登陆分为好几种情况,例如完全第三方登陆,不保存任何用户信息,或者第三方登陆后保存用户信息关联本站账号.个人觉得保存一下用户信息比较妥当(虽然这样注册的时候让用户觉得 ...
- php dingo和jwt,dingo配合laravel、JWT使用
介绍:dingo api包是给laravel和lumen提供的Restful的工具包,它可以与jwt组件一起配合快速的完成用户认证,同时对于数据和运行过程中所产生的异常能够捕获到并且可以做出对应的响应 ...
- 带有GraphQL数据访问和JWT身份验证的.NET 5服务
目录 介绍 服务如何运作? GraphQL的用法和优化 组成和结构 如何运行? 前提条件(对于Windows) 行动顺序 使用Playground的查询和变异 测验 结论 本文和代码说明了.NET 5 ...
- Laravel实现google-authenticator--Google二维码验证器
开发前的准备 安装Laravel 安装二维码生成器QrCode,没有安装也可以,接下来会安装 安装拓展 1.运行如下代码安装拓展包: composer require "earnp/lara ...
最新文章
- ActiveMQ –经纪人网络解释–第4部分
- 百度seo排名规则_百度关键词seo优化排名如何上首页
- SSIA的完整形式是什么?
- c语言终极面试宝典 pdf,C语言终极面试--编程
- 浅谈 iOS设计之多视图—模态视图的基本操作
- NGN学习笔记5——IMS技术
- python作函数图像_如何使用python的matplotlib模块画余切函数图像
- 排序算法——鸽巢排序 Pigeonhole sort
- 爬虫python淘宝_python爬虫爬取淘宝失败原因分析
- Excel批量插入多个空行-VBA实现
- 瞎谈干净架构(clean architecture)
- idea自定义背景图片
- Vue项目开发中使用路由懒加载
- 迭代器Iterator列表迭代器ListIterator
- 感恩美文:生命中总有一些人值得感恩
- autorun.inf desktop.ini folder.htt专杀
- 模拟黑洞图像_实时模拟黑洞视觉效果 | 开源
- 【C语言】关键字const详解 - 变量守护者
- 知识星球:ChatGPTAI 变现圈,正式上线!
- Win10总是开机黑屏?显卡驱动安装失败-驱动人生解决方案