new: [CLI] Get authkey info by `cake user authkey`

pull/7996/head
Jakub Onderka 2021-11-25 18:15:22 +01:00
parent e6e716971a
commit 8d7df612f3
2 changed files with 68 additions and 9 deletions

View File

@ -19,6 +19,14 @@ class UserShell extends AppShell
],
]
]);
$parser->addSubcommand('authkey', [
'help' => __('Get information about given authkey.'),
'parser' => [
'arguments' => [
'authkey' => ['help' => __('Authentication key. If not provide, it will be read from STDIN.')],
],
]
]);
$parser->addSubcommand('block', [
'help' => __('Immediately block user.'),
'parser' => [
@ -111,6 +119,50 @@ class UserShell extends AppShell
}
}
public function authkey()
{
if (isset($this->args[0])) {
$authkey = $this->args[0];
} else {
$authkey = fgets(STDIN); // read line from STDIN
}
$authkey = trim($authkey);
if (strlen($authkey) !== 40) {
$this->error('Authkey has not valid format.');
}
if (Configure::read('Security.advanced_authkeys')) {
$user = $this->User->AuthKey->getAuthUserByAuthKey($authkey, true);
if (empty($user)) {
$this->error("Given authkey doesn't belong to any user.");
}
$isExpired = $user['authkey_expiration'] && $user['authkey_expiration'] < time();
$this->out($this->json([
'user_id' => $user['id'],
'email' => $user['email'],
'org_id' => $user['org_id'],
'authkey_id' => $user['authkey_id'],
'authkey_expiration' => $user['authkey_expiration'],
'authkey_expired' => $isExpired,
'allowed_ips' => $user['allowed_ips'],
'authkey_read_only' => $user['authkey_read_only'],
]));
$this->_stop($isExpired ? 2 : 0);
} else {
$user = $this->User->getAuthUserByAuthkey($authkey);
if (empty($user)) {
$this->error("Given authkey doesn't belong to any user.");
}
$this->out($this->json([
'user_id' => $user['id'],
'email' => $user['email'],
'org_id' => $user['org_id'],
]));
}
}
public function block()
{
list($userId) = $this->args;

View File

@ -129,23 +129,30 @@ class AuthKey extends AppModel
/**
* @param string $authkey
* @param bool $includeExpired
* @return array|false
*/
public function getAuthUserByAuthKey($authkey)
public function getAuthUserByAuthKey($authkey, $includeExpired = false)
{
$start = substr($authkey, 0, 4);
$end = substr($authkey, -4);
$conditions = [
'authkey_start' => $start,
'authkey_end' => $end,
];
if (!$includeExpired) {
$conditions['OR'] = [
'expiration >' => time(),
'expiration' => 0
];
}
$possibleAuthkeys = $this->find('all', [
'recursive' => -1,
'fields' => ['id', 'authkey', 'user_id', 'expiration', 'allowed_ips', 'read_only'],
'conditions' => [
'OR' => [
'expiration >' => time(),
'expiration' => 0
],
'authkey_start' => $start,
'authkey_end' => $end,
]
'conditions' => $conditions,
]);
$passwordHasher = $this->getHasher();
foreach ($possibleAuthkeys as $possibleAuthkey) {