首页 > 解决方案 > 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;
    }
}

标签: laravelgraphql

解决方案


此功能可以帮助您:

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']
    ];
}

推荐阅读