Advertisement
Guest User

Untitled

a guest
Apr 21st, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. #!/usr/bin/env php
  2. <?php
  3. /**
  4. * Database auth helper for Squid in php using redis as a cache provider.
  5. * Jonathan Dizdarevic @dizzda
  6. */
  7.  
  8. //stream_set_blocking(STDIN, 0);
  9. //error_reporting(0);
  10.  
  11. set_time_limit(0);
  12.  
  13. $opts = [
  14. 'host:',
  15. 'database:',
  16. 'user:',
  17. 'password:',
  18. 'cache_ttl::'
  19. ];
  20. $options = getopt(null, $opts);
  21.  
  22. // Setting the cache TTL, 5 minutes by default
  23. define('CACHE_TTL', (int) ($options['cache_ttl'] ?? 300));
  24.  
  25.  
  26. if (extension_loaded('newrelic')) {
  27. newrelic_set_appname('squid_auth_' . $options['database']);
  28. }
  29.  
  30. // Connect to the DB
  31. $conn = new PDO(sprintf('mysql:host=%s;dbname=%s', $options['host'], $options['database']), $options['user'], $options['password'] ?? null);
  32.  
  33. $redis = new Redis();
  34. $redis->connect('127.0.0.1');
  35. $redis->setOption(Redis::OPT_SERIALIZER, defined('Redis::SERIALIZER_IGBINARY') ? Redis::SERIALIZER_IGBINARY : Redis::SERIALIZER_PHP);
  36.  
  37.  
  38. // When receiving an input
  39. while (false !== ($input = fgets(STDIN))) {
  40. // Split the username & the password
  41. $input = explode(' ', trim($input));
  42.  
  43. if (count($input) !== 2) {
  44. // avoid errors
  45. echo 'ERR login failure' . PHP_EOL;
  46. continue;
  47. }
  48. $username = $input[0];
  49. $password = $input[1];
  50.  
  51. $cacheId = sprintf('%s_%s[%s_%s][%s]', $options['database'], 'squid_cache', $username, $password, '1');
  52.  
  53. if ($cached = $redis->get($cacheId)) {
  54. echo $cached . PHP_EOL;
  55. continue;
  56. }
  57.  
  58. $sth = $conn->prepare('SELECT username FROM proxy_token WHERE username = :username AND password = :password AND is_enabled = 1');
  59. $sth->execute([
  60. ':username' => $username,
  61. ':password' => $password
  62. ]);
  63.  
  64. $result = $sth->fetchAll();
  65.  
  66. // Print the result to STDOUT
  67. if (count($result) !== 1) {
  68. echo 'ERR login failure' . PHP_EOL;
  69. $redis->setex($cacheId, CACHE_TTL, 'ERR login failure');
  70. } else {
  71. echo 'OK' . PHP_EOL;
  72. $redis->setex($cacheId, CACHE_TTL, 'OK');
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement