-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathEntrustUserTrait.php
More file actions
321 lines (286 loc) · 9.28 KB
/
EntrustUserTrait.php
File metadata and controls
321 lines (286 loc) · 9.28 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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
<?php namespace Zizaco\Entrust\Traits;
/**
* This file is part of Entrust,
* a role & permission management solution for Laravel.
*
* @license MIT
* @package Zizaco\Entrust
*/
use Illuminate\Cache\TaggableStore;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use InvalidArgumentException;
trait EntrustUserTrait
{
/**
* Big block of caching functionality.
*
* @return mixed Roles
*/
public function cachedRoles()
{
$userPrimaryKey = $this->primaryKey;
$cacheKey = 'entrust_roles_for_user_'.$this->$userPrimaryKey;
if(Cache::getStore() instanceof TaggableStore) {
return Cache::tags(Config::get('entrust.role_user_table'))->remember($cacheKey, Config::get('cache.ttl'), function () {
return $this->roles()->get();
});
}
else return $this->roles()->get();
}
/**
* {@inheritDoc}
*/
public function save(array $options = [])
{ //both inserts and updates
if(Cache::getStore() instanceof TaggableStore) {
Cache::tags(Config::get('entrust.role_user_table'))->flush();
}
return parent::save($options);
}
/**
* {@inheritDoc}
*/
public function delete(array $options = [])
{ //soft or hard
$result = parent::delete($options);
if(Cache::getStore() instanceof TaggableStore) {
Cache::tags(Config::get('entrust.role_user_table'))->flush();
}
return $result;
}
/**
* {@inheritDoc}
*/
public function restore()
{ //soft delete undo's
$result = parent::restore();
if(Cache::getStore() instanceof TaggableStore) {
Cache::tags(Config::get('entrust.role_user_table'))->flush();
}
return $result;
}
/**
* Many-to-Many relations with Role.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function roles()
{
return $this->belongsToMany(Config::get('entrust.role'), Config::get('entrust.role_user_table'), Config::get('entrust.user_foreign_key'), Config::get('entrust.role_foreign_key'));
}
/**
* Boot the user model
* Attach event listener to remove the many-to-many records when trying to delete
* Will NOT delete any records if the user model uses soft deletes.
*
* @return void|bool
*/
public static function boot()
{
parent::boot();
static::deleting(function($user) {
if (!method_exists(Config::get('auth.providers.users.model'), 'bootSoftDeletes')) {
$user->roles()->sync([]);
}
return true;
});
}
/**
* Checks if the user has a role by its name.
*
* @param string|array $name Role name or array of role names.
* @param bool $requireAll All roles in the array are required.
*
* @return bool
*/
public function hasRole($name, $requireAll = false)
{
if (is_array($name)) {
foreach ($name as $roleName) {
$hasRole = $this->hasRole($roleName);
if ($hasRole && !$requireAll) {
return true;
} elseif (!$hasRole && $requireAll) {
return false;
}
}
// If we've made it this far and $requireAll is FALSE, then NONE of the roles were found
// If we've made it this far and $requireAll is TRUE, then ALL of the roles were found.
// Return the value of $requireAll;
return $requireAll;
} else {
foreach ($this->cachedRoles() as $role) {
if ($role->name == $name) {
return true;
}
}
}
return false;
}
/**
* Check if user has a permission by its name.
*
* @param string|array $permission Permission string or array of permissions.
* @param bool $requireAll All permissions in the array are required.
*
* @return bool
*/
public function can($permission, $requireAll = false)
{
if (is_array($permission)) {
foreach ($permission as $permName) {
$hasPerm = $this->can($permName);
if ($hasPerm && !$requireAll) {
return true;
} elseif (!$hasPerm && $requireAll) {
return false;
}
}
// If we've made it this far and $requireAll is FALSE, then NONE of the perms were found
// If we've made it this far and $requireAll is TRUE, then ALL of the perms were found.
// Return the value of $requireAll;
return $requireAll;
} else {
foreach ($this->cachedRoles() as $role) {
// Validate against the Permission table
foreach ($role->cachedPermissions() as $perm) {
if (str_is( $permission, $perm->name) ) {
return true;
}
}
}
}
return false;
}
/**
* Checks role(s) and permission(s).
*
* @param string|array $roles Array of roles or comma separated string
* @param string|array $permissions Array of permissions or comma separated string.
* @param array $options validate_all (true|false) or return_type (boolean|array|both)
*
* @throws \InvalidArgumentException
*
* @return array|bool
*/
public function ability($roles, $permissions, $options = [])
{
// Convert string to array if that's what is passed in.
if (!is_array($roles)) {
$roles = explode(',', $roles);
}
if (!is_array($permissions)) {
$permissions = explode(',', $permissions);
}
// Set up default values and validate options.
if (!isset($options['validate_all'])) {
$options['validate_all'] = false;
} else {
if ($options['validate_all'] !== true && $options['validate_all'] !== false) {
throw new InvalidArgumentException();
}
}
if (!isset($options['return_type'])) {
$options['return_type'] = 'boolean';
} else {
if ($options['return_type'] != 'boolean' &&
$options['return_type'] != 'array' &&
$options['return_type'] != 'both') {
throw new InvalidArgumentException();
}
}
// Loop through roles and permissions and check each.
$checkedRoles = [];
$checkedPermissions = [];
foreach ($roles as $role) {
$checkedRoles[$role] = $this->hasRole($role);
}
foreach ($permissions as $permission) {
$checkedPermissions[$permission] = $this->can($permission);
}
// If validate all and there is a false in either
// Check that if validate all, then there should not be any false.
// Check that if not validate all, there must be at least one true.
if(($options['validate_all'] && !(in_array(false,$checkedRoles) || in_array(false,$checkedPermissions))) ||
(!$options['validate_all'] && (in_array(true,$checkedRoles) || in_array(true,$checkedPermissions)))) {
$validateAll = true;
} else {
$validateAll = false;
}
// Return based on option
if ($options['return_type'] == 'boolean') {
return $validateAll;
} elseif ($options['return_type'] == 'array') {
return ['roles' => $checkedRoles, 'permissions' => $checkedPermissions];
} else {
return [$validateAll, ['roles' => $checkedRoles, 'permissions' => $checkedPermissions]];
}
}
/**
* Alias to eloquent many-to-many relation's attach() method.
*
* @param mixed $role
*/
public function attachRole($role)
{
if(is_object($role)) {
$role = $role->getKey();
}
if(is_array($role)) {
$role = $role['id'];
}
$this->roles()->sync($role, false);
}
/**
* Alias to eloquent many-to-many relation's detach() method.
*
* @param mixed $role
*/
public function detachRole($role)
{
if (is_object($role)) {
$role = $role->getKey();
}
if (is_array($role)) {
$role = $role['id'];
}
$this->roles()->detach($role);
}
/**
* Attach multiple roles to a user
*
* @param mixed $roles
*/
public function attachRoles($roles)
{
foreach ($roles as $role) {
$this->attachRole($role);
}
}
/**
* Detach multiple roles from a user
*
* @param mixed $roles
*/
public function detachRoles($roles=null)
{
if (!$roles) $roles = $this->roles()->get();
foreach ($roles as $role) {
$this->detachRole($role);
}
}
/**
*Filtering users according to their role
*
*@param string $role
*@return users collection
*/
public function scopeWithRole($query, $role)
{
return $query->whereHas('roles', function ($query) use ($role)
{
$query->where('name', $role);
});
}
}