1: | <?php |
2: | |
3: | |
4: | |
5: | |
6: | |
7: | namespace Porta\Psr14Event\Auth; |
8: | |
9: | use Porta\Psr14Event\Event; |
10: | use Psr\Http\Message\RequestInterface; |
11: | use Porta\Psr14Event\EventException; |
12: | |
13: | |
14: | |
15: | |
16: | |
17: | |
18: | |
19: | abstract class Auth implements AuthInterface |
20: | { |
21: | |
22: | const DATE_HEADER = 'Date'; |
23: | |
24: | protected $authHeader = 'Authorization'; |
25: | protected RequestInterface $request; |
26: | protected string $authType; |
27: | protected string $authValue; |
28: | protected string $dateHeader; |
29: | |
30: | |
31: | |
32: | |
33: | |
34: | |
35: | |
36: | |
37: | |
38: | |
39: | |
40: | |
41: | public function withAuthHeader(string $header): self |
42: | { |
43: | $this->authHeader = $header; |
44: | return $this; |
45: | } |
46: | |
47: | |
48: | |
49: | |
50: | |
51: | |
52: | |
53: | |
54: | |
55: | |
56: | |
57: | |
58: | |
59: | public function authentificate(Event $event): Event |
60: | { |
61: | $this->request = $event->getRequest(); |
62: | $this->parseData(); |
63: | $this->check(); |
64: | return $event; |
65: | } |
66: | |
67: | |
68: | |
69: | |
70: | |
71: | |
72: | |
73: | |
74: | |
75: | abstract protected function check(): void; |
76: | |
77: | protected function parseData(): void |
78: | { |
79: | $parts = explode(' ', $this->extractHeader($this->authHeader)); |
80: | if (count($parts) != 2) { |
81: | throw new EventException("Corrupted content of '" . $this->authHeader . "' header in the request", 401); |
82: | } |
83: | $this->authType = $parts[0]; |
84: | $this->authValue = $parts[1]; |
85: | $this->dateHeader = $this->extractHeader(self::DATE_HEADER); |
86: | } |
87: | |
88: | protected function extractHeader(string $headerName): string |
89: | { |
90: | $header = $this->request->getHeader($headerName); |
91: | if (count($header) != 1) { |
92: | throw new EventException("Missed or wrong '" . $headerName . "' header in the request", 401); |
93: | } |
94: | return $header[0]; |
95: | } |
96: | } |
97: | |