File.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. declare(strict_types=1);
  3. namespace Sabre\DAV\Auth\Backend;
  4. use Sabre\DAV;
  5. /**
  6. * This is an authentication backend that uses a file to manage passwords.
  7. *
  8. * The backend file must conform to Apache's htdigest format
  9. *
  10. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  11. * @author Evert Pot (http://evertpot.com/)
  12. * @license http://sabre.io/license/ Modified BSD License
  13. */
  14. class File extends AbstractDigest
  15. {
  16. /**
  17. * List of users.
  18. *
  19. * @var array
  20. */
  21. protected $users = [];
  22. /**
  23. * Creates the backend object.
  24. *
  25. * If the filename argument is passed in, it will parse out the specified file first.
  26. *
  27. * @param string|null $filename
  28. */
  29. public function __construct($filename = null)
  30. {
  31. if (!is_null($filename)) {
  32. $this->loadFile($filename);
  33. }
  34. }
  35. /**
  36. * Loads an htdigest-formatted file. This method can be called multiple times if
  37. * more than 1 file is used.
  38. *
  39. * @param string $filename
  40. */
  41. public function loadFile($filename)
  42. {
  43. foreach (file($filename, FILE_IGNORE_NEW_LINES) as $line) {
  44. if (2 !== substr_count($line, ':')) {
  45. throw new DAV\Exception('Malformed htdigest file. Every line should contain 2 colons');
  46. }
  47. list($username, $realm, $A1) = explode(':', $line);
  48. if (!preg_match('/^[a-zA-Z0-9]{32}$/', $A1)) {
  49. throw new DAV\Exception('Malformed htdigest file. Invalid md5 hash');
  50. }
  51. $this->users[$realm.':'.$username] = $A1;
  52. }
  53. }
  54. /**
  55. * Returns a users' information.
  56. *
  57. * @param string $realm
  58. * @param string $username
  59. *
  60. * @return string
  61. */
  62. public function getDigestHash($realm, $username)
  63. {
  64. return isset($this->users[$realm.':'.$username]) ? $this->users[$realm.':'.$username] : false;
  65. }
  66. }