· 7 years ago · Jun 14, 2018, 10:04 PM
1<?php
2
3namespace App\GraphQL\Mutations\Auth;
4
5use GraphQL\Type\Definition\Type;
6use Folklore\GraphQL\Support\Mutation as GraphQLMutation;
7use GuzzleHttp\Client;
8
9class LoginMutation extends GraphQLMutation
10{
11 protected $attributes = [
12 'name' => 'login',
13 ];
14
15 public function type()
16 {
17 return Type::string();
18 }
19
20 public function rules(): array
21 {
22 return [
23 'email' => 'required|string|email',
24 'password' => 'required|string|min:6',
25 ];
26 }
27
28 public function args(): array
29 {
30 return [
31 'email' => [
32 'name' => 'email',
33 'type' => Type::nonNull(Type::string()),
34 ],
35 'password' => [
36 'name' => 'password',
37 'type' => Type::nonNull(Type::string()),
38 ],
39 'remember' => [
40 'name' => 'remember',
41 'type' => Type::string(),
42 ],
43 ];
44 }
45
46 public function resolve($root, $args)
47 {
48 try {
49 $http = new Client();
50
51 $response = $http->post(env('APP_URL') . '/oauth/token', [
52 'form_params' => [
53 'grant_type' => 'password',
54 'client_id' => env('PASSWORD_CLIENT_ID'),
55 'client_secret' => env('PASSWORD_CLIENT_SECRET'),
56 'username' => $args('email'),
57 'password' => $args('password'),
58 'remember' => $args('remember'),
59 'scope' => '',
60 ],
61 ]);
62
63 return json_decode($response->getBody(), true);
64 } catch (\Exception $e) {
65 return response()->json([
66 'error' => 'invalid_credentials',
67 'message' => "{$e->getCode()}: {$e->getMessage()}"
68 ], 401);
69 }
70 }
71}