| 1 |
<?php |
| 2 |
|
| 3 |
namespace Boxzilla\Licensing; |
| 4 |
|
| 5 |
class Authenticator { |
| 6 |
|
| 7 |
/** |
| 8 |
* @var string |
| 9 |
*/ |
| 10 |
protected $api_url; |
| 11 |
|
| 12 |
/** |
| 13 |
* @var License |
| 14 |
*/ |
| 15 |
protected $license; |
| 16 |
|
| 17 |
/** |
| 18 |
* Add the necessary Auth headers to all requests to our API |
| 19 |
* |
| 20 |
* @param $api_url |
| 21 |
* @param License $license |
| 22 |
*/ |
| 23 |
public function __construct( $api_url, License $license ) { |
| 24 |
$this->license = $license; |
| 25 |
$this->api_url = $api_url; |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Initialise the awesome |
| 30 |
*/ |
| 31 |
public function add_hooks() { |
| 32 |
add_filter( 'http_request_args', array( $this, 'add_auth_headers' ), 10, 2 ); |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* @param $args |
| 37 |
* @param $url |
| 38 |
* |
| 39 |
* @return mixed |
| 40 |
*/ |
| 41 |
public function add_auth_headers( $args, $url ) { |
| 42 |
|
| 43 |
if( strpos( $url, $this->api_url ) !== 0 ) { |
| 44 |
return $args; |
| 45 |
} |
| 46 |
|
| 47 |
$this->license->load(); |
| 48 |
|
| 49 |
if( empty( $args['headers'] ) ) { |
| 50 |
$args['headers'] = array(); |
| 51 |
} |
| 52 |
|
| 53 |
$args['headers']['Authorization'] = 'Bearer ' . urlencode( $this->license->key ); |
| 54 |
return $args; |
| 55 |
} |
| 56 |
} |