laravel - Laravel:使用 Passport 和 Graphql 时如何登录?
问题描述
我在 laravel 中使用 Graphql( laravel-graphql ),我正在编写登录组件,我想使用 laravel 的 Passport,下面的代码使用 JWTAuth
.
问题:使用 Passport 时
如何编写方法?resolve()
LoginMutation.php
namespace App\GraphQL\Mutation;
use Folklore\GraphQL\Error\AuthorizationError;
use Folklore\GraphQL\Support\Mutation;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use GraphQL;
use JWTAuth;
use Auth;
class LoginMutation extends Mutation
{
protected $attributes = [
'name' => 'Login',
'description' => 'A mutation for user login'
];
public function type()
{
return GraphQL::type('User');
}
public function args()
{
return [
'email' => ['name' => 'email', 'type' => Type::nonNull(Type::string())],
'password' => ['name' => 'password', 'type' => Type::nonNull(Type::string())],
];
}
public function rules()
{
return [
'email' => ['required', 'email'],
'password' => ['required']
];
}
public function resolve($root, $args, $context, ResolveInfo $info)
{
$credentials = [
'email' => $args['email'],
'password' => $args['password']
];
if (!$token = JWTAuth::attempt($credentials)) {
throw new AuthorizationError('Invalid Credentials.');
}
$user = Auth::user();
$user->token = $token;
return $user;
}
}
解决方案
此功能可以帮助您:
public function resolve($root, $args, $context, ResolveInfo $info){
$user = User::where('email', $args['email'])->first();
if(!$user || !Hash::check($args['password'], $user->password)){
throw new AuthorizationError('Invalid Credentials.');
}
$http = new Client;
$response = $http->post(url('oauth/token'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => '2',
'client_secret' => 'your-client-secret-key',
'username' => $args['email'],
'password' => $args['password'],
'scope' => ''
]
]);
return $user;
}
也不要忘记添加use GuzzleHttp\Client;
到 LoginUserMutation 文件的顶部。
此外,在定义规则功能时,您可以通过以下方式扩展电子邮件规则:
public function rules()
{
return [
'email' => ['required', 'email', 'exists:users'],
'password' => ['required']
];
}
推荐阅读
- python - ReportLab 文本重叠
- python - 处理 YAML 重复键条目的灵活性
- pytorch - .grad() 在 pytorch 中返回 None
- java - 带lambda的热插拔代码失败,说明方法无法删除
- python - Selenium Firefox headless 返回不同的结果
- spring-boot - 超出 Prometheus 错误上下文期限
- python - 重新加载 QML 画布图像
- python-3.x - 我想在 Python 中进行与在 Scala 中相同的转换
- angular - Observable 是空的 Rxjs
- sqlite - 离线优先方法和 PWA 的区别?