1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (https://nette.org)
5: * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6: */
7:
8: namespace Nette\Security;
9:
10: use Nette;
11:
12:
13: /**
14: * Trivial implementation of IAuthenticator.
15: */
16: class SimpleAuthenticator extends Nette\Object implements IAuthenticator
17: {
18: /** @var array */
19: private $userlist;
20:
21: /** @var array */
22: private $usersRoles;
23:
24:
25: /**
26: * @param array list of pairs username => password
27: * @param array list of pairs username => role[]
28: */
29: public function __construct(array $userlist, array $usersRoles = array())
30: {
31: $this->userlist = $userlist;
32: $this->usersRoles = $usersRoles;
33: }
34:
35:
36: /**
37: * Performs an authentication against e.g. database.
38: * and returns IIdentity on success or throws AuthenticationException
39: * @return IIdentity
40: * @throws AuthenticationException
41: */
42: public function authenticate(array $credentials)
43: {
44: list($username, $password) = $credentials;
45: foreach ($this->userlist as $name => $pass) {
46: if (strcasecmp($name, $username) === 0) {
47: if ((string) $pass === (string) $password) {
48: return new Identity($name, isset($this->usersRoles[$name]) ? $this->usersRoles[$name] : NULL);
49: } else {
50: throw new AuthenticationException('Invalid password.', self::INVALID_CREDENTIAL);
51: }
52: }
53: }
54: throw new AuthenticationException("User '$username' not found.", self::IDENTITY_NOT_FOUND);
55: }
56:
57: }
58: