DbManager.php
13.6 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
<?php
namespace app\ht\exts\rbac;
use Yii;
use yii\caching\Cache;
use yii\db\Connection;
use yii\db\Query;
use yii\di\Instance;
use yii\base\Component;
/**
* DbManager represents an authorization manager that stores authorization information in database.
* @author Nemo Luo <378107001@qq,com>
* @since 2.0
*/
class DbManager extends Component implements ManagerInterface
{
/**
* @var Connection|array|string the DB connection object or the application component ID of the DB connection.
* After the DbManager object is created, if you want to change this property, you should only assign it
* with a DB connection object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $db = 'db';
/**
* @var string the name of the table storing authorization roles. Defaults to "auth_role".
*/
public $roleTable = '{{%auth_role}}';
/**
* @var string the name of the table storing authorization role assignments. Defaults to "auth_assignment".
*/
public $assignmentTable = '{{%auth_users_roles}}';
/**
* @var string the name of the table storing authorization roles. Defaults to "auth_role".
*/
public $permTable = '{{%auth_perm}}';
/**
* @var Cache|array|string the cache used to improve RBAC performance. This can be one of the following:
*
* - an application component ID (e.g. `cache`)
* - a configuration array
* - a [[\yii\caching\Cache]] object
*
* When this is not set, it means caching is not enabled.
*
* Note that by enabling RBAC cache, all auth roles, rules and auth role parent-child relationships will
* be cached and loaded into memory. This will improve the performance of RBAC perm check. However,
* it does require extra memory and as a result may not be appropriate if your RBAC system contains too many
* auth roles. You should seek other RBAC implementations (e.g. RBAC based on Redis storage) in this case.
*
* Also note that if you modify RBAC roles, rules or parent-child relationships from outside of this component,
* you have to manually call [[invalidateCache()]] to ensure data consistency.
*
* @since 2.0.3
*/
public $cache;
/**
* @var string the key used to store RBAC data in cache
* @see cache
* @since 2.0.3
*/
public $cacheKey = 'rbac';
/**
* @var Roles[] all auth roles (role_id => Role)
*/
protected $roles;
/**
* @var Perm[] all auth rules (perm_id => Perm)
*/
protected $perms;
const SUPPER_ADMIN_NAME = '超级管理员';
/**
* Initializes the application component.
* This method overrides the parent implementation by establishing the database connection.
*/
public function init()
{
parent::init();
$this->db = Instance::ensure($this->db, Connection::className());
if ($this->cache !== null) {
$this->cache = Instance::ensure($this->cache, Cache::className());
}
}
/**
* @inheritdoc
*/
public function checkAccess($userId, $permId, $params = [])
{
$perms = $this->getPermsByUser($userId);
$this->loadFromCache();
return $this->checkAccessFromCache($permId, $perms, $params);
}
/**
* Performs access check for the specified user based on the data loaded from cache.
*/
protected function checkAccessFromCache($permId, $perms, $params = [])
{
if (!isset($this->perms[$permId])) {
return false;
}
$perm = $this->perms[$permId];
Yii::trace("Checking permission: $perm->name", __METHOD__);
foreach ($perms as $p) {
if ($p->permId == $permId) {
return true;
}
}
return false;
}
public function invalidateCache()
{
if ($this->cache !== null) {
$this->cache->delete($this->cacheKey);
$this->roles = null;
$this->perms = null;
}
}
/**
* @inheritdoc
*/
public function createRole($name)
{
$role = new Role;
$role->name = $name;
return $role;
}
/**
* @inheritdoc
*/
public function addRole($role)
{
$row = (new Query)->from($this->roleTable)
->where(['name' => $role->name])
->one($this->db);
if ($row) {
return false;
}
$this->db->createCommand()
->insert($this->roleTable, [
'name' => $role->name,
'description' => $role->description,
])->execute();
$this->invalidateCache();
return true;
}
/**
* @inheritdoc
*/
public function removeRole($role)
{
$this->db->createCommand()
->delete($this->assignmentTable, ['role_id' => $role->roleId])
->execute();
$this->db->createCommand()
->delete($this->roleTable, ['role_id' => $role->roleId])
->execute();
$this->invalidateCache();
return true;
}
/**
* @inheritdoc
*/
public function updateRole($roleId, $role)
{
$this->db->createCommand()
->update($this->roleTable, [
'name' => $role->name,
'description' => $role->description,
], [
'role_id' => $roleId,
])->execute();
$this->invalidateCache();
return true;
}
/**
* @inheritdoc
*/
public function setRolePerms($roleId, $perms = '')
{
$this->db->createCommand()
->update($this->roleTable, [
'perms' => $perms,
], [
'role_id' => $roleId,
])->execute();
$this->invalidateCache();
return true;
}
/**
* @inheritdoc
*/
public function getRole($roleId)
{
if (empty($roleId)) {
return null;
}
if (!empty($this->roles[$roleId])) {
return $this->roles[$roleId];
}
$row = (new Query)->from($this->roleTable)
->where(['role_id' => $roleId])
->one($this->db);
if ($row === false) {
return null;
}
return $this->populateRole($row);
}
/**
* @inheritdoc
*/
public function getRoles()
{
$query = (new Query)
->from($this->roleTable);
$roles = [];
foreach ($query->all($this->db) as $row) {
$roles[$row['role_id']] = $this->populateRole($row);
}
return $roles;
}
/**
* @inheritdoc
*/
public function getRolesByUser($userId)
{
if (empty($userId)) {
return [];
}
$query = (new Query)->select('b.*')
->from(['a' => $this->assignmentTable, 'b' => $this->roleTable])
->where('{{a}}.[[role_id]]={{b}}.[[role_id]]')
->andWhere(['a.sys_user_id' => (int) $userId]);
$roles = [];
foreach ($query->all($this->db) as $row) {
$roles[$row['role_id']] = $this->populateRole($row);
}
return $roles;
}
/**
* Populates an auth role with the data fetched from database
* @param array $row the data from the auth role table
* @return Role the populated auth role instance (either Role)
*/
protected function populateRole($row)
{
$class = Role::className();
return new $class([
'roleId' => $row['role_id'],
'name' => $row['name'],
'perms' => $row['perms'],
'description' => $row['description'],
]);
}
/**
* @inheritdoc
*/
public function getPerm($permId)
{
if (empty($permId)) {
return null;
}
if (!empty($this->perms[$permId])) {
return $this->perms[$permId];
}
$row = (new Query)->from($this->permTable)
->where(['perm_id' => $permId])
->one($this->db);
if ($row === false) {
return null;
}
return $this->populatePerm($row);
}
/**
* @inheritdoc
*/
public function getPerms()
{
$query = (new Query)
->from($this->permTable);
$perms = [];
foreach ($query->all($this->db) as $row) {
$perms[$row['perm_id']] = $this->populatePerm($row);
}
return $perms;
}
/**
* @inheritdoc
*/
public function getPermsByRole($roleId)
{
$perms = [];
$role = $this->getRole($roleId);
if ($role->perms && $permIds = explode(',', $role->perms)) {
foreach ($permIds as $permId) {
if ($this->getPerm($permId)) {
$perms[$permId] = $this->getPerm($permId);
}
}
}
return $perms;
}
/**
* @inheritdoc
*/
public function getPermsByUser($userId)
{
$perms = [];
$assignments = $this->getAssignments($userId);
foreach ($assignments as $roleId => $role) {
$perms = array_merge($perms, $this->getPermsByRole($roleId));
}
return $perms;
}
/**
* Populates an auth perm with the data fetched from database
* @param array $row the data from the auth role table
* @return Role the populated auth role instance (either Role)
*/
protected function populatePerm($row)
{
$class = Perm::className();
return new $class([
'permId' => $row['perm_id'],
'name' => $row['name'],
]);
}
/**
* @inheritdoc
*/
public function assign($role, $userId)
{
$assignment = new Assignment([
'userId' => $userId,
'roleId' => $role->roleId,
]);
$this->db->createCommand()
->insert($this->assignmentTable, [
'sys_user_id' => $assignment->userId,
'role_id' => $assignment->roleId,
])->execute();
return $assignment;
}
/**
* @inheritdoc
*/
public function getAssignment($roleId, $userId)
{
if (empty($userId)) {
return null;
}
$row = (new Query)->from($this->assignmentTable)
->where(['user_id' => (int) $userId, 'roleId' => $roleId])
->one($this->db);
if ($row === false) {
return null;
}
return new Assignment([
'userId' => $row['user_id'],
'roleId' => $row['role_id'],
]);
}
/**
* @inheritdoc
*/
public function getAssignments($userId)
{
if (empty($userId)) {
return [];
}
$query = (new Query)
->from($this->assignmentTable)
->where(['sys_user_id' => (int) $userId]);
$assignments = [];
foreach ($query->all($this->db) as $row) {
$assignments[$row['role_id']] = new Assignment([
'userId' => $row['sys_user_id'],
'roleId' => $row['role_id'],
]);
}
return $assignments;
}
/**
* @inheritdoc
*/
public function revoke($role, $userId)
{
if (empty($userId)) {
return false;
}
return $this->db->createCommand()
->delete($this->assignmentTable, ['sys_user_id' => (int) $userId, 'role_id' => $role->role_id])
->execute() > 0;
}
/**
* @inheritdoc
*/
public function revokeAll($userId)
{
return $this->db->createCommand()
->delete($this->assignmentTable, ['sys_user_id' => (int) $userId])
->execute() > 0;
}
/**
* @inheritdoc
*/
public function removeAllPerms()
{
}
/**
* @inheritdoc
*/
public function removeAllRoles()
{
}
public function loadFromCache()
{
if ($this->roles !== null || !$this->cache instanceof Cache) {
return;
}
$data = $this->cache->get($this->cacheKey);
if (is_array($data) && isset($data[0], $data[1])) {
list ($this->roles, $this->perms) = $data;
return;
}
$query = (new Query)->from($this->roleTable);
$this->roles = [];
foreach ($query->all($this->db) as $row) {
$this->roles[$row['role_id']] = $this->populateRole($row);
}
$query = (new Query)->from($this->permTable);
$this->perms = [];
foreach ($query->all($this->db) as $row) {
$this->perms[$row['perm_id']] = $this->populatePerm($row);;
}
$this->cache->set($this->cacheKey, [$this->roles, $this->perms]);
}
/**
* Returns all role assignment information for the specified role.
* @param string $roleId
* @return Assignment[] the assignments. An empty array will be
* returned if role is not assigned to any user.
* @since 2.0.7
*/
public function getUserIdsByRole($roleId)
{
if (empty($roleId)) {
return [];
}
return (new Query)->select('[[sys_user_id]]')
->from($this->assignmentTable)
->where(['role_id' => $roleId])->column($this->db);
}
/**
* @param $roleName
* @return Role|null
*/
public function getRoleByName($roleName)
{
if (empty($roleName)) {
return null;
}
$row = (new Query)->from($this->roleTable)
->where(['name' => $roleName])
->one($this->db);
if ($row === false) {
return null;
}
return $this->populateRole($row);
}
}