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 = array(
19: 'debugger' => TRUE,
20: 'users' => array(),
21: 'roles' => array(),
22: 'resources' => array(),
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: $container = $this->getContainerBuilder();
39:
40: $container->addDefinition($this->prefix('userStorage'))
41: ->setClass('Nette\Security\IUserStorage')
42: ->setFactory('Nette\Http\UserStorage');
43:
44: $user = $container->addDefinition($this->prefix('user'))
45: ->setClass('Nette\Security\User');
46:
47: if ($this->debugMode && $config['debugger']) {
48: $user->addSetup('@Tracy\Bar::addPanel', array(
49: new Nette\DI\Statement('Nette\Bridges\SecurityTracy\UserPanel'),
50: ));
51: }
52:
53: if ($config['users']) {
54: $usersList = $usersRoles = array();
55: foreach ($config['users'] as $username => $data) {
56: $data = is_array($data) ? $data : array('password' => $data);
57: $this->validateConfig(array('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: $container->addDefinition($this->prefix('authenticator'))
63: ->setClass('Nette\Security\IAuthenticator')
64: ->setFactory('Nette\Security\SimpleAuthenticator', array($usersList, $usersRoles));
65:
66: if ($this->name === 'security') {
67: $container->addAlias('nette.authenticator', $this->prefix('authenticator'));
68: }
69: }
70:
71: if ($config['roles'] || $config['resources']) {
72: $authorizator = $container->addDefinition($this->prefix('authorizator'))
73: ->setClass('Nette\Security\IAuthorizator')
74: ->setFactory('Nette\Security\Permission');
75:
76: foreach ($config['roles'] as $role => $parents) {
77: $authorizator->addSetup('addRole', array($role, $parents));
78: }
79: foreach ($config['resources'] as $resource => $parents) {
80: $authorizator->addSetup('addResource', array($resource, $parents));
81: }
82:
83: if ($this->name === 'security') {
84: $container->addAlias('nette.authorizator', $this->prefix('authorizator'));
85: }
86: }
87:
88: if ($this->name === 'security') {
89: $container->addAlias('user', $this->prefix('user'));
90: $container->addAlias('nette.userStorage', $this->prefix('userStorage'));
91: }
92: }
93:
94: }
95: