1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Bridges\SecurityDI;
9:
10: use Nette;
11:
12:
13: 14: 15:
16: class SecurityExtension extends Nette\DI\CompilerExtension
17: {
18: public $defaults = [
19: 'debugger' => true,
20: 'users' => [],
21: 'roles' => [],
22: 'resources' => [],
23: ];
24:
25:
26: private $debugMode;
27:
28:
29: public function __construct($debugMode = false)
30: {
31: $this->debugMode = $debugMode;
32: }
33:
34:
35: public function loadConfiguration()
36: {
37: $config = $this->validateConfig($this->defaults);
38: $builder = $this->getContainerBuilder();
39:
40: $builder->addDefinition($this->prefix('userStorage'))
41: ->setClass(Nette\Security\IUserStorage::class)
42: ->setFactory(Nette\Http\UserStorage::class);
43:
44: $user = $builder->addDefinition($this->prefix('user'))
45: ->setFactory(Nette\Security\User::class);
46:
47: if ($this->debugMode && $config['debugger']) {
48: $user->addSetup('@Tracy\Bar::addPanel', [
49: new Nette\DI\Statement(Nette\Bridges\SecurityTracy\UserPanel::class),
50: ]);
51: }
52:
53: if ($config['users']) {
54: $usersList = $usersRoles = [];
55: foreach ($config['users'] as $username => $data) {
56: $data = is_array($data) ? $data : ['password' => $data];
57: $this->validateConfig(['password' => null, 'roles' => null], $data, $this->prefix("security.users.$username"));
58: $usersList[$username] = $data['password'];
59: $usersRoles[$username] = isset($data['roles']) ? $data['roles'] : null;
60: }
61:
62: $builder->addDefinition($this->prefix('authenticator'))
63: ->setClass(Nette\Security\IAuthenticator::class)
64: ->setFactory(Nette\Security\SimpleAuthenticator::class, [$usersList, $usersRoles]);
65:
66: if ($this->name === 'security') {
67: $builder->addAlias('nette.authenticator', $this->prefix('authenticator'));
68: }
69: }
70:
71: if ($config['roles'] || $config['resources']) {
72: $authorizator = $builder->addDefinition($this->prefix('authorizator'))
73: ->setClass(Nette\Security\IAuthorizator::class)
74: ->setFactory(Nette\Security\Permission::class);
75:
76: foreach ($config['roles'] as $role => $parents) {
77: $authorizator->addSetup('addRole', [$role, $parents]);
78: }
79: foreach ($config['resources'] as $resource => $parents) {
80: $authorizator->addSetup('addResource', [$resource, $parents]);
81: }
82:
83: if ($this->name === 'security') {
84: $builder->addAlias('nette.authorizator', $this->prefix('authorizator'));
85: }
86: }
87:
88: if ($this->name === 'security') {
89: $builder->addAlias('user', $this->prefix('user'));
90: $builder->addAlias('nette.userStorage', $this->prefix('userStorage'));
91: }
92: }
93: }
94: