/
AuthorizesRequests.php
96 lines (85 loc) · 2.94 KB
/
AuthorizesRequests.php
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
<?php
namespace Illuminate\Foundation\Auth\Access;
use Illuminate\Contracts\Auth\Access\Gate;
use Illuminate\Auth\Access\UnauthorizedException;
use Symfony\Component\HttpKernel\Exception\HttpException;
trait AuthorizesRequests
{
/**
* Authorize a given action against a set of arguments.
*
* @param mixed $ability
* @param mixed|array $arguments
* @return \Illuminate\Auth\Access\Response
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function authorize($ability, $arguments = [])
{
list($ability, $arguments) = $this->parseAbilityAndArguments($ability, $arguments);
return $this->authorizeAtGate(app(Gate::class), $ability, $arguments);
}
/**
* Authorize a given action for a user.
*
* @param \Illuminate\Contracts\Auth\Authenticatable|mixed $user
* @param mixed $ability
* @param mixed|array $arguments
* @return \Illuminate\Auth\Access\Response
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function authorizeForUser($user, $ability, $arguments = [])
{
list($ability, $arguments) = $this->parseAbilityAndArguments($ability, $arguments);
$gate = app(Gate::class)->forUser($user);
return $this->authorizeAtGate($gate, $ability, $arguments);
}
/**
* Authorize the request at the given gate.
*
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
* @param mixed $ability
* @param mixed|array $arguments
* @return \Illuminate\Auth\Access\Response
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function authorizeAtGate(Gate $gate, $ability, $arguments)
{
try {
return $gate->authorize($ability, $arguments);
} catch (UnauthorizedException $e) {
throw $this->createGateUnauthorizedException(
$ability, $arguments, $e->getMessage(), $e
);
}
}
/**
* Guesses the ability's name if it wasn't provided.
*
* @param mixed $ability
* @param mixed|array $arguments
* @return array
*/
protected function parseAbilityAndArguments($ability, $arguments)
{
if (is_string($ability)) {
return [$ability, $arguments];
}
return [debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function'], $ability];
}
/**
* Throw an unauthorized exception based on gate results.
*
* @param string $ability
* @param mixed|array $arguments
* @param string $message
* @param \Exception $previousException
* @return \Symfony\Component\HttpKernel\Exception\HttpException
*/
protected function createGateUnauthorizedException($ability, $arguments, $message = 'This action is unauthorized.', $previousException = null)
{
return new HttpException(403, $message, $previousException);
}
}