Merge pull request #8027 from JakubOnderka/cli_authkey_valid

new: [CLI] user authkey_valid command
pull/8039/head
Jakub Onderka 2021-12-17 18:02:42 +01:00 committed by GitHub
commit b05c4f90a9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 36 additions and 0 deletions

View File

@ -27,6 +27,9 @@ class UserShell extends AppShell
],
]
]);
$parser->addSubcommand('authkey_valid', [
'help' => __('Check if given authkey by STDIN is valid.'),
]);
$parser->addSubcommand('block', [
'help' => __('Immediately block user.'),
'parser' => [
@ -163,6 +166,39 @@ class UserShell extends AppShell
}
}
/**
* Reads line from stdin and checks if authkey is valid. Returns '1' to stdout if key is valid and '0' if not.
*/
public function authkey_valid()
{
$cache = [];
do {
$authkey = fgets(STDIN); // read line from STDIN
$authkey = trim($authkey);
if (strlen($authkey) !== 40) {
fwrite(STDOUT, "0\n"); // authkey is not in valid format
continue;
}
$time = time();
// Generate hash from authkey to not store raw authkey in memory
$keyHash = hash('sha256', $authkey, true);
if (isset($cache[$keyHash]) && $cache[$keyHash][1] > $time) {
fwrite(STDOUT, $cache[$keyHash][0] ? "1\n" : "0\n");
continue;
}
if (Configure::read('Security.advanced_authkeys')) {
$user = $this->User->AuthKey->getAuthUserByAuthKey($authkey);
} else {
$user = $this->User->getAuthUserByAuthkey($authkey);
}
$user = (bool)$user;
// Cache results for 5 seconds
$cache[$keyHash] = [$user, $time + 5];
fwrite(STDOUT, $user ? "1\n" : "0\n");
} while (true);
}
public function block()
{
list($userId) = $this->args;