1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace App\Model;
13:
14: use Nette\Object,
15: Nette\Security as NS,
16: Nette\Security\Passwords,
17: App\Model\Database,
18: App\Lib\Table,
19: App\Lib\Statics\Cons,
20: App\Router\RouterFactory;
21:
22: 23: 24:
25: class Authenticator extends Object implements NS\IAuthenticator {
26:
27:
28: private $database;
29:
30: 31: 32:
33: public function __construct(Database $database) {
34: $this->database = $database;
35: }
36:
37: 38: 39: 40: 41:
42: public function authenticate(array $credentials) {
43: list($username, $password) = $credentials;
44: $row = (new Table(Cons::TABLE_USERS, $this->database))->data->where(Cons::COLUMN_USERNAME, $username)->fetch();
45: if (!$row) {
46: throw new NS\AuthenticationException('Špatné jméno nebo heslo.', self::IDENTITY_NOT_FOUND);
47: } else if ($this->password($row, $password)) {
48: return new NS\Identity($row->id, $this->getRoles($row->id), $this->getData($row));
49: }
50: }
51:
52: 53: 54: 55: 56:
57: public function getRoles($id) {
58: $roles = array();
59: $selection = (new Table(Cons::TABLE_USERS.'_'.Cons::TABLE_ROLES, $this->database))
60: ->data->where(Cons::TABLE_USERS.'_'.Cons::COLUMN_ID, $id);
61: foreach ($selection as $row) {
62: $roles[] = $row[Cons::TABLE_ACL.'_'.Cons::TABLE_ROLES][Cons::COLUMN_PATH];
63: }
64: return $roles;
65: }
66:
67: 68: 69: 70: 71: 72: 73:
74: private function password($user, $password) {
75: if (!Passwords::verify($password, $user[Cons::COLUMN_PASSWORD])) {
76: throw new NS\AuthenticationException('Špatné jméno nebo heslo.', self::INVALID_CREDENTIAL);
77: } elseif (Passwords::needsRehash($user[Cons::COLUMN_PASSWORD])) {
78: $user->update(array(Cons::COLUMN_PASSWORD => Passwords::hash($password)));
79: } elseif ($user[Cons::COLUMN_STATE] === 'Blocked') {
80: throw new NS\AuthenticationException('Uživatel byl zablokován', self::INVALID_CREDENTIAL);
81: } elseif($user[Cons::COLUMN_STATE] === 'Inactive'){
82: throw new NS\AuthenticationException('Uživatel není aktivní', self::INVALID_CREDENTIAL);
83: } else {
84: return true;
85: }
86: }
87:
88: 89: 90: 91: 92:
93: private function getData($userRow) {
94: $homepageRow = $userRow->ref(Cons::TABLE_SOURCE);
95: return array(
96: Cons::USER_LOGIN => $userRow[Cons::COLUMN_USERNAME],
97: Cons::USER_NAME => $userRow[Cons::COLUMN_FULLNAME],
98: Cons::USER_EMAIL => $userRow[Cons::COLUMN_EMAIL],
99: Cons::USER_HOME => RouterFactory::getRouteString($homepageRow),
100: Cons::USER_SOURCE => $userRow[Cons::TABLE_SOURCE.'_'.Cons::COLUMN_ID])
101: ;
102: }
103: }
104: