Skip to content

Instantly share code, notes, and snippets.

@dizda
Created April 21, 2016 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dizda/3b028f7fef97d0158a33d7ec2404959f to your computer and use it in GitHub Desktop.
Save dizda/3b028f7fef97d0158a33d7ec2404959f to your computer and use it in GitHub Desktop.
Database auth helper for Squid in php using redis as a cache provider.
#!/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');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment