Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env php
- <?php
- /**
- * Database auth helper for Squid in php using redis as a cache provider.
- * Jonathan Dizdarevic @dizzda
- */
- //stream_set_blocking(STDIN, 0);
- //error_reporting(0);
- set_time_limit(0);
- $opts = [
- 'host:',
- 'database:',
- 'user:',
- 'password:',
- 'cache_ttl::'
- ];
- $options = getopt(null, $opts);
- // Setting the cache TTL, 5 minutes by default
- define('CACHE_TTL', (int) ($options['cache_ttl'] ?? 300));
- if (extension_loaded('newrelic')) {
- newrelic_set_appname('squid_auth_' . $options['database']);
- }
- // Connect to the DB
- $conn = new PDO(sprintf('mysql:host=%s;dbname=%s', $options['host'], $options['database']), $options['user'], $options['password'] ?? null);
- $redis = new Redis();
- $redis->connect('127.0.0.1');
- $redis->setOption(Redis::OPT_SERIALIZER, defined('Redis::SERIALIZER_IGBINARY') ? Redis::SERIALIZER_IGBINARY : Redis::SERIALIZER_PHP);
- // When receiving an input
- while (false !== ($input = fgets(STDIN))) {
- // Split the username & the password
- $input = explode(' ', trim($input));
- if (count($input) !== 2) {
- // avoid errors
- echo 'ERR login failure' . PHP_EOL;
- continue;
- }
- $username = $input[0];
- $password = $input[1];
- $cacheId = sprintf('%s_%s[%s_%s][%s]', $options['database'], 'squid_cache', $username, $password, '1');
- if ($cached = $redis->get($cacheId)) {
- echo $cached . PHP_EOL;
- continue;
- }
- $sth = $conn->prepare('SELECT username FROM proxy_token WHERE username = :username AND password = :password AND is_enabled = 1');
- $sth->execute([
- ':username' => $username,
- ':password' => $password
- ]);
- $result = $sth->fetchAll();
- // Print the result to STDOUT
- if (count($result) !== 1) {
- echo 'ERR login failure' . PHP_EOL;
- $redis->setex($cacheId, CACHE_TTL, 'ERR login failure');
- } else {
- echo 'OK' . PHP_EOL;
- $redis->setex($cacheId, CACHE_TTL, 'OK');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement