e918e993966898aeccfed336f1be3c71217f1387
[phancap.git] / src / phancap / Authenticator.php
1 <?php
2 namespace phancap;
3
4 class Authenticator
5 {
6     public function authenticate(Config $config)
7     {
8         if ($config->access === false) {
9             throw new \Exception('Authentication not setup');
10         }
11         if ($config->access === true) {
12             //Access without restrictions allowed
13             return;
14         }
15
16         if (!isset($_GET['atoken'])) {
17             throw new \Exception('Parameter missing: atoken');
18         }
19         if (!isset($_GET['asignature'])) {
20             throw new \Exception('Parameter missing: asignature');
21         }
22         if (!isset($_GET['atimestamp'])) {
23             throw new \Exception('Parameter missing: atimestamp');
24         }
25
26         $token = $_GET['atoken'];
27         if (!array_key_exists($token, $config->access)) {
28             throw new \Exception('Unknown atoken');
29         }
30
31         $timestamp = (int) $_GET['atimestamp'];
32         if ($timestamp + $config->timestampLifetime < time()) {
33             throw new \Exception('atimestamp too old');
34         }
35
36         $signature = $_GET['asignature'];
37
38         $params = $_GET;
39         unset($params['asignature']);
40         $sigdata = $this->getSignatureData($params);
41
42         $verifiedSignature = hash_hmac('sha1', $sigdata, $config->access[$token]);
43         if ($signature !== $verifiedSignature) {
44             throw new \Exception('Invalid signature');
45         }
46     }
47
48
49     protected function getSignatureData($params)
50     {
51         ksort($params);
52         $encparams = array();
53         foreach ($params as $key => $value) {
54             $encparams[] = $key . '=' . rawurlencode($value);
55         }
56         return implode('&', $encparams);
57     }
58 }
59 ?>