FRED™  3.0
FRED™: Framework for Rapid and Easy Development
Http.php
Go to the documentation of this file.
1 <?php
2 
4 
5 class Http extends \Rsi\Fred\User\Authenticator{
6 
7  const EVENT_PASSWORD = 'user:authenticator:http:password';
8 
9  public $realm = 'FRED™';
10 
11  public function check(){
12  if(!$this->controllerName){
13  if(
14  ($data = $this->digest()) &&
15  $this->verify($data,$this->component('event')->trigger(self::EVENT_PASSWORD,$this,$data['username']))
16  ) return true;
17  $this->prompt();
18  $this->_fred->halt();
19  }
20  return null;
21  }
22 
23  public function invalidate(){
24  if($this->checked && !headers_sent()) http_response_code(401); //Unauthorized
25  parent::invalidate();
26  }
27  /**
28  * Send headers for the digest prompt.
29  */
30  public function prompt(){
31  http_response_code(401); //Unauthorized
32  header('WWW-Authenticate: Digest realm="' . $this->realm . '",qop="auth",nonce="' . uniqid() . '",opaque="' . $this->hash([$this->realm]) . '"');
33  }
34  /**
35  * Retrieve data from authentication digest.
36  * @return array Empty when digest not present not, false when incomplete.
37  */
38  public function digest(){
39  $data = [];
40  if(array_key_exists('PHP_AUTH_DIGEST',$_SERVER)) foreach(['nonce','nc','cnonce','qop','username','uri','response'] as $key)
41  if(preg_match('/' . $key . '=(?:([\'"])([^\\1]+?)\\1|([^\\s,]+))/',$_SERVER['PHP_AUTH_DIGEST'],$match)) $data[$key] = $match[2] ?: $match[3];
42  else return false;
43  return $data;
44  }
45 
46  protected function hash($data){
47  return md5(implode(':',$data));
48  }
49  /**
50  * Verify a password.
51  * @param array $data Data from digest().
52  * @param string $password Correct password for $data['username'].
53  * @return bool True when correct.
54  */
55  public function verify($data,$password){
56  $this->verified(($data['response'] == $this->hash([
57  $this->hash([$data['username'],$this->realm,$password]),
58  $data['nonce'],$data['nc'],$data['cnonce'],$data['qop'],
59  $this->hash([$_SERVER['REQUEST_METHOD'],$data['uri']])
60  ])) ?: null);
61  if(!$this->checked && !headers_sent()) http_response_code(401); //Unauthorized
62  return $this->checked;
63  }
64 
65 }
verify($data, $password)
Verify a password.
Definition: Http.php:55
digest()
Retrieve data from authentication digest.
Definition: Http.php:38
prompt()
Send headers for the digest prompt.
Definition: Http.php:30
verified($result)
Process the result of a verification.
component($name)
Get a component (local or default).
Definition: Component.php:80