-
-
Notifications
You must be signed in to change notification settings - Fork 466
Expand file tree
/
Copy pathBaseCanDirective.php
More file actions
186 lines (158 loc) · 6.06 KB
/
BaseCanDirective.php
File metadata and controls
186 lines (158 loc) · 6.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
<?php declare(strict_types=1);
namespace Nuwave\Lighthouse\Auth;
use Illuminate\Contracts\Auth\Access\Gate;
use Nuwave\Lighthouse\Exceptions\AuthorizationException;
use Nuwave\Lighthouse\Execution\ResolveInfo;
use Nuwave\Lighthouse\Schema\Directives\BaseDirective;
use Nuwave\Lighthouse\Schema\Values\FieldValue;
use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use Nuwave\Lighthouse\Support\Utils;
abstract class BaseCanDirective extends BaseDirective implements FieldMiddleware
{
public function __construct(
protected Gate $gate,
) {}
protected static function commonArguments(): string
{
return /** @lang GraphQL */ <<<'GRAPHQL'
"""
The ability to check permissions for.
"""
ability: String!
"""
Pass along the client given input data as arguments to `Gate::check`.
"""
injectArgs: Boolean! = false
"""
Statically defined arguments that are passed to `Gate::check`.
You may pass arbitrary GraphQL literals,
e.g.: [1, 2, 3] or { foo: "bar" }
"""
args: CanArgs
"""
Action to do if the user is not authorized.
"""
action: CanAction! = EXCEPTION_PASS
"""
Value to return if the user is not authorized and `action` is `RETURN_VALUE`.
"""
returnValue: CanReturnValue
GRAPHQL;
}
protected static function commonTypes(): string
{
return /** @lang GraphQL */ <<<'GRAPHQL'
"""
Any constant literal value.
See https://graphql.github.io/graphql-spec/draft/#sec-Input-Values.
"""
scalar CanArgs
"""
Any constant literal value.
See https://graphql.github.io/graphql-spec/draft/#sec-Input-Values.
"""
scalar CanReturnValue
enum CanAction {
"""
Pass exception to the client.
"""
EXCEPTION_PASS
"""
Throw generic "not authorized" exception to conceal the real error.
"""
EXCEPTION_NOT_AUTHORIZED
"""
Return the value specified in the `returnValue` directive argument to conceal the real error.
"""
RETURN_VALUE
}
GRAPHQL;
}
/** Ensure the user is authorized to access this field. */
public function handleField(FieldValue $fieldValue): void
{
$ability = $this->directiveArgValue('ability');
$fieldValue->wrapResolver(fn (callable $resolver): \Closure => function (mixed $root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($resolver, $ability) {
$gate = $this->gate->forUser($context->user());
$checkArguments = $this->buildCheckArguments($args);
$authorizeModel = fn (mixed $model) => $this->authorizeModel($gate, $ability, $model, $checkArguments);
$hasResolved = false;
$trackedResolver = static function () use (&$hasResolved, $resolver) {
$hasResolved = true;
return $resolver(...func_get_args());
};
try {
$resolved = $this->authorizeRequest($root, $args, $context, $resolveInfo, $trackedResolver, $authorizeModel);
if ($hasResolved) {
return $resolved;
}
} catch (\Throwable $throwable) {
$action = $this->directiveArgValue('action');
if ($action === 'EXCEPTION_NOT_AUTHORIZED') {
throw new AuthorizationException(AuthorizationException::MESSAGE, $throwable->getCode(), $throwable);
}
if ($action === 'RETURN_VALUE') {
return $this->directiveArgValue('returnValue');
}
throw $throwable;
}
// Try to resolve the field outside the authorization try-catch block to avoid catching resolver exceptions.
return $resolver($root, $args, $context, $resolveInfo);
});
}
/**
* Authorizes request and optionally resolves the field.
*
* This method is called inside the authorization try-catch block.
* Resolving the field here is optional.
* It will be done outside the try-catch block if this method does not resolve it.
* Resolving inside this method means any exceptions thrown by the resolver are caught.
* Those exceptions are handled according to the `action` argument.
*
* @phpstan-import-type Resolver from \Nuwave\Lighthouse\Schema\Values\FieldValue as Resolver
*
* @param array<string, mixed> $args
* @param callable(mixed, array<string, mixed>, \Nuwave\Lighthouse\Support\Contracts\GraphQLContext, \Nuwave\Lighthouse\Execution\ResolveInfo): mixed $resolver
* @param callable(mixed): void $authorize
*/
abstract protected function authorizeRequest(mixed $root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo, callable $resolver, callable $authorize): mixed;
/**
* @param string|array<string> $ability
* @param array<int, mixed> $arguments
*/
protected function authorizeModel(Gate $gate, string|array $ability, mixed $model, array $arguments): void
{
// The signature of the second argument `$arguments` of `Gate::check`
// should be [modelClassName, additionalArg, additionalArg...]
array_unshift($arguments, $model);
Utils::applyEach(
static function ($ability) use ($gate, $arguments): void {
$response = $gate->inspect($ability, $arguments);
if ($response->denied()) {
throw new AuthorizationException($response->message(), $response->code());
}
},
$ability,
);
}
/**
* Additional arguments that are passed to @see Gate::check().
*
* @param array<string, mixed> $args
*
* @return array<int, mixed>
*/
protected function buildCheckArguments(array $args): array
{
$checkArguments = [];
// The injected args come before the static args
if ($this->directiveArgValue('injectArgs')) {
$checkArguments[] = $args;
}
if ($this->directiveHasArgument('args')) {
$checkArguments[] = $this->directiveArgValue('args');
}
return $checkArguments;
}
}