|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Drupal\nidirect_prisons\Authentication\Provider; |
| 4 | + |
| 5 | +use Drupal\Core\Authentication\AuthenticationProviderInterface; |
| 6 | +use Symfony\Component\HttpFoundation\Request; |
| 7 | + |
| 8 | +/** |
| 9 | + * Provides authentication for requests using X-Auth-Token. |
| 10 | + */ |
| 11 | +class TokenAndIpAddressAuth implements AuthenticationProviderInterface { |
| 12 | + |
| 13 | + /** |
| 14 | + * {@inheritdoc} |
| 15 | + */ |
| 16 | + public function applies(Request $request) { |
| 17 | + // Do not apply to requests missing the X-Auth-Token header. |
| 18 | + if (!$request->headers->has('X-Auth-Token')) { |
| 19 | + return FALSE; |
| 20 | + } |
| 21 | + |
| 22 | + // Apply to endpoints under /api/{version}/prisoner-payments. |
| 23 | + $path = $request->getPathInfo(); |
| 24 | + return preg_match('#^/api/v\d+/prisoner-payments#', $path); |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * {@inheritdoc} |
| 29 | + */ |
| 30 | + public function authenticate(Request $request) { |
| 31 | + // Allowed tokens and IP addresses. |
| 32 | + $allowed_tokens = array_map('trim', explode(',', getenv('PRISONS_API_PERMITTED_TOKENS'))); |
| 33 | + $allowed_ip_addresses = array_map('trim', explode(',', getenv('PRISONS_API_PERMITTED_IPS'))); |
| 34 | + |
| 35 | + // Authentication fails if either token or IP is not allowed. |
| 36 | + $token = $request->headers->get('X-Auth-Token'); |
| 37 | + $client_ip = $request->getClientIp(); |
| 38 | + |
| 39 | + if (!in_array($token, $allowed_tokens)) { |
| 40 | + \Drupal::logger('nidirect_prisons')->debug('Supplied X-Auth-Token not found in PRISONS_API_PERMITTED_TOKENS'); |
| 41 | + return NULL; |
| 42 | + } |
| 43 | + |
| 44 | + if (!in_array($client_ip, $allowed_ip_addresses)) { |
| 45 | + \Drupal::logger('nidirect_prisons')->debug('IP address @client_ip not found in PRISONS_API_PERMITTED_IPS.', ['@client_ip' => $client_ip]); |
| 46 | + return NULL; |
| 47 | + } |
| 48 | + |
| 49 | + // IP and token are allowed. Return the nidirect_prisons_api_user. |
| 50 | + $username = 'nidirect_prisons_api_user'; |
| 51 | + $authenticated_user = user_load_by_name($username); |
| 52 | + |
| 53 | + if ($authenticated_user) { |
| 54 | + return $authenticated_user; |
| 55 | + } |
| 56 | + |
| 57 | + // There must have been a problem loading nidirect_prisons_api_user. |
| 58 | + \Drupal::logger('nidirect_prisons')->error('Service account with username @username could not be loaded.', ['@username' => $username]); |
| 59 | + |
| 60 | + // Authentication has failed. |
| 61 | + return NULL; |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments