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 implements IAuthenticator
17: {
18: use Nette\SmartObject;
19:
20: /** @var array */
21: private $userlist;
22:
23: /** @var array */
24: private $usersRoles;
25:
26:
27: /**
28: * @param array list of pairs username => password
29: * @param array list of pairs username => role[]
30: */
31: public function __construct(array $userlist, array $usersRoles = [])
32: {
33: $this->userlist = $userlist;
34: $this->usersRoles = $usersRoles;
35: }
36:
37:
38: /**
39: * Performs an authentication against e.g. database.
40: * and returns IIdentity on success or throws AuthenticationException
41: * @return IIdentity
42: * @throws AuthenticationException
43: */
44: public function authenticate(array $credentials)
45: {
46: list($username, $password) = $credentials;
47: foreach ($this->userlist as $name => $pass) {
48: if (strcasecmp($name, $username) === 0) {
49: if ((string) $pass === (string) $password) {
50: return new Identity($name, isset($this->usersRoles[$name]) ? $this->usersRoles[$name] : null);
51: } else {
52: throw new AuthenticationException('Invalid password.', self::INVALID_CREDENTIAL);
53: }
54: }
55: }
56: throw new AuthenticationException("User '$username' not found.", self::IDENTITY_NOT_FOUND);
57: }
58: }
59: