Guest User

Untitled

a guest
Jul 15th, 2018
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Kdyby\Security;
  4.  
  5. use Nette;
  6. use Kdyby;
  7.  
  8.  
  9. /**
  10. * Globální zámek pro aplikaci, vyžaduje auth handler, ideálně napojit http_authentication
  11. *
  12. * @author Filip Procházka <hosiplan@kdyby.org>
  13. */
  14. class ApplicationLock extends Nette\Object
  15. {
  16.  
  17. /** @var array */
  18. private $users;
  19.  
  20. /** @var Nette\Web\HttpRequest */
  21. private $httpRequest;
  22.  
  23. /** @var string */
  24. public $message = "Access denied";
  25.  
  26. /** @var string */
  27. public $realm = "test";
  28.  
  29.  
  30.  
  31. public function __construct()
  32. {
  33. $this->httpRequest = Nette\Environment::getHttpRequest();
  34. }
  35.  
  36.  
  37.  
  38. /**
  39. * @param string $name
  40. * @param string $pass
  41. */
  42. public function addUser($name, $pass)
  43. {
  44. $this->users[$name] = $pass;
  45. }
  46.  
  47.  
  48.  
  49. /**
  50. * @return Kdyby\Security\ApplicationLock
  51. */
  52. public function authorize()
  53. {
  54. $uri = $this->httpRequest->getUri();
  55.  
  56. if (!isset($uri->user) || !isset($uri->password)) {
  57. $this->kill();
  58. }
  59.  
  60. $user = $uri->user;
  61. $pass = $uri->password;
  62.  
  63. if (isset($this->users[$user]) && $this->users[$user] === $pass) {
  64. header('Content-Type: text/html; charset=utf-8');
  65. return $this;
  66. }
  67.  
  68. return $this->kill();
  69. }
  70.  
  71.  
  72.  
  73. private function kill()
  74. {
  75. header('Content-Type: text/plain; charset=utf-8');
  76. header('HTTP/1.1 401 Unauthorized');
  77. header('WWW-Authenticate: Basic realm="'.(string)$this->realm.'"');
  78. die((string)$this->message);
  79. }
  80.  
  81.  
  82.  
  83. /**
  84. * @param array $options
  85. * @return Kdyby\Security\ApplicationLock
  86. */
  87. public static function createApplicationLock($options)
  88. {
  89. $lock = new self;
  90.  
  91. foreach ((array)$options['user'] as $name => $pass) {
  92. //list($name, $pass) = explode('=', $user);
  93. $lock->addUser($name, $pass);
  94. }
  95.  
  96. $lock->message = isset($options['message']) ? $options['message'] : $lock->message;
  97. $lock->realm = isset($options['realm']) ? $options['realm'] : $lock->realm;
  98.  
  99. return $lock->authorize();
  100. }
  101.  
  102. }
Add Comment
Please, Sign In to add comment