1: <?php
2:
3: /*
4: * Library to use PortBilling events with PSR-14 event dispatch
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: * Abstract sase class for event call authentification
15: *
16: * @api
17: * @package Auth
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: * Set class to use custom auth header
32: *
33: * PortaBilling support use of custom header instead of 'Aithorization:'.
34: * If you use custom header, use this method. You may chain it as
35: * `(new AuthBasic($user,$pass))->withAuthHeader('Verify');`
36: *
37: * @param string $header - alternate auth header
38: * @return self for chaining
39: * @api
40: */
41: public function withAuthHeader(string $header): self
42: {
43: $this->authHeader = $header;
44: return $this;
45: }
46:
47: /**
48: * Perform authentification
49: *
50: * The method takes Event, retrieves auth data and perform authentification.
51: * - In a case of success it returns the Event itself.
52: * - In a case of failure it will throw EventException with code 401
53: *
54: * @param Event $event
55: * @return Event For chaining the methid with other methods
56: * @throws EventException with code 401 in a case of failure
57: * @api
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: * Abstract method to perform auth check
69: *
70: * Override this to implement exact auth method
71: *
72: * @throws EventException with code 401 in a case of authfailure
73: * @api
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: